three.module.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '152';
  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. /** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */
  146. const LinearEncoding = 3000;
  147. /** @deprecated Use SRGBColorSpace in three.js r152+. */
  148. const sRGBEncoding = 3001;
  149. const BasicDepthPacking = 3200;
  150. const RGBADepthPacking = 3201;
  151. const TangentSpaceNormalMap = 0;
  152. const ObjectSpaceNormalMap = 1;
  153. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  154. const NoColorSpace = '';
  155. const SRGBColorSpace = 'srgb';
  156. const LinearSRGBColorSpace = 'srgb-linear';
  157. const DisplayP3ColorSpace = 'display-p3';
  158. const ZeroStencilOp = 0;
  159. const KeepStencilOp = 7680;
  160. const ReplaceStencilOp = 7681;
  161. const IncrementStencilOp = 7682;
  162. const DecrementStencilOp = 7683;
  163. const IncrementWrapStencilOp = 34055;
  164. const DecrementWrapStencilOp = 34056;
  165. const InvertStencilOp = 5386;
  166. const NeverStencilFunc = 512;
  167. const LessStencilFunc = 513;
  168. const EqualStencilFunc = 514;
  169. const LessEqualStencilFunc = 515;
  170. const GreaterStencilFunc = 516;
  171. const NotEqualStencilFunc = 517;
  172. const GreaterEqualStencilFunc = 518;
  173. const AlwaysStencilFunc = 519;
  174. const StaticDrawUsage = 35044;
  175. const DynamicDrawUsage = 35048;
  176. const StreamDrawUsage = 35040;
  177. const StaticReadUsage = 35045;
  178. const DynamicReadUsage = 35049;
  179. const StreamReadUsage = 35041;
  180. const StaticCopyUsage = 35046;
  181. const DynamicCopyUsage = 35050;
  182. const StreamCopyUsage = 35042;
  183. const GLSL1 = '100';
  184. const GLSL3 = '300 es';
  185. const _SRGBAFormat = 1035; // fallback for WebGL 1
  186. /**
  187. * https://github.com/mrdoob/eventdispatcher.js/
  188. */
  189. class EventDispatcher {
  190. addEventListener( type, listener ) {
  191. if ( this._listeners === undefined ) this._listeners = {};
  192. const listeners = this._listeners;
  193. if ( listeners[ type ] === undefined ) {
  194. listeners[ type ] = [];
  195. }
  196. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  197. listeners[ type ].push( listener );
  198. }
  199. }
  200. hasEventListener( type, listener ) {
  201. if ( this._listeners === undefined ) return false;
  202. const listeners = this._listeners;
  203. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  204. }
  205. removeEventListener( type, listener ) {
  206. if ( this._listeners === undefined ) return;
  207. const listeners = this._listeners;
  208. const listenerArray = listeners[ type ];
  209. if ( listenerArray !== undefined ) {
  210. const index = listenerArray.indexOf( listener );
  211. if ( index !== - 1 ) {
  212. listenerArray.splice( index, 1 );
  213. }
  214. }
  215. }
  216. dispatchEvent( event ) {
  217. if ( this._listeners === undefined ) return;
  218. const listeners = this._listeners;
  219. const listenerArray = listeners[ event.type ];
  220. if ( listenerArray !== undefined ) {
  221. event.target = this;
  222. // Make a copy, in case listeners are removed while iterating.
  223. const array = listenerArray.slice( 0 );
  224. for ( let i = 0, l = array.length; i < l; i ++ ) {
  225. array[ i ].call( this, event );
  226. }
  227. event.target = null;
  228. }
  229. }
  230. }
  231. 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' ];
  232. let _seed = 1234567;
  233. const DEG2RAD = Math.PI / 180;
  234. const RAD2DEG = 180 / Math.PI;
  235. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  236. function generateUUID() {
  237. const d0 = Math.random() * 0xffffffff | 0;
  238. const d1 = Math.random() * 0xffffffff | 0;
  239. const d2 = Math.random() * 0xffffffff | 0;
  240. const d3 = Math.random() * 0xffffffff | 0;
  241. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  242. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  243. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  244. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  245. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  246. return uuid.toLowerCase();
  247. }
  248. function clamp( value, min, max ) {
  249. return Math.max( min, Math.min( max, value ) );
  250. }
  251. // compute euclidean modulo of m % n
  252. // https://en.wikipedia.org/wiki/Modulo_operation
  253. function euclideanModulo( n, m ) {
  254. return ( ( n % m ) + m ) % m;
  255. }
  256. // Linear mapping from range <a1, a2> to range <b1, b2>
  257. function mapLinear( x, a1, a2, b1, b2 ) {
  258. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  259. }
  260. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  261. function inverseLerp( x, y, value ) {
  262. if ( x !== y ) {
  263. return ( value - x ) / ( y - x );
  264. } else {
  265. return 0;
  266. }
  267. }
  268. // https://en.wikipedia.org/wiki/Linear_interpolation
  269. function lerp( x, y, t ) {
  270. return ( 1 - t ) * x + t * y;
  271. }
  272. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  273. function damp( x, y, lambda, dt ) {
  274. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  275. }
  276. // https://www.desmos.com/calculator/vcsjnyz7x4
  277. function pingpong( x, length = 1 ) {
  278. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  279. }
  280. // http://en.wikipedia.org/wiki/Smoothstep
  281. function smoothstep( x, min, max ) {
  282. if ( x <= min ) return 0;
  283. if ( x >= max ) return 1;
  284. x = ( x - min ) / ( max - min );
  285. return x * x * ( 3 - 2 * x );
  286. }
  287. function smootherstep( x, min, max ) {
  288. if ( x <= min ) return 0;
  289. if ( x >= max ) return 1;
  290. x = ( x - min ) / ( max - min );
  291. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  292. }
  293. // Random integer from <low, high> interval
  294. function randInt( low, high ) {
  295. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  296. }
  297. // Random float from <low, high> interval
  298. function randFloat( low, high ) {
  299. return low + Math.random() * ( high - low );
  300. }
  301. // Random float from <-range/2, range/2> interval
  302. function randFloatSpread( range ) {
  303. return range * ( 0.5 - Math.random() );
  304. }
  305. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  306. function seededRandom( s ) {
  307. if ( s !== undefined ) _seed = s;
  308. // Mulberry32 generator
  309. let t = _seed += 0x6D2B79F5;
  310. t = Math.imul( t ^ t >>> 15, t | 1 );
  311. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  312. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  313. }
  314. function degToRad( degrees ) {
  315. return degrees * DEG2RAD;
  316. }
  317. function radToDeg( radians ) {
  318. return radians * RAD2DEG;
  319. }
  320. function isPowerOfTwo( value ) {
  321. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  322. }
  323. function ceilPowerOfTwo( value ) {
  324. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  325. }
  326. function floorPowerOfTwo( value ) {
  327. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  328. }
  329. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  330. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  331. // rotations are applied to the axes in the order specified by 'order'
  332. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  333. // angles are in radians
  334. const cos = Math.cos;
  335. const sin = Math.sin;
  336. const c2 = cos( b / 2 );
  337. const s2 = sin( b / 2 );
  338. const c13 = cos( ( a + c ) / 2 );
  339. const s13 = sin( ( a + c ) / 2 );
  340. const c1_3 = cos( ( a - c ) / 2 );
  341. const s1_3 = sin( ( a - c ) / 2 );
  342. const c3_1 = cos( ( c - a ) / 2 );
  343. const s3_1 = sin( ( c - a ) / 2 );
  344. switch ( order ) {
  345. case 'XYX':
  346. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  347. break;
  348. case 'YZY':
  349. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  350. break;
  351. case 'ZXZ':
  352. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  353. break;
  354. case 'XZX':
  355. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  356. break;
  357. case 'YXY':
  358. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  359. break;
  360. case 'ZYZ':
  361. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  362. break;
  363. default:
  364. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  365. }
  366. }
  367. function denormalize( value, array ) {
  368. switch ( array.constructor ) {
  369. case Float32Array:
  370. return value;
  371. case Uint16Array:
  372. return value / 65535.0;
  373. case Uint8Array:
  374. return value / 255.0;
  375. case Int16Array:
  376. return Math.max( value / 32767.0, - 1.0 );
  377. case Int8Array:
  378. return Math.max( value / 127.0, - 1.0 );
  379. default:
  380. throw new Error( 'Invalid component type.' );
  381. }
  382. }
  383. function normalize( value, array ) {
  384. switch ( array.constructor ) {
  385. case Float32Array:
  386. return value;
  387. case Uint16Array:
  388. return Math.round( value * 65535.0 );
  389. case Uint8Array:
  390. return Math.round( value * 255.0 );
  391. case Int16Array:
  392. return Math.round( value * 32767.0 );
  393. case Int8Array:
  394. return Math.round( value * 127.0 );
  395. default:
  396. throw new Error( 'Invalid component type.' );
  397. }
  398. }
  399. const MathUtils = {
  400. DEG2RAD: DEG2RAD,
  401. RAD2DEG: RAD2DEG,
  402. generateUUID: generateUUID,
  403. clamp: clamp,
  404. euclideanModulo: euclideanModulo,
  405. mapLinear: mapLinear,
  406. inverseLerp: inverseLerp,
  407. lerp: lerp,
  408. damp: damp,
  409. pingpong: pingpong,
  410. smoothstep: smoothstep,
  411. smootherstep: smootherstep,
  412. randInt: randInt,
  413. randFloat: randFloat,
  414. randFloatSpread: randFloatSpread,
  415. seededRandom: seededRandom,
  416. degToRad: degToRad,
  417. radToDeg: radToDeg,
  418. isPowerOfTwo: isPowerOfTwo,
  419. ceilPowerOfTwo: ceilPowerOfTwo,
  420. floorPowerOfTwo: floorPowerOfTwo,
  421. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  422. normalize: normalize,
  423. denormalize: denormalize
  424. };
  425. class Vector2 {
  426. constructor( x = 0, y = 0 ) {
  427. Vector2.prototype.isVector2 = true;
  428. this.x = x;
  429. this.y = y;
  430. }
  431. get width() {
  432. return this.x;
  433. }
  434. set width( value ) {
  435. this.x = value;
  436. }
  437. get height() {
  438. return this.y;
  439. }
  440. set height( value ) {
  441. this.y = value;
  442. }
  443. set( x, y ) {
  444. this.x = x;
  445. this.y = y;
  446. return this;
  447. }
  448. setScalar( scalar ) {
  449. this.x = scalar;
  450. this.y = scalar;
  451. return this;
  452. }
  453. setX( x ) {
  454. this.x = x;
  455. return this;
  456. }
  457. setY( y ) {
  458. this.y = y;
  459. return this;
  460. }
  461. setComponent( index, value ) {
  462. switch ( index ) {
  463. case 0: this.x = value; break;
  464. case 1: this.y = value; break;
  465. default: throw new Error( 'index is out of range: ' + index );
  466. }
  467. return this;
  468. }
  469. getComponent( index ) {
  470. switch ( index ) {
  471. case 0: return this.x;
  472. case 1: return this.y;
  473. default: throw new Error( 'index is out of range: ' + index );
  474. }
  475. }
  476. clone() {
  477. return new this.constructor( this.x, this.y );
  478. }
  479. copy( v ) {
  480. this.x = v.x;
  481. this.y = v.y;
  482. return this;
  483. }
  484. add( v ) {
  485. this.x += v.x;
  486. this.y += v.y;
  487. return this;
  488. }
  489. addScalar( s ) {
  490. this.x += s;
  491. this.y += s;
  492. return this;
  493. }
  494. addVectors( a, b ) {
  495. this.x = a.x + b.x;
  496. this.y = a.y + b.y;
  497. return this;
  498. }
  499. addScaledVector( v, s ) {
  500. this.x += v.x * s;
  501. this.y += v.y * s;
  502. return this;
  503. }
  504. sub( v ) {
  505. this.x -= v.x;
  506. this.y -= v.y;
  507. return this;
  508. }
  509. subScalar( s ) {
  510. this.x -= s;
  511. this.y -= s;
  512. return this;
  513. }
  514. subVectors( a, b ) {
  515. this.x = a.x - b.x;
  516. this.y = a.y - b.y;
  517. return this;
  518. }
  519. multiply( v ) {
  520. this.x *= v.x;
  521. this.y *= v.y;
  522. return this;
  523. }
  524. multiplyScalar( scalar ) {
  525. this.x *= scalar;
  526. this.y *= scalar;
  527. return this;
  528. }
  529. divide( v ) {
  530. this.x /= v.x;
  531. this.y /= v.y;
  532. return this;
  533. }
  534. divideScalar( scalar ) {
  535. return this.multiplyScalar( 1 / scalar );
  536. }
  537. applyMatrix3( m ) {
  538. const x = this.x, y = this.y;
  539. const e = m.elements;
  540. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  541. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  542. return this;
  543. }
  544. min( v ) {
  545. this.x = Math.min( this.x, v.x );
  546. this.y = Math.min( this.y, v.y );
  547. return this;
  548. }
  549. max( v ) {
  550. this.x = Math.max( this.x, v.x );
  551. this.y = Math.max( this.y, v.y );
  552. return this;
  553. }
  554. clamp( min, max ) {
  555. // assumes min < max, componentwise
  556. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  557. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  558. return this;
  559. }
  560. clampScalar( minVal, maxVal ) {
  561. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  562. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  563. return this;
  564. }
  565. clampLength( min, max ) {
  566. const length = this.length();
  567. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  568. }
  569. floor() {
  570. this.x = Math.floor( this.x );
  571. this.y = Math.floor( this.y );
  572. return this;
  573. }
  574. ceil() {
  575. this.x = Math.ceil( this.x );
  576. this.y = Math.ceil( this.y );
  577. return this;
  578. }
  579. round() {
  580. this.x = Math.round( this.x );
  581. this.y = Math.round( this.y );
  582. return this;
  583. }
  584. roundToZero() {
  585. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  586. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  587. return this;
  588. }
  589. negate() {
  590. this.x = - this.x;
  591. this.y = - this.y;
  592. return this;
  593. }
  594. dot( v ) {
  595. return this.x * v.x + this.y * v.y;
  596. }
  597. cross( v ) {
  598. return this.x * v.y - this.y * v.x;
  599. }
  600. lengthSq() {
  601. return this.x * this.x + this.y * this.y;
  602. }
  603. length() {
  604. return Math.sqrt( this.x * this.x + this.y * this.y );
  605. }
  606. manhattanLength() {
  607. return Math.abs( this.x ) + Math.abs( this.y );
  608. }
  609. normalize() {
  610. return this.divideScalar( this.length() || 1 );
  611. }
  612. angle() {
  613. // computes the angle in radians with respect to the positive x-axis
  614. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  615. return angle;
  616. }
  617. angleTo( v ) {
  618. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  619. if ( denominator === 0 ) return Math.PI / 2;
  620. const theta = this.dot( v ) / denominator;
  621. // clamp, to handle numerical problems
  622. return Math.acos( clamp( theta, - 1, 1 ) );
  623. }
  624. distanceTo( v ) {
  625. return Math.sqrt( this.distanceToSquared( v ) );
  626. }
  627. distanceToSquared( v ) {
  628. const dx = this.x - v.x, dy = this.y - v.y;
  629. return dx * dx + dy * dy;
  630. }
  631. manhattanDistanceTo( v ) {
  632. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  633. }
  634. setLength( length ) {
  635. return this.normalize().multiplyScalar( length );
  636. }
  637. lerp( v, alpha ) {
  638. this.x += ( v.x - this.x ) * alpha;
  639. this.y += ( v.y - this.y ) * alpha;
  640. return this;
  641. }
  642. lerpVectors( v1, v2, alpha ) {
  643. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  644. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  645. return this;
  646. }
  647. equals( v ) {
  648. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  649. }
  650. fromArray( array, offset = 0 ) {
  651. this.x = array[ offset ];
  652. this.y = array[ offset + 1 ];
  653. return this;
  654. }
  655. toArray( array = [], offset = 0 ) {
  656. array[ offset ] = this.x;
  657. array[ offset + 1 ] = this.y;
  658. return array;
  659. }
  660. fromBufferAttribute( attribute, index ) {
  661. this.x = attribute.getX( index );
  662. this.y = attribute.getY( index );
  663. return this;
  664. }
  665. rotateAround( center, angle ) {
  666. const c = Math.cos( angle ), s = Math.sin( angle );
  667. const x = this.x - center.x;
  668. const y = this.y - center.y;
  669. this.x = x * c - y * s + center.x;
  670. this.y = x * s + y * c + center.y;
  671. return this;
  672. }
  673. random() {
  674. this.x = Math.random();
  675. this.y = Math.random();
  676. return this;
  677. }
  678. *[ Symbol.iterator ]() {
  679. yield this.x;
  680. yield this.y;
  681. }
  682. }
  683. class Matrix3 {
  684. constructor() {
  685. Matrix3.prototype.isMatrix3 = true;
  686. this.elements = [
  687. 1, 0, 0,
  688. 0, 1, 0,
  689. 0, 0, 1
  690. ];
  691. }
  692. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  693. const te = this.elements;
  694. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  695. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  696. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  697. return this;
  698. }
  699. identity() {
  700. this.set(
  701. 1, 0, 0,
  702. 0, 1, 0,
  703. 0, 0, 1
  704. );
  705. return this;
  706. }
  707. copy( m ) {
  708. const te = this.elements;
  709. const me = m.elements;
  710. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  711. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  712. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  713. return this;
  714. }
  715. extractBasis( xAxis, yAxis, zAxis ) {
  716. xAxis.setFromMatrix3Column( this, 0 );
  717. yAxis.setFromMatrix3Column( this, 1 );
  718. zAxis.setFromMatrix3Column( this, 2 );
  719. return this;
  720. }
  721. setFromMatrix4( m ) {
  722. const me = m.elements;
  723. this.set(
  724. me[ 0 ], me[ 4 ], me[ 8 ],
  725. me[ 1 ], me[ 5 ], me[ 9 ],
  726. me[ 2 ], me[ 6 ], me[ 10 ]
  727. );
  728. return this;
  729. }
  730. multiply( m ) {
  731. return this.multiplyMatrices( this, m );
  732. }
  733. premultiply( m ) {
  734. return this.multiplyMatrices( m, this );
  735. }
  736. multiplyMatrices( a, b ) {
  737. const ae = a.elements;
  738. const be = b.elements;
  739. const te = this.elements;
  740. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  741. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  742. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  743. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  744. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  745. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  746. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  747. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  748. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  749. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  750. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  751. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  752. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  753. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  754. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  755. return this;
  756. }
  757. multiplyScalar( s ) {
  758. const te = this.elements;
  759. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  760. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  761. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  762. return this;
  763. }
  764. determinant() {
  765. const te = this.elements;
  766. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  767. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  768. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  769. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  770. }
  771. invert() {
  772. const te = this.elements,
  773. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  774. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  775. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  776. t11 = n33 * n22 - n32 * n23,
  777. t12 = n32 * n13 - n33 * n12,
  778. t13 = n23 * n12 - n22 * n13,
  779. det = n11 * t11 + n21 * t12 + n31 * t13;
  780. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  781. const detInv = 1 / det;
  782. te[ 0 ] = t11 * detInv;
  783. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  784. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  785. te[ 3 ] = t12 * detInv;
  786. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  787. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  788. te[ 6 ] = t13 * detInv;
  789. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  790. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  791. return this;
  792. }
  793. transpose() {
  794. let tmp;
  795. const m = this.elements;
  796. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  797. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  798. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  799. return this;
  800. }
  801. getNormalMatrix( matrix4 ) {
  802. return this.setFromMatrix4( matrix4 ).invert().transpose();
  803. }
  804. transposeIntoArray( r ) {
  805. const m = this.elements;
  806. r[ 0 ] = m[ 0 ];
  807. r[ 1 ] = m[ 3 ];
  808. r[ 2 ] = m[ 6 ];
  809. r[ 3 ] = m[ 1 ];
  810. r[ 4 ] = m[ 4 ];
  811. r[ 5 ] = m[ 7 ];
  812. r[ 6 ] = m[ 2 ];
  813. r[ 7 ] = m[ 5 ];
  814. r[ 8 ] = m[ 8 ];
  815. return this;
  816. }
  817. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  818. const c = Math.cos( rotation );
  819. const s = Math.sin( rotation );
  820. this.set(
  821. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  822. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  823. 0, 0, 1
  824. );
  825. return this;
  826. }
  827. //
  828. scale( sx, sy ) {
  829. this.premultiply( _m3.makeScale( sx, sy ) );
  830. return this;
  831. }
  832. rotate( theta ) {
  833. this.premultiply( _m3.makeRotation( - theta ) );
  834. return this;
  835. }
  836. translate( tx, ty ) {
  837. this.premultiply( _m3.makeTranslation( tx, ty ) );
  838. return this;
  839. }
  840. // for 2D Transforms
  841. makeTranslation( x, y ) {
  842. this.set(
  843. 1, 0, x,
  844. 0, 1, y,
  845. 0, 0, 1
  846. );
  847. return this;
  848. }
  849. makeRotation( theta ) {
  850. // counterclockwise
  851. const c = Math.cos( theta );
  852. const s = Math.sin( theta );
  853. this.set(
  854. c, - s, 0,
  855. s, c, 0,
  856. 0, 0, 1
  857. );
  858. return this;
  859. }
  860. makeScale( x, y ) {
  861. this.set(
  862. x, 0, 0,
  863. 0, y, 0,
  864. 0, 0, 1
  865. );
  866. return this;
  867. }
  868. //
  869. equals( matrix ) {
  870. const te = this.elements;
  871. const me = matrix.elements;
  872. for ( let i = 0; i < 9; i ++ ) {
  873. if ( te[ i ] !== me[ i ] ) return false;
  874. }
  875. return true;
  876. }
  877. fromArray( array, offset = 0 ) {
  878. for ( let i = 0; i < 9; i ++ ) {
  879. this.elements[ i ] = array[ i + offset ];
  880. }
  881. return this;
  882. }
  883. toArray( array = [], offset = 0 ) {
  884. const te = this.elements;
  885. array[ offset ] = te[ 0 ];
  886. array[ offset + 1 ] = te[ 1 ];
  887. array[ offset + 2 ] = te[ 2 ];
  888. array[ offset + 3 ] = te[ 3 ];
  889. array[ offset + 4 ] = te[ 4 ];
  890. array[ offset + 5 ] = te[ 5 ];
  891. array[ offset + 6 ] = te[ 6 ];
  892. array[ offset + 7 ] = te[ 7 ];
  893. array[ offset + 8 ] = te[ 8 ];
  894. return array;
  895. }
  896. clone() {
  897. return new this.constructor().fromArray( this.elements );
  898. }
  899. }
  900. const _m3 = /*@__PURE__*/ new Matrix3();
  901. function arrayNeedsUint32( array ) {
  902. // assumes larger values usually on last
  903. for ( let i = array.length - 1; i >= 0; -- i ) {
  904. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  905. }
  906. return false;
  907. }
  908. const TYPED_ARRAYS = {
  909. Int8Array: Int8Array,
  910. Uint8Array: Uint8Array,
  911. Uint8ClampedArray: Uint8ClampedArray,
  912. Int16Array: Int16Array,
  913. Uint16Array: Uint16Array,
  914. Int32Array: Int32Array,
  915. Uint32Array: Uint32Array,
  916. Float32Array: Float32Array,
  917. Float64Array: Float64Array
  918. };
  919. function getTypedArray( type, buffer ) {
  920. return new TYPED_ARRAYS[ type ]( buffer );
  921. }
  922. function createElementNS( name ) {
  923. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  924. }
  925. const _cache = {};
  926. function warnOnce( message ) {
  927. if ( message in _cache ) return;
  928. _cache[ message ] = true;
  929. console.warn( message );
  930. }
  931. function SRGBToLinear( c ) {
  932. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  933. }
  934. function LinearToSRGB( c ) {
  935. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  936. }
  937. /**
  938. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  939. * or clipping. Based on W3C specifications for sRGB and Display P3,
  940. * and ICC specifications for the D50 connection space. Values in/out
  941. * are _linear_ sRGB and _linear_ Display P3.
  942. *
  943. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  944. *
  945. * Reference:
  946. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  947. */
  948. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [
  949. 0.8224621, 0.0331941, 0.0170827,
  950. 0.1775380, 0.9668058, 0.0723974,
  951. - 0.0000001, 0.0000001, 0.9105199
  952. ] );
  953. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [
  954. 1.2249401, - 0.0420569, - 0.0196376,
  955. - 0.2249404, 1.0420571, - 0.0786361,
  956. 0.0000001, 0.0000000, 1.0982735
  957. ] );
  958. function DisplayP3ToLinearSRGB( color ) {
  959. // Display P3 uses the sRGB transfer functions
  960. return color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  961. }
  962. function LinearSRGBToDisplayP3( color ) {
  963. // Display P3 uses the sRGB transfer functions
  964. return color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB();
  965. }
  966. // Conversions from <source> to Linear-sRGB reference space.
  967. const TO_LINEAR = {
  968. [ LinearSRGBColorSpace ]: ( color ) => color,
  969. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  970. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  971. };
  972. // Conversions to <target> from Linear-sRGB reference space.
  973. const FROM_LINEAR = {
  974. [ LinearSRGBColorSpace ]: ( color ) => color,
  975. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  976. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  977. };
  978. const ColorManagement = {
  979. enabled: true,
  980. get legacyMode() {
  981. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  982. return ! this.enabled;
  983. },
  984. set legacyMode( legacyMode ) {
  985. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  986. this.enabled = ! legacyMode;
  987. },
  988. get workingColorSpace() {
  989. return LinearSRGBColorSpace;
  990. },
  991. set workingColorSpace( colorSpace ) {
  992. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  993. },
  994. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  995. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  996. return color;
  997. }
  998. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  999. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  1000. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  1001. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  1002. }
  1003. return targetFromLinear( sourceToLinear( color ) );
  1004. },
  1005. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1006. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1007. },
  1008. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1009. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1010. },
  1011. };
  1012. let _canvas;
  1013. class ImageUtils {
  1014. static getDataURL( image ) {
  1015. if ( /^data:/i.test( image.src ) ) {
  1016. return image.src;
  1017. }
  1018. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1019. return image.src;
  1020. }
  1021. let canvas;
  1022. if ( image instanceof HTMLCanvasElement ) {
  1023. canvas = image;
  1024. } else {
  1025. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1026. _canvas.width = image.width;
  1027. _canvas.height = image.height;
  1028. const context = _canvas.getContext( '2d' );
  1029. if ( image instanceof ImageData ) {
  1030. context.putImageData( image, 0, 0 );
  1031. } else {
  1032. context.drawImage( image, 0, 0, image.width, image.height );
  1033. }
  1034. canvas = _canvas;
  1035. }
  1036. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1037. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1038. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1039. } else {
  1040. return canvas.toDataURL( 'image/png' );
  1041. }
  1042. }
  1043. static sRGBToLinear( image ) {
  1044. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1045. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1046. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1047. const canvas = createElementNS( 'canvas' );
  1048. canvas.width = image.width;
  1049. canvas.height = image.height;
  1050. const context = canvas.getContext( '2d' );
  1051. context.drawImage( image, 0, 0, image.width, image.height );
  1052. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1053. const data = imageData.data;
  1054. for ( let i = 0; i < data.length; i ++ ) {
  1055. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1056. }
  1057. context.putImageData( imageData, 0, 0 );
  1058. return canvas;
  1059. } else if ( image.data ) {
  1060. const data = image.data.slice( 0 );
  1061. for ( let i = 0; i < data.length; i ++ ) {
  1062. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1063. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1064. } else {
  1065. // assuming float
  1066. data[ i ] = SRGBToLinear( data[ i ] );
  1067. }
  1068. }
  1069. return {
  1070. data: data,
  1071. width: image.width,
  1072. height: image.height
  1073. };
  1074. } else {
  1075. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1076. return image;
  1077. }
  1078. }
  1079. }
  1080. class Source {
  1081. constructor( data = null ) {
  1082. this.isSource = true;
  1083. this.uuid = generateUUID();
  1084. this.data = data;
  1085. this.version = 0;
  1086. }
  1087. set needsUpdate( value ) {
  1088. if ( value === true ) this.version ++;
  1089. }
  1090. toJSON( meta ) {
  1091. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1092. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1093. return meta.images[ this.uuid ];
  1094. }
  1095. const output = {
  1096. uuid: this.uuid,
  1097. url: ''
  1098. };
  1099. const data = this.data;
  1100. if ( data !== null ) {
  1101. let url;
  1102. if ( Array.isArray( data ) ) {
  1103. // cube texture
  1104. url = [];
  1105. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1106. if ( data[ i ].isDataTexture ) {
  1107. url.push( serializeImage( data[ i ].image ) );
  1108. } else {
  1109. url.push( serializeImage( data[ i ] ) );
  1110. }
  1111. }
  1112. } else {
  1113. // texture
  1114. url = serializeImage( data );
  1115. }
  1116. output.url = url;
  1117. }
  1118. if ( ! isRootObject ) {
  1119. meta.images[ this.uuid ] = output;
  1120. }
  1121. return output;
  1122. }
  1123. }
  1124. function serializeImage( image ) {
  1125. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1126. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1127. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1128. // default images
  1129. return ImageUtils.getDataURL( image );
  1130. } else {
  1131. if ( image.data ) {
  1132. // images of DataTexture
  1133. return {
  1134. data: Array.from( image.data ),
  1135. width: image.width,
  1136. height: image.height,
  1137. type: image.data.constructor.name
  1138. };
  1139. } else {
  1140. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1141. return {};
  1142. }
  1143. }
  1144. }
  1145. let textureId = 0;
  1146. class Texture extends EventDispatcher {
  1147. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1148. super();
  1149. this.isTexture = true;
  1150. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1151. this.uuid = generateUUID();
  1152. this.name = '';
  1153. this.source = new Source( image );
  1154. this.mipmaps = [];
  1155. this.mapping = mapping;
  1156. this.channel = 0;
  1157. this.wrapS = wrapS;
  1158. this.wrapT = wrapT;
  1159. this.magFilter = magFilter;
  1160. this.minFilter = minFilter;
  1161. this.anisotropy = anisotropy;
  1162. this.format = format;
  1163. this.internalFormat = null;
  1164. this.type = type;
  1165. this.offset = new Vector2( 0, 0 );
  1166. this.repeat = new Vector2( 1, 1 );
  1167. this.center = new Vector2( 0, 0 );
  1168. this.rotation = 0;
  1169. this.matrixAutoUpdate = true;
  1170. this.matrix = new Matrix3();
  1171. this.generateMipmaps = true;
  1172. this.premultiplyAlpha = false;
  1173. this.flipY = true;
  1174. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1175. if ( typeof colorSpace === 'string' ) {
  1176. this.colorSpace = colorSpace;
  1177. } else { // @deprecated, r152
  1178. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1179. this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1180. }
  1181. this.userData = {};
  1182. this.version = 0;
  1183. this.onUpdate = null;
  1184. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1185. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1186. }
  1187. get image() {
  1188. return this.source.data;
  1189. }
  1190. set image( value = null ) {
  1191. this.source.data = value;
  1192. }
  1193. updateMatrix() {
  1194. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1195. }
  1196. clone() {
  1197. return new this.constructor().copy( this );
  1198. }
  1199. copy( source ) {
  1200. this.name = source.name;
  1201. this.source = source.source;
  1202. this.mipmaps = source.mipmaps.slice( 0 );
  1203. this.mapping = source.mapping;
  1204. this.channel = source.channel;
  1205. this.wrapS = source.wrapS;
  1206. this.wrapT = source.wrapT;
  1207. this.magFilter = source.magFilter;
  1208. this.minFilter = source.minFilter;
  1209. this.anisotropy = source.anisotropy;
  1210. this.format = source.format;
  1211. this.internalFormat = source.internalFormat;
  1212. this.type = source.type;
  1213. this.offset.copy( source.offset );
  1214. this.repeat.copy( source.repeat );
  1215. this.center.copy( source.center );
  1216. this.rotation = source.rotation;
  1217. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1218. this.matrix.copy( source.matrix );
  1219. this.generateMipmaps = source.generateMipmaps;
  1220. this.premultiplyAlpha = source.premultiplyAlpha;
  1221. this.flipY = source.flipY;
  1222. this.unpackAlignment = source.unpackAlignment;
  1223. this.colorSpace = source.colorSpace;
  1224. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1225. this.needsUpdate = true;
  1226. return this;
  1227. }
  1228. toJSON( meta ) {
  1229. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1230. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1231. return meta.textures[ this.uuid ];
  1232. }
  1233. const output = {
  1234. metadata: {
  1235. version: 4.5,
  1236. type: 'Texture',
  1237. generator: 'Texture.toJSON'
  1238. },
  1239. uuid: this.uuid,
  1240. name: this.name,
  1241. image: this.source.toJSON( meta ).uuid,
  1242. mapping: this.mapping,
  1243. channel: this.channel,
  1244. repeat: [ this.repeat.x, this.repeat.y ],
  1245. offset: [ this.offset.x, this.offset.y ],
  1246. center: [ this.center.x, this.center.y ],
  1247. rotation: this.rotation,
  1248. wrap: [ this.wrapS, this.wrapT ],
  1249. format: this.format,
  1250. internalFormat: this.internalFormat,
  1251. type: this.type,
  1252. colorSpace: this.colorSpace,
  1253. minFilter: this.minFilter,
  1254. magFilter: this.magFilter,
  1255. anisotropy: this.anisotropy,
  1256. flipY: this.flipY,
  1257. generateMipmaps: this.generateMipmaps,
  1258. premultiplyAlpha: this.premultiplyAlpha,
  1259. unpackAlignment: this.unpackAlignment
  1260. };
  1261. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1262. if ( ! isRootObject ) {
  1263. meta.textures[ this.uuid ] = output;
  1264. }
  1265. return output;
  1266. }
  1267. dispose() {
  1268. this.dispatchEvent( { type: 'dispose' } );
  1269. }
  1270. transformUv( uv ) {
  1271. if ( this.mapping !== UVMapping ) return uv;
  1272. uv.applyMatrix3( this.matrix );
  1273. if ( uv.x < 0 || uv.x > 1 ) {
  1274. switch ( this.wrapS ) {
  1275. case RepeatWrapping:
  1276. uv.x = uv.x - Math.floor( uv.x );
  1277. break;
  1278. case ClampToEdgeWrapping:
  1279. uv.x = uv.x < 0 ? 0 : 1;
  1280. break;
  1281. case MirroredRepeatWrapping:
  1282. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1283. uv.x = Math.ceil( uv.x ) - uv.x;
  1284. } else {
  1285. uv.x = uv.x - Math.floor( uv.x );
  1286. }
  1287. break;
  1288. }
  1289. }
  1290. if ( uv.y < 0 || uv.y > 1 ) {
  1291. switch ( this.wrapT ) {
  1292. case RepeatWrapping:
  1293. uv.y = uv.y - Math.floor( uv.y );
  1294. break;
  1295. case ClampToEdgeWrapping:
  1296. uv.y = uv.y < 0 ? 0 : 1;
  1297. break;
  1298. case MirroredRepeatWrapping:
  1299. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1300. uv.y = Math.ceil( uv.y ) - uv.y;
  1301. } else {
  1302. uv.y = uv.y - Math.floor( uv.y );
  1303. }
  1304. break;
  1305. }
  1306. }
  1307. if ( this.flipY ) {
  1308. uv.y = 1 - uv.y;
  1309. }
  1310. return uv;
  1311. }
  1312. set needsUpdate( value ) {
  1313. if ( value === true ) {
  1314. this.version ++;
  1315. this.source.needsUpdate = true;
  1316. }
  1317. }
  1318. get encoding() { // @deprecated, r152
  1319. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1320. return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  1321. }
  1322. set encoding( encoding ) { // @deprecated, r152
  1323. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1324. this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1325. }
  1326. }
  1327. Texture.DEFAULT_IMAGE = null;
  1328. Texture.DEFAULT_MAPPING = UVMapping;
  1329. Texture.DEFAULT_ANISOTROPY = 1;
  1330. class Vector4 {
  1331. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1332. Vector4.prototype.isVector4 = true;
  1333. this.x = x;
  1334. this.y = y;
  1335. this.z = z;
  1336. this.w = w;
  1337. }
  1338. get width() {
  1339. return this.z;
  1340. }
  1341. set width( value ) {
  1342. this.z = value;
  1343. }
  1344. get height() {
  1345. return this.w;
  1346. }
  1347. set height( value ) {
  1348. this.w = value;
  1349. }
  1350. set( x, y, z, w ) {
  1351. this.x = x;
  1352. this.y = y;
  1353. this.z = z;
  1354. this.w = w;
  1355. return this;
  1356. }
  1357. setScalar( scalar ) {
  1358. this.x = scalar;
  1359. this.y = scalar;
  1360. this.z = scalar;
  1361. this.w = scalar;
  1362. return this;
  1363. }
  1364. setX( x ) {
  1365. this.x = x;
  1366. return this;
  1367. }
  1368. setY( y ) {
  1369. this.y = y;
  1370. return this;
  1371. }
  1372. setZ( z ) {
  1373. this.z = z;
  1374. return this;
  1375. }
  1376. setW( w ) {
  1377. this.w = w;
  1378. return this;
  1379. }
  1380. setComponent( index, value ) {
  1381. switch ( index ) {
  1382. case 0: this.x = value; break;
  1383. case 1: this.y = value; break;
  1384. case 2: this.z = value; break;
  1385. case 3: this.w = value; break;
  1386. default: throw new Error( 'index is out of range: ' + index );
  1387. }
  1388. return this;
  1389. }
  1390. getComponent( index ) {
  1391. switch ( index ) {
  1392. case 0: return this.x;
  1393. case 1: return this.y;
  1394. case 2: return this.z;
  1395. case 3: return this.w;
  1396. default: throw new Error( 'index is out of range: ' + index );
  1397. }
  1398. }
  1399. clone() {
  1400. return new this.constructor( this.x, this.y, this.z, this.w );
  1401. }
  1402. copy( v ) {
  1403. this.x = v.x;
  1404. this.y = v.y;
  1405. this.z = v.z;
  1406. this.w = ( v.w !== undefined ) ? v.w : 1;
  1407. return this;
  1408. }
  1409. add( v ) {
  1410. this.x += v.x;
  1411. this.y += v.y;
  1412. this.z += v.z;
  1413. this.w += v.w;
  1414. return this;
  1415. }
  1416. addScalar( s ) {
  1417. this.x += s;
  1418. this.y += s;
  1419. this.z += s;
  1420. this.w += s;
  1421. return this;
  1422. }
  1423. addVectors( a, b ) {
  1424. this.x = a.x + b.x;
  1425. this.y = a.y + b.y;
  1426. this.z = a.z + b.z;
  1427. this.w = a.w + b.w;
  1428. return this;
  1429. }
  1430. addScaledVector( v, s ) {
  1431. this.x += v.x * s;
  1432. this.y += v.y * s;
  1433. this.z += v.z * s;
  1434. this.w += v.w * s;
  1435. return this;
  1436. }
  1437. sub( v ) {
  1438. this.x -= v.x;
  1439. this.y -= v.y;
  1440. this.z -= v.z;
  1441. this.w -= v.w;
  1442. return this;
  1443. }
  1444. subScalar( s ) {
  1445. this.x -= s;
  1446. this.y -= s;
  1447. this.z -= s;
  1448. this.w -= s;
  1449. return this;
  1450. }
  1451. subVectors( a, b ) {
  1452. this.x = a.x - b.x;
  1453. this.y = a.y - b.y;
  1454. this.z = a.z - b.z;
  1455. this.w = a.w - b.w;
  1456. return this;
  1457. }
  1458. multiply( v ) {
  1459. this.x *= v.x;
  1460. this.y *= v.y;
  1461. this.z *= v.z;
  1462. this.w *= v.w;
  1463. return this;
  1464. }
  1465. multiplyScalar( scalar ) {
  1466. this.x *= scalar;
  1467. this.y *= scalar;
  1468. this.z *= scalar;
  1469. this.w *= scalar;
  1470. return this;
  1471. }
  1472. applyMatrix4( m ) {
  1473. const x = this.x, y = this.y, z = this.z, w = this.w;
  1474. const e = m.elements;
  1475. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1476. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1477. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1478. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1479. return this;
  1480. }
  1481. divideScalar( scalar ) {
  1482. return this.multiplyScalar( 1 / scalar );
  1483. }
  1484. setAxisAngleFromQuaternion( q ) {
  1485. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1486. // q is assumed to be normalized
  1487. this.w = 2 * Math.acos( q.w );
  1488. const s = Math.sqrt( 1 - q.w * q.w );
  1489. if ( s < 0.0001 ) {
  1490. this.x = 1;
  1491. this.y = 0;
  1492. this.z = 0;
  1493. } else {
  1494. this.x = q.x / s;
  1495. this.y = q.y / s;
  1496. this.z = q.z / s;
  1497. }
  1498. return this;
  1499. }
  1500. setAxisAngleFromRotationMatrix( m ) {
  1501. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1502. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1503. let angle, x, y, z; // variables for result
  1504. const epsilon = 0.01, // margin to allow for rounding errors
  1505. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1506. te = m.elements,
  1507. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1508. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1509. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1510. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1511. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1512. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1513. // singularity found
  1514. // first check for identity matrix which must have +1 for all terms
  1515. // in leading diagonal and zero in other terms
  1516. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1517. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1518. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1519. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1520. // this singularity is identity matrix so angle = 0
  1521. this.set( 1, 0, 0, 0 );
  1522. return this; // zero angle, arbitrary axis
  1523. }
  1524. // otherwise this singularity is angle = 180
  1525. angle = Math.PI;
  1526. const xx = ( m11 + 1 ) / 2;
  1527. const yy = ( m22 + 1 ) / 2;
  1528. const zz = ( m33 + 1 ) / 2;
  1529. const xy = ( m12 + m21 ) / 4;
  1530. const xz = ( m13 + m31 ) / 4;
  1531. const yz = ( m23 + m32 ) / 4;
  1532. if ( ( xx > yy ) && ( xx > zz ) ) {
  1533. // m11 is the largest diagonal term
  1534. if ( xx < epsilon ) {
  1535. x = 0;
  1536. y = 0.707106781;
  1537. z = 0.707106781;
  1538. } else {
  1539. x = Math.sqrt( xx );
  1540. y = xy / x;
  1541. z = xz / x;
  1542. }
  1543. } else if ( yy > zz ) {
  1544. // m22 is the largest diagonal term
  1545. if ( yy < epsilon ) {
  1546. x = 0.707106781;
  1547. y = 0;
  1548. z = 0.707106781;
  1549. } else {
  1550. y = Math.sqrt( yy );
  1551. x = xy / y;
  1552. z = yz / y;
  1553. }
  1554. } else {
  1555. // m33 is the largest diagonal term so base result on this
  1556. if ( zz < epsilon ) {
  1557. x = 0.707106781;
  1558. y = 0.707106781;
  1559. z = 0;
  1560. } else {
  1561. z = Math.sqrt( zz );
  1562. x = xz / z;
  1563. y = yz / z;
  1564. }
  1565. }
  1566. this.set( x, y, z, angle );
  1567. return this; // return 180 deg rotation
  1568. }
  1569. // as we have reached here there are no singularities so we can handle normally
  1570. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1571. ( m13 - m31 ) * ( m13 - m31 ) +
  1572. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1573. if ( Math.abs( s ) < 0.001 ) s = 1;
  1574. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1575. // caught by singularity test above, but I've left it in just in case
  1576. this.x = ( m32 - m23 ) / s;
  1577. this.y = ( m13 - m31 ) / s;
  1578. this.z = ( m21 - m12 ) / s;
  1579. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1580. return this;
  1581. }
  1582. min( v ) {
  1583. this.x = Math.min( this.x, v.x );
  1584. this.y = Math.min( this.y, v.y );
  1585. this.z = Math.min( this.z, v.z );
  1586. this.w = Math.min( this.w, v.w );
  1587. return this;
  1588. }
  1589. max( v ) {
  1590. this.x = Math.max( this.x, v.x );
  1591. this.y = Math.max( this.y, v.y );
  1592. this.z = Math.max( this.z, v.z );
  1593. this.w = Math.max( this.w, v.w );
  1594. return this;
  1595. }
  1596. clamp( min, max ) {
  1597. // assumes min < max, componentwise
  1598. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1599. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1600. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1601. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1602. return this;
  1603. }
  1604. clampScalar( minVal, maxVal ) {
  1605. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1606. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1607. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1608. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1609. return this;
  1610. }
  1611. clampLength( min, max ) {
  1612. const length = this.length();
  1613. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1614. }
  1615. floor() {
  1616. this.x = Math.floor( this.x );
  1617. this.y = Math.floor( this.y );
  1618. this.z = Math.floor( this.z );
  1619. this.w = Math.floor( this.w );
  1620. return this;
  1621. }
  1622. ceil() {
  1623. this.x = Math.ceil( this.x );
  1624. this.y = Math.ceil( this.y );
  1625. this.z = Math.ceil( this.z );
  1626. this.w = Math.ceil( this.w );
  1627. return this;
  1628. }
  1629. round() {
  1630. this.x = Math.round( this.x );
  1631. this.y = Math.round( this.y );
  1632. this.z = Math.round( this.z );
  1633. this.w = Math.round( this.w );
  1634. return this;
  1635. }
  1636. roundToZero() {
  1637. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1638. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1639. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1640. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1641. return this;
  1642. }
  1643. negate() {
  1644. this.x = - this.x;
  1645. this.y = - this.y;
  1646. this.z = - this.z;
  1647. this.w = - this.w;
  1648. return this;
  1649. }
  1650. dot( v ) {
  1651. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1652. }
  1653. lengthSq() {
  1654. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1655. }
  1656. length() {
  1657. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1658. }
  1659. manhattanLength() {
  1660. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1661. }
  1662. normalize() {
  1663. return this.divideScalar( this.length() || 1 );
  1664. }
  1665. setLength( length ) {
  1666. return this.normalize().multiplyScalar( length );
  1667. }
  1668. lerp( v, alpha ) {
  1669. this.x += ( v.x - this.x ) * alpha;
  1670. this.y += ( v.y - this.y ) * alpha;
  1671. this.z += ( v.z - this.z ) * alpha;
  1672. this.w += ( v.w - this.w ) * alpha;
  1673. return this;
  1674. }
  1675. lerpVectors( v1, v2, alpha ) {
  1676. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1677. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1678. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1679. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1680. return this;
  1681. }
  1682. equals( v ) {
  1683. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1684. }
  1685. fromArray( array, offset = 0 ) {
  1686. this.x = array[ offset ];
  1687. this.y = array[ offset + 1 ];
  1688. this.z = array[ offset + 2 ];
  1689. this.w = array[ offset + 3 ];
  1690. return this;
  1691. }
  1692. toArray( array = [], offset = 0 ) {
  1693. array[ offset ] = this.x;
  1694. array[ offset + 1 ] = this.y;
  1695. array[ offset + 2 ] = this.z;
  1696. array[ offset + 3 ] = this.w;
  1697. return array;
  1698. }
  1699. fromBufferAttribute( attribute, index ) {
  1700. this.x = attribute.getX( index );
  1701. this.y = attribute.getY( index );
  1702. this.z = attribute.getZ( index );
  1703. this.w = attribute.getW( index );
  1704. return this;
  1705. }
  1706. random() {
  1707. this.x = Math.random();
  1708. this.y = Math.random();
  1709. this.z = Math.random();
  1710. this.w = Math.random();
  1711. return this;
  1712. }
  1713. *[ Symbol.iterator ]() {
  1714. yield this.x;
  1715. yield this.y;
  1716. yield this.z;
  1717. yield this.w;
  1718. }
  1719. }
  1720. /*
  1721. In options, we can specify:
  1722. * Texture parameters for an auto-generated target texture
  1723. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1724. */
  1725. class WebGLRenderTarget extends EventDispatcher {
  1726. constructor( width = 1, height = 1, options = {} ) {
  1727. super();
  1728. this.isWebGLRenderTarget = true;
  1729. this.width = width;
  1730. this.height = height;
  1731. this.depth = 1;
  1732. this.scissor = new Vector4( 0, 0, width, height );
  1733. this.scissorTest = false;
  1734. this.viewport = new Vector4( 0, 0, width, height );
  1735. const image = { width: width, height: height, depth: 1 };
  1736. if ( options.encoding !== undefined ) {
  1737. // @deprecated, r152
  1738. warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  1739. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1740. }
  1741. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1742. this.texture.isRenderTargetTexture = true;
  1743. this.texture.flipY = false;
  1744. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1745. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1746. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1747. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1748. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1749. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1750. this.samples = options.samples !== undefined ? options.samples : 0;
  1751. }
  1752. setSize( width, height, depth = 1 ) {
  1753. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1754. this.width = width;
  1755. this.height = height;
  1756. this.depth = depth;
  1757. this.texture.image.width = width;
  1758. this.texture.image.height = height;
  1759. this.texture.image.depth = depth;
  1760. this.dispose();
  1761. }
  1762. this.viewport.set( 0, 0, width, height );
  1763. this.scissor.set( 0, 0, width, height );
  1764. }
  1765. clone() {
  1766. return new this.constructor().copy( this );
  1767. }
  1768. copy( source ) {
  1769. this.width = source.width;
  1770. this.height = source.height;
  1771. this.depth = source.depth;
  1772. this.scissor.copy( source.scissor );
  1773. this.scissorTest = source.scissorTest;
  1774. this.viewport.copy( source.viewport );
  1775. this.texture = source.texture.clone();
  1776. this.texture.isRenderTargetTexture = true;
  1777. // ensure image object is not shared, see #20328
  1778. const image = Object.assign( {}, source.texture.image );
  1779. this.texture.source = new Source( image );
  1780. this.depthBuffer = source.depthBuffer;
  1781. this.stencilBuffer = source.stencilBuffer;
  1782. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1783. this.samples = source.samples;
  1784. return this;
  1785. }
  1786. dispose() {
  1787. this.dispatchEvent( { type: 'dispose' } );
  1788. }
  1789. }
  1790. class DataArrayTexture extends Texture {
  1791. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1792. super( null );
  1793. this.isDataArrayTexture = true;
  1794. this.image = { data, width, height, depth };
  1795. this.magFilter = NearestFilter;
  1796. this.minFilter = NearestFilter;
  1797. this.wrapR = ClampToEdgeWrapping;
  1798. this.generateMipmaps = false;
  1799. this.flipY = false;
  1800. this.unpackAlignment = 1;
  1801. }
  1802. }
  1803. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1804. constructor( width = 1, height = 1, depth = 1 ) {
  1805. super( width, height );
  1806. this.isWebGLArrayRenderTarget = true;
  1807. this.depth = depth;
  1808. this.texture = new DataArrayTexture( null, width, height, depth );
  1809. this.texture.isRenderTargetTexture = true;
  1810. }
  1811. }
  1812. class Data3DTexture extends Texture {
  1813. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1814. // We're going to add .setXXX() methods for setting properties later.
  1815. // Users can still set in DataTexture3D directly.
  1816. //
  1817. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1818. // texture.anisotropy = 16;
  1819. //
  1820. // See #14839
  1821. super( null );
  1822. this.isData3DTexture = true;
  1823. this.image = { data, width, height, depth };
  1824. this.magFilter = NearestFilter;
  1825. this.minFilter = NearestFilter;
  1826. this.wrapR = ClampToEdgeWrapping;
  1827. this.generateMipmaps = false;
  1828. this.flipY = false;
  1829. this.unpackAlignment = 1;
  1830. }
  1831. }
  1832. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1833. constructor( width = 1, height = 1, depth = 1 ) {
  1834. super( width, height );
  1835. this.isWebGL3DRenderTarget = true;
  1836. this.depth = depth;
  1837. this.texture = new Data3DTexture( null, width, height, depth );
  1838. this.texture.isRenderTargetTexture = true;
  1839. }
  1840. }
  1841. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1842. constructor( width = 1, height = 1, count = 1, options = {} ) {
  1843. super( width, height, options );
  1844. this.isWebGLMultipleRenderTargets = true;
  1845. const texture = this.texture;
  1846. this.texture = [];
  1847. for ( let i = 0; i < count; i ++ ) {
  1848. this.texture[ i ] = texture.clone();
  1849. this.texture[ i ].isRenderTargetTexture = true;
  1850. }
  1851. }
  1852. setSize( width, height, depth = 1 ) {
  1853. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1854. this.width = width;
  1855. this.height = height;
  1856. this.depth = depth;
  1857. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1858. this.texture[ i ].image.width = width;
  1859. this.texture[ i ].image.height = height;
  1860. this.texture[ i ].image.depth = depth;
  1861. }
  1862. this.dispose();
  1863. }
  1864. this.viewport.set( 0, 0, width, height );
  1865. this.scissor.set( 0, 0, width, height );
  1866. return this;
  1867. }
  1868. copy( source ) {
  1869. this.dispose();
  1870. this.width = source.width;
  1871. this.height = source.height;
  1872. this.depth = source.depth;
  1873. this.scissor.copy( source.scissor );
  1874. this.scissorTest = source.scissorTest;
  1875. this.viewport.copy( source.viewport );
  1876. this.depthBuffer = source.depthBuffer;
  1877. this.stencilBuffer = source.stencilBuffer;
  1878. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1879. this.texture.length = 0;
  1880. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1881. this.texture[ i ] = source.texture[ i ].clone();
  1882. this.texture[ i ].isRenderTargetTexture = true;
  1883. }
  1884. return this;
  1885. }
  1886. }
  1887. class Quaternion {
  1888. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1889. this.isQuaternion = true;
  1890. this._x = x;
  1891. this._y = y;
  1892. this._z = z;
  1893. this._w = w;
  1894. }
  1895. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1896. // fuzz-free, array-based Quaternion SLERP operation
  1897. let x0 = src0[ srcOffset0 + 0 ],
  1898. y0 = src0[ srcOffset0 + 1 ],
  1899. z0 = src0[ srcOffset0 + 2 ],
  1900. w0 = src0[ srcOffset0 + 3 ];
  1901. const x1 = src1[ srcOffset1 + 0 ],
  1902. y1 = src1[ srcOffset1 + 1 ],
  1903. z1 = src1[ srcOffset1 + 2 ],
  1904. w1 = src1[ srcOffset1 + 3 ];
  1905. if ( t === 0 ) {
  1906. dst[ dstOffset + 0 ] = x0;
  1907. dst[ dstOffset + 1 ] = y0;
  1908. dst[ dstOffset + 2 ] = z0;
  1909. dst[ dstOffset + 3 ] = w0;
  1910. return;
  1911. }
  1912. if ( t === 1 ) {
  1913. dst[ dstOffset + 0 ] = x1;
  1914. dst[ dstOffset + 1 ] = y1;
  1915. dst[ dstOffset + 2 ] = z1;
  1916. dst[ dstOffset + 3 ] = w1;
  1917. return;
  1918. }
  1919. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1920. let s = 1 - t;
  1921. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1922. dir = ( cos >= 0 ? 1 : - 1 ),
  1923. sqrSin = 1 - cos * cos;
  1924. // Skip the Slerp for tiny steps to avoid numeric problems:
  1925. if ( sqrSin > Number.EPSILON ) {
  1926. const sin = Math.sqrt( sqrSin ),
  1927. len = Math.atan2( sin, cos * dir );
  1928. s = Math.sin( s * len ) / sin;
  1929. t = Math.sin( t * len ) / sin;
  1930. }
  1931. const tDir = t * dir;
  1932. x0 = x0 * s + x1 * tDir;
  1933. y0 = y0 * s + y1 * tDir;
  1934. z0 = z0 * s + z1 * tDir;
  1935. w0 = w0 * s + w1 * tDir;
  1936. // Normalize in case we just did a lerp:
  1937. if ( s === 1 - t ) {
  1938. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1939. x0 *= f;
  1940. y0 *= f;
  1941. z0 *= f;
  1942. w0 *= f;
  1943. }
  1944. }
  1945. dst[ dstOffset ] = x0;
  1946. dst[ dstOffset + 1 ] = y0;
  1947. dst[ dstOffset + 2 ] = z0;
  1948. dst[ dstOffset + 3 ] = w0;
  1949. }
  1950. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1951. const x0 = src0[ srcOffset0 ];
  1952. const y0 = src0[ srcOffset0 + 1 ];
  1953. const z0 = src0[ srcOffset0 + 2 ];
  1954. const w0 = src0[ srcOffset0 + 3 ];
  1955. const x1 = src1[ srcOffset1 ];
  1956. const y1 = src1[ srcOffset1 + 1 ];
  1957. const z1 = src1[ srcOffset1 + 2 ];
  1958. const w1 = src1[ srcOffset1 + 3 ];
  1959. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1960. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1961. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1962. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1963. return dst;
  1964. }
  1965. get x() {
  1966. return this._x;
  1967. }
  1968. set x( value ) {
  1969. this._x = value;
  1970. this._onChangeCallback();
  1971. }
  1972. get y() {
  1973. return this._y;
  1974. }
  1975. set y( value ) {
  1976. this._y = value;
  1977. this._onChangeCallback();
  1978. }
  1979. get z() {
  1980. return this._z;
  1981. }
  1982. set z( value ) {
  1983. this._z = value;
  1984. this._onChangeCallback();
  1985. }
  1986. get w() {
  1987. return this._w;
  1988. }
  1989. set w( value ) {
  1990. this._w = value;
  1991. this._onChangeCallback();
  1992. }
  1993. set( x, y, z, w ) {
  1994. this._x = x;
  1995. this._y = y;
  1996. this._z = z;
  1997. this._w = w;
  1998. this._onChangeCallback();
  1999. return this;
  2000. }
  2001. clone() {
  2002. return new this.constructor( this._x, this._y, this._z, this._w );
  2003. }
  2004. copy( quaternion ) {
  2005. this._x = quaternion.x;
  2006. this._y = quaternion.y;
  2007. this._z = quaternion.z;
  2008. this._w = quaternion.w;
  2009. this._onChangeCallback();
  2010. return this;
  2011. }
  2012. setFromEuler( euler, update ) {
  2013. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2014. // http://www.mathworks.com/matlabcentral/fileexchange/
  2015. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2016. // content/SpinCalc.m
  2017. const cos = Math.cos;
  2018. const sin = Math.sin;
  2019. const c1 = cos( x / 2 );
  2020. const c2 = cos( y / 2 );
  2021. const c3 = cos( z / 2 );
  2022. const s1 = sin( x / 2 );
  2023. const s2 = sin( y / 2 );
  2024. const s3 = sin( z / 2 );
  2025. switch ( order ) {
  2026. case 'XYZ':
  2027. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2028. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2029. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2030. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2031. break;
  2032. case 'YXZ':
  2033. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2034. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2035. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2036. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2037. break;
  2038. case 'ZXY':
  2039. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2040. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2041. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2042. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2043. break;
  2044. case 'ZYX':
  2045. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2046. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2047. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2048. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2049. break;
  2050. case 'YZX':
  2051. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2052. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2053. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2054. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2055. break;
  2056. case 'XZY':
  2057. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2058. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2059. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2060. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2061. break;
  2062. default:
  2063. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2064. }
  2065. if ( update !== false ) this._onChangeCallback();
  2066. return this;
  2067. }
  2068. setFromAxisAngle( axis, angle ) {
  2069. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2070. // assumes axis is normalized
  2071. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2072. this._x = axis.x * s;
  2073. this._y = axis.y * s;
  2074. this._z = axis.z * s;
  2075. this._w = Math.cos( halfAngle );
  2076. this._onChangeCallback();
  2077. return this;
  2078. }
  2079. setFromRotationMatrix( m ) {
  2080. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2081. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2082. const te = m.elements,
  2083. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2084. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2085. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2086. trace = m11 + m22 + m33;
  2087. if ( trace > 0 ) {
  2088. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2089. this._w = 0.25 / s;
  2090. this._x = ( m32 - m23 ) * s;
  2091. this._y = ( m13 - m31 ) * s;
  2092. this._z = ( m21 - m12 ) * s;
  2093. } else if ( m11 > m22 && m11 > m33 ) {
  2094. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2095. this._w = ( m32 - m23 ) / s;
  2096. this._x = 0.25 * s;
  2097. this._y = ( m12 + m21 ) / s;
  2098. this._z = ( m13 + m31 ) / s;
  2099. } else if ( m22 > m33 ) {
  2100. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2101. this._w = ( m13 - m31 ) / s;
  2102. this._x = ( m12 + m21 ) / s;
  2103. this._y = 0.25 * s;
  2104. this._z = ( m23 + m32 ) / s;
  2105. } else {
  2106. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2107. this._w = ( m21 - m12 ) / s;
  2108. this._x = ( m13 + m31 ) / s;
  2109. this._y = ( m23 + m32 ) / s;
  2110. this._z = 0.25 * s;
  2111. }
  2112. this._onChangeCallback();
  2113. return this;
  2114. }
  2115. setFromUnitVectors( vFrom, vTo ) {
  2116. // assumes direction vectors vFrom and vTo are normalized
  2117. let r = vFrom.dot( vTo ) + 1;
  2118. if ( r < Number.EPSILON ) {
  2119. // vFrom and vTo point in opposite directions
  2120. r = 0;
  2121. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2122. this._x = - vFrom.y;
  2123. this._y = vFrom.x;
  2124. this._z = 0;
  2125. this._w = r;
  2126. } else {
  2127. this._x = 0;
  2128. this._y = - vFrom.z;
  2129. this._z = vFrom.y;
  2130. this._w = r;
  2131. }
  2132. } else {
  2133. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2134. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2135. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2136. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2137. this._w = r;
  2138. }
  2139. return this.normalize();
  2140. }
  2141. angleTo( q ) {
  2142. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2143. }
  2144. rotateTowards( q, step ) {
  2145. const angle = this.angleTo( q );
  2146. if ( angle === 0 ) return this;
  2147. const t = Math.min( 1, step / angle );
  2148. this.slerp( q, t );
  2149. return this;
  2150. }
  2151. identity() {
  2152. return this.set( 0, 0, 0, 1 );
  2153. }
  2154. invert() {
  2155. // quaternion is assumed to have unit length
  2156. return this.conjugate();
  2157. }
  2158. conjugate() {
  2159. this._x *= - 1;
  2160. this._y *= - 1;
  2161. this._z *= - 1;
  2162. this._onChangeCallback();
  2163. return this;
  2164. }
  2165. dot( v ) {
  2166. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2167. }
  2168. lengthSq() {
  2169. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2170. }
  2171. length() {
  2172. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2173. }
  2174. normalize() {
  2175. let l = this.length();
  2176. if ( l === 0 ) {
  2177. this._x = 0;
  2178. this._y = 0;
  2179. this._z = 0;
  2180. this._w = 1;
  2181. } else {
  2182. l = 1 / l;
  2183. this._x = this._x * l;
  2184. this._y = this._y * l;
  2185. this._z = this._z * l;
  2186. this._w = this._w * l;
  2187. }
  2188. this._onChangeCallback();
  2189. return this;
  2190. }
  2191. multiply( q ) {
  2192. return this.multiplyQuaternions( this, q );
  2193. }
  2194. premultiply( q ) {
  2195. return this.multiplyQuaternions( q, this );
  2196. }
  2197. multiplyQuaternions( a, b ) {
  2198. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2199. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2200. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2201. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2202. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2203. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2204. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2205. this._onChangeCallback();
  2206. return this;
  2207. }
  2208. slerp( qb, t ) {
  2209. if ( t === 0 ) return this;
  2210. if ( t === 1 ) return this.copy( qb );
  2211. const x = this._x, y = this._y, z = this._z, w = this._w;
  2212. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2213. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2214. if ( cosHalfTheta < 0 ) {
  2215. this._w = - qb._w;
  2216. this._x = - qb._x;
  2217. this._y = - qb._y;
  2218. this._z = - qb._z;
  2219. cosHalfTheta = - cosHalfTheta;
  2220. } else {
  2221. this.copy( qb );
  2222. }
  2223. if ( cosHalfTheta >= 1.0 ) {
  2224. this._w = w;
  2225. this._x = x;
  2226. this._y = y;
  2227. this._z = z;
  2228. return this;
  2229. }
  2230. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2231. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2232. const s = 1 - t;
  2233. this._w = s * w + t * this._w;
  2234. this._x = s * x + t * this._x;
  2235. this._y = s * y + t * this._y;
  2236. this._z = s * z + t * this._z;
  2237. this.normalize();
  2238. this._onChangeCallback();
  2239. return this;
  2240. }
  2241. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2242. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2243. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2244. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2245. this._w = ( w * ratioA + this._w * ratioB );
  2246. this._x = ( x * ratioA + this._x * ratioB );
  2247. this._y = ( y * ratioA + this._y * ratioB );
  2248. this._z = ( z * ratioA + this._z * ratioB );
  2249. this._onChangeCallback();
  2250. return this;
  2251. }
  2252. slerpQuaternions( qa, qb, t ) {
  2253. return this.copy( qa ).slerp( qb, t );
  2254. }
  2255. random() {
  2256. // Derived from http://planning.cs.uiuc.edu/node198.html
  2257. // Note, this source uses w, x, y, z ordering,
  2258. // so we swap the order below.
  2259. const u1 = Math.random();
  2260. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2261. const sqrtu1 = Math.sqrt( u1 );
  2262. const u2 = 2 * Math.PI * Math.random();
  2263. const u3 = 2 * Math.PI * Math.random();
  2264. return this.set(
  2265. sqrt1u1 * Math.cos( u2 ),
  2266. sqrtu1 * Math.sin( u3 ),
  2267. sqrtu1 * Math.cos( u3 ),
  2268. sqrt1u1 * Math.sin( u2 ),
  2269. );
  2270. }
  2271. equals( quaternion ) {
  2272. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2273. }
  2274. fromArray( array, offset = 0 ) {
  2275. this._x = array[ offset ];
  2276. this._y = array[ offset + 1 ];
  2277. this._z = array[ offset + 2 ];
  2278. this._w = array[ offset + 3 ];
  2279. this._onChangeCallback();
  2280. return this;
  2281. }
  2282. toArray( array = [], offset = 0 ) {
  2283. array[ offset ] = this._x;
  2284. array[ offset + 1 ] = this._y;
  2285. array[ offset + 2 ] = this._z;
  2286. array[ offset + 3 ] = this._w;
  2287. return array;
  2288. }
  2289. fromBufferAttribute( attribute, index ) {
  2290. this._x = attribute.getX( index );
  2291. this._y = attribute.getY( index );
  2292. this._z = attribute.getZ( index );
  2293. this._w = attribute.getW( index );
  2294. return this;
  2295. }
  2296. toJSON() {
  2297. return this.toArray();
  2298. }
  2299. _onChange( callback ) {
  2300. this._onChangeCallback = callback;
  2301. return this;
  2302. }
  2303. _onChangeCallback() {}
  2304. *[ Symbol.iterator ]() {
  2305. yield this._x;
  2306. yield this._y;
  2307. yield this._z;
  2308. yield this._w;
  2309. }
  2310. }
  2311. class Vector3 {
  2312. constructor( x = 0, y = 0, z = 0 ) {
  2313. Vector3.prototype.isVector3 = true;
  2314. this.x = x;
  2315. this.y = y;
  2316. this.z = z;
  2317. }
  2318. set( x, y, z ) {
  2319. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2320. this.x = x;
  2321. this.y = y;
  2322. this.z = z;
  2323. return this;
  2324. }
  2325. setScalar( scalar ) {
  2326. this.x = scalar;
  2327. this.y = scalar;
  2328. this.z = scalar;
  2329. return this;
  2330. }
  2331. setX( x ) {
  2332. this.x = x;
  2333. return this;
  2334. }
  2335. setY( y ) {
  2336. this.y = y;
  2337. return this;
  2338. }
  2339. setZ( z ) {
  2340. this.z = z;
  2341. return this;
  2342. }
  2343. setComponent( index, value ) {
  2344. switch ( index ) {
  2345. case 0: this.x = value; break;
  2346. case 1: this.y = value; break;
  2347. case 2: this.z = value; break;
  2348. default: throw new Error( 'index is out of range: ' + index );
  2349. }
  2350. return this;
  2351. }
  2352. getComponent( index ) {
  2353. switch ( index ) {
  2354. case 0: return this.x;
  2355. case 1: return this.y;
  2356. case 2: return this.z;
  2357. default: throw new Error( 'index is out of range: ' + index );
  2358. }
  2359. }
  2360. clone() {
  2361. return new this.constructor( this.x, this.y, this.z );
  2362. }
  2363. copy( v ) {
  2364. this.x = v.x;
  2365. this.y = v.y;
  2366. this.z = v.z;
  2367. return this;
  2368. }
  2369. add( v ) {
  2370. this.x += v.x;
  2371. this.y += v.y;
  2372. this.z += v.z;
  2373. return this;
  2374. }
  2375. addScalar( s ) {
  2376. this.x += s;
  2377. this.y += s;
  2378. this.z += s;
  2379. return this;
  2380. }
  2381. addVectors( a, b ) {
  2382. this.x = a.x + b.x;
  2383. this.y = a.y + b.y;
  2384. this.z = a.z + b.z;
  2385. return this;
  2386. }
  2387. addScaledVector( v, s ) {
  2388. this.x += v.x * s;
  2389. this.y += v.y * s;
  2390. this.z += v.z * s;
  2391. return this;
  2392. }
  2393. sub( v ) {
  2394. this.x -= v.x;
  2395. this.y -= v.y;
  2396. this.z -= v.z;
  2397. return this;
  2398. }
  2399. subScalar( s ) {
  2400. this.x -= s;
  2401. this.y -= s;
  2402. this.z -= s;
  2403. return this;
  2404. }
  2405. subVectors( a, b ) {
  2406. this.x = a.x - b.x;
  2407. this.y = a.y - b.y;
  2408. this.z = a.z - b.z;
  2409. return this;
  2410. }
  2411. multiply( v ) {
  2412. this.x *= v.x;
  2413. this.y *= v.y;
  2414. this.z *= v.z;
  2415. return this;
  2416. }
  2417. multiplyScalar( scalar ) {
  2418. this.x *= scalar;
  2419. this.y *= scalar;
  2420. this.z *= scalar;
  2421. return this;
  2422. }
  2423. multiplyVectors( a, b ) {
  2424. this.x = a.x * b.x;
  2425. this.y = a.y * b.y;
  2426. this.z = a.z * b.z;
  2427. return this;
  2428. }
  2429. applyEuler( euler ) {
  2430. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2431. }
  2432. applyAxisAngle( axis, angle ) {
  2433. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2434. }
  2435. applyMatrix3( m ) {
  2436. const x = this.x, y = this.y, z = this.z;
  2437. const e = m.elements;
  2438. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2439. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2440. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2441. return this;
  2442. }
  2443. applyNormalMatrix( m ) {
  2444. return this.applyMatrix3( m ).normalize();
  2445. }
  2446. applyMatrix4( m ) {
  2447. const x = this.x, y = this.y, z = this.z;
  2448. const e = m.elements;
  2449. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2450. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2451. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2452. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2453. return this;
  2454. }
  2455. applyQuaternion( q ) {
  2456. const x = this.x, y = this.y, z = this.z;
  2457. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2458. // calculate quat * vector
  2459. const ix = qw * x + qy * z - qz * y;
  2460. const iy = qw * y + qz * x - qx * z;
  2461. const iz = qw * z + qx * y - qy * x;
  2462. const iw = - qx * x - qy * y - qz * z;
  2463. // calculate result * inverse quat
  2464. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2465. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2466. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2467. return this;
  2468. }
  2469. project( camera ) {
  2470. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2471. }
  2472. unproject( camera ) {
  2473. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2474. }
  2475. transformDirection( m ) {
  2476. // input: THREE.Matrix4 affine matrix
  2477. // vector interpreted as a direction
  2478. const x = this.x, y = this.y, z = this.z;
  2479. const e = m.elements;
  2480. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2481. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2482. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2483. return this.normalize();
  2484. }
  2485. divide( v ) {
  2486. this.x /= v.x;
  2487. this.y /= v.y;
  2488. this.z /= v.z;
  2489. return this;
  2490. }
  2491. divideScalar( scalar ) {
  2492. return this.multiplyScalar( 1 / scalar );
  2493. }
  2494. min( v ) {
  2495. this.x = Math.min( this.x, v.x );
  2496. this.y = Math.min( this.y, v.y );
  2497. this.z = Math.min( this.z, v.z );
  2498. return this;
  2499. }
  2500. max( v ) {
  2501. this.x = Math.max( this.x, v.x );
  2502. this.y = Math.max( this.y, v.y );
  2503. this.z = Math.max( this.z, v.z );
  2504. return this;
  2505. }
  2506. clamp( min, max ) {
  2507. // assumes min < max, componentwise
  2508. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2509. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2510. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2511. return this;
  2512. }
  2513. clampScalar( minVal, maxVal ) {
  2514. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2515. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2516. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2517. return this;
  2518. }
  2519. clampLength( min, max ) {
  2520. const length = this.length();
  2521. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2522. }
  2523. floor() {
  2524. this.x = Math.floor( this.x );
  2525. this.y = Math.floor( this.y );
  2526. this.z = Math.floor( this.z );
  2527. return this;
  2528. }
  2529. ceil() {
  2530. this.x = Math.ceil( this.x );
  2531. this.y = Math.ceil( this.y );
  2532. this.z = Math.ceil( this.z );
  2533. return this;
  2534. }
  2535. round() {
  2536. this.x = Math.round( this.x );
  2537. this.y = Math.round( this.y );
  2538. this.z = Math.round( this.z );
  2539. return this;
  2540. }
  2541. roundToZero() {
  2542. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2543. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2544. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2545. return this;
  2546. }
  2547. negate() {
  2548. this.x = - this.x;
  2549. this.y = - this.y;
  2550. this.z = - this.z;
  2551. return this;
  2552. }
  2553. dot( v ) {
  2554. return this.x * v.x + this.y * v.y + this.z * v.z;
  2555. }
  2556. // TODO lengthSquared?
  2557. lengthSq() {
  2558. return this.x * this.x + this.y * this.y + this.z * this.z;
  2559. }
  2560. length() {
  2561. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2562. }
  2563. manhattanLength() {
  2564. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2565. }
  2566. normalize() {
  2567. return this.divideScalar( this.length() || 1 );
  2568. }
  2569. setLength( length ) {
  2570. return this.normalize().multiplyScalar( length );
  2571. }
  2572. lerp( v, alpha ) {
  2573. this.x += ( v.x - this.x ) * alpha;
  2574. this.y += ( v.y - this.y ) * alpha;
  2575. this.z += ( v.z - this.z ) * alpha;
  2576. return this;
  2577. }
  2578. lerpVectors( v1, v2, alpha ) {
  2579. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2580. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2581. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2582. return this;
  2583. }
  2584. cross( v ) {
  2585. return this.crossVectors( this, v );
  2586. }
  2587. crossVectors( a, b ) {
  2588. const ax = a.x, ay = a.y, az = a.z;
  2589. const bx = b.x, by = b.y, bz = b.z;
  2590. this.x = ay * bz - az * by;
  2591. this.y = az * bx - ax * bz;
  2592. this.z = ax * by - ay * bx;
  2593. return this;
  2594. }
  2595. projectOnVector( v ) {
  2596. const denominator = v.lengthSq();
  2597. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2598. const scalar = v.dot( this ) / denominator;
  2599. return this.copy( v ).multiplyScalar( scalar );
  2600. }
  2601. projectOnPlane( planeNormal ) {
  2602. _vector$b.copy( this ).projectOnVector( planeNormal );
  2603. return this.sub( _vector$b );
  2604. }
  2605. reflect( normal ) {
  2606. // reflect incident vector off plane orthogonal to normal
  2607. // normal is assumed to have unit length
  2608. return this.sub( _vector$b.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2609. }
  2610. angleTo( v ) {
  2611. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2612. if ( denominator === 0 ) return Math.PI / 2;
  2613. const theta = this.dot( v ) / denominator;
  2614. // clamp, to handle numerical problems
  2615. return Math.acos( clamp( theta, - 1, 1 ) );
  2616. }
  2617. distanceTo( v ) {
  2618. return Math.sqrt( this.distanceToSquared( v ) );
  2619. }
  2620. distanceToSquared( v ) {
  2621. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2622. return dx * dx + dy * dy + dz * dz;
  2623. }
  2624. manhattanDistanceTo( v ) {
  2625. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2626. }
  2627. setFromSpherical( s ) {
  2628. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2629. }
  2630. setFromSphericalCoords( radius, phi, theta ) {
  2631. const sinPhiRadius = Math.sin( phi ) * radius;
  2632. this.x = sinPhiRadius * Math.sin( theta );
  2633. this.y = Math.cos( phi ) * radius;
  2634. this.z = sinPhiRadius * Math.cos( theta );
  2635. return this;
  2636. }
  2637. setFromCylindrical( c ) {
  2638. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2639. }
  2640. setFromCylindricalCoords( radius, theta, y ) {
  2641. this.x = radius * Math.sin( theta );
  2642. this.y = y;
  2643. this.z = radius * Math.cos( theta );
  2644. return this;
  2645. }
  2646. setFromMatrixPosition( m ) {
  2647. const e = m.elements;
  2648. this.x = e[ 12 ];
  2649. this.y = e[ 13 ];
  2650. this.z = e[ 14 ];
  2651. return this;
  2652. }
  2653. setFromMatrixScale( m ) {
  2654. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2655. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2656. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2657. this.x = sx;
  2658. this.y = sy;
  2659. this.z = sz;
  2660. return this;
  2661. }
  2662. setFromMatrixColumn( m, index ) {
  2663. return this.fromArray( m.elements, index * 4 );
  2664. }
  2665. setFromMatrix3Column( m, index ) {
  2666. return this.fromArray( m.elements, index * 3 );
  2667. }
  2668. setFromEuler( e ) {
  2669. this.x = e._x;
  2670. this.y = e._y;
  2671. this.z = e._z;
  2672. return this;
  2673. }
  2674. setFromColor( c ) {
  2675. this.x = c.r;
  2676. this.y = c.g;
  2677. this.z = c.b;
  2678. return this;
  2679. }
  2680. equals( v ) {
  2681. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2682. }
  2683. fromArray( array, offset = 0 ) {
  2684. this.x = array[ offset ];
  2685. this.y = array[ offset + 1 ];
  2686. this.z = array[ offset + 2 ];
  2687. return this;
  2688. }
  2689. toArray( array = [], offset = 0 ) {
  2690. array[ offset ] = this.x;
  2691. array[ offset + 1 ] = this.y;
  2692. array[ offset + 2 ] = this.z;
  2693. return array;
  2694. }
  2695. fromBufferAttribute( attribute, index ) {
  2696. this.x = attribute.getX( index );
  2697. this.y = attribute.getY( index );
  2698. this.z = attribute.getZ( index );
  2699. return this;
  2700. }
  2701. random() {
  2702. this.x = Math.random();
  2703. this.y = Math.random();
  2704. this.z = Math.random();
  2705. return this;
  2706. }
  2707. randomDirection() {
  2708. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2709. const u = ( Math.random() - 0.5 ) * 2;
  2710. const t = Math.random() * Math.PI * 2;
  2711. const f = Math.sqrt( 1 - u ** 2 );
  2712. this.x = f * Math.cos( t );
  2713. this.y = f * Math.sin( t );
  2714. this.z = u;
  2715. return this;
  2716. }
  2717. *[ Symbol.iterator ]() {
  2718. yield this.x;
  2719. yield this.y;
  2720. yield this.z;
  2721. }
  2722. }
  2723. const _vector$b = /*@__PURE__*/ new Vector3();
  2724. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2725. class Box3 {
  2726. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2727. this.isBox3 = true;
  2728. this.min = min;
  2729. this.max = max;
  2730. }
  2731. set( min, max ) {
  2732. this.min.copy( min );
  2733. this.max.copy( max );
  2734. return this;
  2735. }
  2736. setFromArray( array ) {
  2737. this.makeEmpty();
  2738. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2739. this.expandByPoint( _vector$a.fromArray( array, i ) );
  2740. }
  2741. return this;
  2742. }
  2743. setFromBufferAttribute( attribute ) {
  2744. this.makeEmpty();
  2745. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2746. this.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );
  2747. }
  2748. return this;
  2749. }
  2750. setFromPoints( points ) {
  2751. this.makeEmpty();
  2752. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2753. this.expandByPoint( points[ i ] );
  2754. }
  2755. return this;
  2756. }
  2757. setFromCenterAndSize( center, size ) {
  2758. const halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );
  2759. this.min.copy( center ).sub( halfSize );
  2760. this.max.copy( center ).add( halfSize );
  2761. return this;
  2762. }
  2763. setFromObject( object, precise = false ) {
  2764. this.makeEmpty();
  2765. return this.expandByObject( object, precise );
  2766. }
  2767. clone() {
  2768. return new this.constructor().copy( this );
  2769. }
  2770. copy( box ) {
  2771. this.min.copy( box.min );
  2772. this.max.copy( box.max );
  2773. return this;
  2774. }
  2775. makeEmpty() {
  2776. this.min.x = this.min.y = this.min.z = + Infinity;
  2777. this.max.x = this.max.y = this.max.z = - Infinity;
  2778. return this;
  2779. }
  2780. isEmpty() {
  2781. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2782. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2783. }
  2784. getCenter( target ) {
  2785. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2786. }
  2787. getSize( target ) {
  2788. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2789. }
  2790. expandByPoint( point ) {
  2791. this.min.min( point );
  2792. this.max.max( point );
  2793. return this;
  2794. }
  2795. expandByVector( vector ) {
  2796. this.min.sub( vector );
  2797. this.max.add( vector );
  2798. return this;
  2799. }
  2800. expandByScalar( scalar ) {
  2801. this.min.addScalar( - scalar );
  2802. this.max.addScalar( scalar );
  2803. return this;
  2804. }
  2805. expandByObject( object, precise = false ) {
  2806. // Computes the world-axis-aligned bounding box of an object (including its children),
  2807. // accounting for both the object's, and children's, world transforms
  2808. object.updateWorldMatrix( false, false );
  2809. if ( object.boundingBox !== undefined ) {
  2810. if ( object.boundingBox === null ) {
  2811. object.computeBoundingBox();
  2812. }
  2813. _box$3.copy( object.boundingBox );
  2814. _box$3.applyMatrix4( object.matrixWorld );
  2815. this.union( _box$3 );
  2816. } else {
  2817. const geometry = object.geometry;
  2818. if ( geometry !== undefined ) {
  2819. if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {
  2820. const position = geometry.attributes.position;
  2821. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2822. _vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2823. this.expandByPoint( _vector$a );
  2824. }
  2825. } else {
  2826. if ( geometry.boundingBox === null ) {
  2827. geometry.computeBoundingBox();
  2828. }
  2829. _box$3.copy( geometry.boundingBox );
  2830. _box$3.applyMatrix4( object.matrixWorld );
  2831. this.union( _box$3 );
  2832. }
  2833. }
  2834. }
  2835. const children = object.children;
  2836. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2837. this.expandByObject( children[ i ], precise );
  2838. }
  2839. return this;
  2840. }
  2841. containsPoint( point ) {
  2842. return point.x < this.min.x || point.x > this.max.x ||
  2843. point.y < this.min.y || point.y > this.max.y ||
  2844. point.z < this.min.z || point.z > this.max.z ? false : true;
  2845. }
  2846. containsBox( box ) {
  2847. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2848. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2849. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2850. }
  2851. getParameter( point, target ) {
  2852. // This can potentially have a divide by zero if the box
  2853. // has a size dimension of 0.
  2854. return target.set(
  2855. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2856. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2857. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2858. );
  2859. }
  2860. intersectsBox( box ) {
  2861. // using 6 splitting planes to rule out intersections.
  2862. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2863. box.max.y < this.min.y || box.min.y > this.max.y ||
  2864. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2865. }
  2866. intersectsSphere( sphere ) {
  2867. // Find the point on the AABB closest to the sphere center.
  2868. this.clampPoint( sphere.center, _vector$a );
  2869. // If that point is inside the sphere, the AABB and sphere intersect.
  2870. return _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2871. }
  2872. intersectsPlane( plane ) {
  2873. // We compute the minimum and maximum dot product values. If those values
  2874. // are on the same side (back or front) of the plane, then there is no intersection.
  2875. let min, max;
  2876. if ( plane.normal.x > 0 ) {
  2877. min = plane.normal.x * this.min.x;
  2878. max = plane.normal.x * this.max.x;
  2879. } else {
  2880. min = plane.normal.x * this.max.x;
  2881. max = plane.normal.x * this.min.x;
  2882. }
  2883. if ( plane.normal.y > 0 ) {
  2884. min += plane.normal.y * this.min.y;
  2885. max += plane.normal.y * this.max.y;
  2886. } else {
  2887. min += plane.normal.y * this.max.y;
  2888. max += plane.normal.y * this.min.y;
  2889. }
  2890. if ( plane.normal.z > 0 ) {
  2891. min += plane.normal.z * this.min.z;
  2892. max += plane.normal.z * this.max.z;
  2893. } else {
  2894. min += plane.normal.z * this.max.z;
  2895. max += plane.normal.z * this.min.z;
  2896. }
  2897. return ( min <= - plane.constant && max >= - plane.constant );
  2898. }
  2899. intersectsTriangle( triangle ) {
  2900. if ( this.isEmpty() ) {
  2901. return false;
  2902. }
  2903. // compute box center and extents
  2904. this.getCenter( _center );
  2905. _extents.subVectors( this.max, _center );
  2906. // translate triangle to aabb origin
  2907. _v0$2.subVectors( triangle.a, _center );
  2908. _v1$7.subVectors( triangle.b, _center );
  2909. _v2$4.subVectors( triangle.c, _center );
  2910. // compute edge vectors for triangle
  2911. _f0.subVectors( _v1$7, _v0$2 );
  2912. _f1.subVectors( _v2$4, _v1$7 );
  2913. _f2.subVectors( _v0$2, _v2$4 );
  2914. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2915. // 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
  2916. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2917. let axes = [
  2918. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2919. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2920. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2921. ];
  2922. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2923. return false;
  2924. }
  2925. // test 3 face normals from the aabb
  2926. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2927. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2928. return false;
  2929. }
  2930. // finally testing the face normal of the triangle
  2931. // use already existing triangle edge vectors here
  2932. _triangleNormal.crossVectors( _f0, _f1 );
  2933. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2934. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2935. }
  2936. clampPoint( point, target ) {
  2937. return target.copy( point ).clamp( this.min, this.max );
  2938. }
  2939. distanceToPoint( point ) {
  2940. return this.clampPoint( point, _vector$a ).distanceTo( point );
  2941. }
  2942. getBoundingSphere( target ) {
  2943. if ( this.isEmpty() ) {
  2944. target.makeEmpty();
  2945. } else {
  2946. this.getCenter( target.center );
  2947. target.radius = this.getSize( _vector$a ).length() * 0.5;
  2948. }
  2949. return target;
  2950. }
  2951. intersect( box ) {
  2952. this.min.max( box.min );
  2953. this.max.min( box.max );
  2954. // 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.
  2955. if ( this.isEmpty() ) this.makeEmpty();
  2956. return this;
  2957. }
  2958. union( box ) {
  2959. this.min.min( box.min );
  2960. this.max.max( box.max );
  2961. return this;
  2962. }
  2963. applyMatrix4( matrix ) {
  2964. // transform of empty box is an empty box.
  2965. if ( this.isEmpty() ) return this;
  2966. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2967. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2968. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2969. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2970. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2971. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2972. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2973. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2974. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2975. this.setFromPoints( _points );
  2976. return this;
  2977. }
  2978. translate( offset ) {
  2979. this.min.add( offset );
  2980. this.max.add( offset );
  2981. return this;
  2982. }
  2983. equals( box ) {
  2984. return box.min.equals( this.min ) && box.max.equals( this.max );
  2985. }
  2986. }
  2987. const _points = [
  2988. /*@__PURE__*/ new Vector3(),
  2989. /*@__PURE__*/ new Vector3(),
  2990. /*@__PURE__*/ new Vector3(),
  2991. /*@__PURE__*/ new Vector3(),
  2992. /*@__PURE__*/ new Vector3(),
  2993. /*@__PURE__*/ new Vector3(),
  2994. /*@__PURE__*/ new Vector3(),
  2995. /*@__PURE__*/ new Vector3()
  2996. ];
  2997. const _vector$a = /*@__PURE__*/ new Vector3();
  2998. const _box$3 = /*@__PURE__*/ new Box3();
  2999. // triangle centered vertices
  3000. const _v0$2 = /*@__PURE__*/ new Vector3();
  3001. const _v1$7 = /*@__PURE__*/ new Vector3();
  3002. const _v2$4 = /*@__PURE__*/ new Vector3();
  3003. // triangle edge vectors
  3004. const _f0 = /*@__PURE__*/ new Vector3();
  3005. const _f1 = /*@__PURE__*/ new Vector3();
  3006. const _f2 = /*@__PURE__*/ new Vector3();
  3007. const _center = /*@__PURE__*/ new Vector3();
  3008. const _extents = /*@__PURE__*/ new Vector3();
  3009. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3010. const _testAxis = /*@__PURE__*/ new Vector3();
  3011. function satForAxes( axes, v0, v1, v2, extents ) {
  3012. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3013. _testAxis.fromArray( axes, i );
  3014. // project the aabb onto the separating axis
  3015. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3016. // project all 3 vertices of the triangle onto the separating axis
  3017. const p0 = v0.dot( _testAxis );
  3018. const p1 = v1.dot( _testAxis );
  3019. const p2 = v2.dot( _testAxis );
  3020. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3021. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3022. // points of the projected triangle are outside the projected half-length of the aabb
  3023. // the axis is separating and we can exit
  3024. return false;
  3025. }
  3026. }
  3027. return true;
  3028. }
  3029. const _box$2 = /*@__PURE__*/ new Box3();
  3030. const _v1$6 = /*@__PURE__*/ new Vector3();
  3031. const _v2$3 = /*@__PURE__*/ new Vector3();
  3032. class Sphere {
  3033. constructor( center = new Vector3(), radius = - 1 ) {
  3034. this.center = center;
  3035. this.radius = radius;
  3036. }
  3037. set( center, radius ) {
  3038. this.center.copy( center );
  3039. this.radius = radius;
  3040. return this;
  3041. }
  3042. setFromPoints( points, optionalCenter ) {
  3043. const center = this.center;
  3044. if ( optionalCenter !== undefined ) {
  3045. center.copy( optionalCenter );
  3046. } else {
  3047. _box$2.setFromPoints( points ).getCenter( center );
  3048. }
  3049. let maxRadiusSq = 0;
  3050. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3051. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3052. }
  3053. this.radius = Math.sqrt( maxRadiusSq );
  3054. return this;
  3055. }
  3056. copy( sphere ) {
  3057. this.center.copy( sphere.center );
  3058. this.radius = sphere.radius;
  3059. return this;
  3060. }
  3061. isEmpty() {
  3062. return ( this.radius < 0 );
  3063. }
  3064. makeEmpty() {
  3065. this.center.set( 0, 0, 0 );
  3066. this.radius = - 1;
  3067. return this;
  3068. }
  3069. containsPoint( point ) {
  3070. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3071. }
  3072. distanceToPoint( point ) {
  3073. return ( point.distanceTo( this.center ) - this.radius );
  3074. }
  3075. intersectsSphere( sphere ) {
  3076. const radiusSum = this.radius + sphere.radius;
  3077. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3078. }
  3079. intersectsBox( box ) {
  3080. return box.intersectsSphere( this );
  3081. }
  3082. intersectsPlane( plane ) {
  3083. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3084. }
  3085. clampPoint( point, target ) {
  3086. const deltaLengthSq = this.center.distanceToSquared( point );
  3087. target.copy( point );
  3088. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3089. target.sub( this.center ).normalize();
  3090. target.multiplyScalar( this.radius ).add( this.center );
  3091. }
  3092. return target;
  3093. }
  3094. getBoundingBox( target ) {
  3095. if ( this.isEmpty() ) {
  3096. // Empty sphere produces empty bounding box
  3097. target.makeEmpty();
  3098. return target;
  3099. }
  3100. target.set( this.center, this.center );
  3101. target.expandByScalar( this.radius );
  3102. return target;
  3103. }
  3104. applyMatrix4( matrix ) {
  3105. this.center.applyMatrix4( matrix );
  3106. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3107. return this;
  3108. }
  3109. translate( offset ) {
  3110. this.center.add( offset );
  3111. return this;
  3112. }
  3113. expandByPoint( point ) {
  3114. if ( this.isEmpty() ) {
  3115. this.center.copy( point );
  3116. this.radius = 0;
  3117. return this;
  3118. }
  3119. _v1$6.subVectors( point, this.center );
  3120. const lengthSq = _v1$6.lengthSq();
  3121. if ( lengthSq > ( this.radius * this.radius ) ) {
  3122. // calculate the minimal sphere
  3123. const length = Math.sqrt( lengthSq );
  3124. const delta = ( length - this.radius ) * 0.5;
  3125. this.center.addScaledVector( _v1$6, delta / length );
  3126. this.radius += delta;
  3127. }
  3128. return this;
  3129. }
  3130. union( sphere ) {
  3131. if ( sphere.isEmpty() ) {
  3132. return this;
  3133. }
  3134. if ( this.isEmpty() ) {
  3135. this.copy( sphere );
  3136. return this;
  3137. }
  3138. if ( this.center.equals( sphere.center ) === true ) {
  3139. this.radius = Math.max( this.radius, sphere.radius );
  3140. } else {
  3141. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3142. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3143. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3144. }
  3145. return this;
  3146. }
  3147. equals( sphere ) {
  3148. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3149. }
  3150. clone() {
  3151. return new this.constructor().copy( this );
  3152. }
  3153. }
  3154. const _vector$9 = /*@__PURE__*/ new Vector3();
  3155. const _segCenter = /*@__PURE__*/ new Vector3();
  3156. const _segDir = /*@__PURE__*/ new Vector3();
  3157. const _diff = /*@__PURE__*/ new Vector3();
  3158. const _edge1 = /*@__PURE__*/ new Vector3();
  3159. const _edge2 = /*@__PURE__*/ new Vector3();
  3160. const _normal$1 = /*@__PURE__*/ new Vector3();
  3161. class Ray {
  3162. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3163. this.origin = origin;
  3164. this.direction = direction;
  3165. }
  3166. set( origin, direction ) {
  3167. this.origin.copy( origin );
  3168. this.direction.copy( direction );
  3169. return this;
  3170. }
  3171. copy( ray ) {
  3172. this.origin.copy( ray.origin );
  3173. this.direction.copy( ray.direction );
  3174. return this;
  3175. }
  3176. at( t, target ) {
  3177. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3178. }
  3179. lookAt( v ) {
  3180. this.direction.copy( v ).sub( this.origin ).normalize();
  3181. return this;
  3182. }
  3183. recast( t ) {
  3184. this.origin.copy( this.at( t, _vector$9 ) );
  3185. return this;
  3186. }
  3187. closestPointToPoint( point, target ) {
  3188. target.subVectors( point, this.origin );
  3189. const directionDistance = target.dot( this.direction );
  3190. if ( directionDistance < 0 ) {
  3191. return target.copy( this.origin );
  3192. }
  3193. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3194. }
  3195. distanceToPoint( point ) {
  3196. return Math.sqrt( this.distanceSqToPoint( point ) );
  3197. }
  3198. distanceSqToPoint( point ) {
  3199. const directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );
  3200. // point behind the ray
  3201. if ( directionDistance < 0 ) {
  3202. return this.origin.distanceToSquared( point );
  3203. }
  3204. _vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3205. return _vector$9.distanceToSquared( point );
  3206. }
  3207. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3208. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3209. // It returns the min distance between the ray and the segment
  3210. // defined by v0 and v1
  3211. // It can also set two optional targets :
  3212. // - The closest point on the ray
  3213. // - The closest point on the segment
  3214. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3215. _segDir.copy( v1 ).sub( v0 ).normalize();
  3216. _diff.copy( this.origin ).sub( _segCenter );
  3217. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3218. const a01 = - this.direction.dot( _segDir );
  3219. const b0 = _diff.dot( this.direction );
  3220. const b1 = - _diff.dot( _segDir );
  3221. const c = _diff.lengthSq();
  3222. const det = Math.abs( 1 - a01 * a01 );
  3223. let s0, s1, sqrDist, extDet;
  3224. if ( det > 0 ) {
  3225. // The ray and segment are not parallel.
  3226. s0 = a01 * b1 - b0;
  3227. s1 = a01 * b0 - b1;
  3228. extDet = segExtent * det;
  3229. if ( s0 >= 0 ) {
  3230. if ( s1 >= - extDet ) {
  3231. if ( s1 <= extDet ) {
  3232. // region 0
  3233. // Minimum at interior points of ray and segment.
  3234. const invDet = 1 / det;
  3235. s0 *= invDet;
  3236. s1 *= invDet;
  3237. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3238. } else {
  3239. // region 1
  3240. s1 = segExtent;
  3241. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3242. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3243. }
  3244. } else {
  3245. // region 5
  3246. s1 = - segExtent;
  3247. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3248. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3249. }
  3250. } else {
  3251. if ( s1 <= - extDet ) {
  3252. // region 4
  3253. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3254. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3255. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3256. } else if ( s1 <= extDet ) {
  3257. // region 3
  3258. s0 = 0;
  3259. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3260. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3261. } else {
  3262. // region 2
  3263. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3264. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3265. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3266. }
  3267. }
  3268. } else {
  3269. // Ray and segment are parallel.
  3270. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3271. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3272. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3273. }
  3274. if ( optionalPointOnRay ) {
  3275. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3276. }
  3277. if ( optionalPointOnSegment ) {
  3278. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3279. }
  3280. return sqrDist;
  3281. }
  3282. intersectSphere( sphere, target ) {
  3283. _vector$9.subVectors( sphere.center, this.origin );
  3284. const tca = _vector$9.dot( this.direction );
  3285. const d2 = _vector$9.dot( _vector$9 ) - tca * tca;
  3286. const radius2 = sphere.radius * sphere.radius;
  3287. if ( d2 > radius2 ) return null;
  3288. const thc = Math.sqrt( radius2 - d2 );
  3289. // t0 = first intersect point - entrance on front of sphere
  3290. const t0 = tca - thc;
  3291. // t1 = second intersect point - exit point on back of sphere
  3292. const t1 = tca + thc;
  3293. // test to see if t1 is behind the ray - if so, return null
  3294. if ( t1 < 0 ) return null;
  3295. // test to see if t0 is behind the ray:
  3296. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3297. // in order to always return an intersect point that is in front of the ray.
  3298. if ( t0 < 0 ) return this.at( t1, target );
  3299. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3300. return this.at( t0, target );
  3301. }
  3302. intersectsSphere( sphere ) {
  3303. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3304. }
  3305. distanceToPlane( plane ) {
  3306. const denominator = plane.normal.dot( this.direction );
  3307. if ( denominator === 0 ) {
  3308. // line is coplanar, return origin
  3309. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3310. return 0;
  3311. }
  3312. // Null is preferable to undefined since undefined means.... it is undefined
  3313. return null;
  3314. }
  3315. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3316. // Return if the ray never intersects the plane
  3317. return t >= 0 ? t : null;
  3318. }
  3319. intersectPlane( plane, target ) {
  3320. const t = this.distanceToPlane( plane );
  3321. if ( t === null ) {
  3322. return null;
  3323. }
  3324. return this.at( t, target );
  3325. }
  3326. intersectsPlane( plane ) {
  3327. // check if the ray lies on the plane first
  3328. const distToPoint = plane.distanceToPoint( this.origin );
  3329. if ( distToPoint === 0 ) {
  3330. return true;
  3331. }
  3332. const denominator = plane.normal.dot( this.direction );
  3333. if ( denominator * distToPoint < 0 ) {
  3334. return true;
  3335. }
  3336. // ray origin is behind the plane (and is pointing behind it)
  3337. return false;
  3338. }
  3339. intersectBox( box, target ) {
  3340. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3341. const invdirx = 1 / this.direction.x,
  3342. invdiry = 1 / this.direction.y,
  3343. invdirz = 1 / this.direction.z;
  3344. const origin = this.origin;
  3345. if ( invdirx >= 0 ) {
  3346. tmin = ( box.min.x - origin.x ) * invdirx;
  3347. tmax = ( box.max.x - origin.x ) * invdirx;
  3348. } else {
  3349. tmin = ( box.max.x - origin.x ) * invdirx;
  3350. tmax = ( box.min.x - origin.x ) * invdirx;
  3351. }
  3352. if ( invdiry >= 0 ) {
  3353. tymin = ( box.min.y - origin.y ) * invdiry;
  3354. tymax = ( box.max.y - origin.y ) * invdiry;
  3355. } else {
  3356. tymin = ( box.max.y - origin.y ) * invdiry;
  3357. tymax = ( box.min.y - origin.y ) * invdiry;
  3358. }
  3359. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3360. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3361. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3362. if ( invdirz >= 0 ) {
  3363. tzmin = ( box.min.z - origin.z ) * invdirz;
  3364. tzmax = ( box.max.z - origin.z ) * invdirz;
  3365. } else {
  3366. tzmin = ( box.max.z - origin.z ) * invdirz;
  3367. tzmax = ( box.min.z - origin.z ) * invdirz;
  3368. }
  3369. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3370. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3371. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3372. //return point closest to the ray (positive side)
  3373. if ( tmax < 0 ) return null;
  3374. return this.at( tmin >= 0 ? tmin : tmax, target );
  3375. }
  3376. intersectsBox( box ) {
  3377. return this.intersectBox( box, _vector$9 ) !== null;
  3378. }
  3379. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3380. // Compute the offset origin, edges, and normal.
  3381. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3382. _edge1.subVectors( b, a );
  3383. _edge2.subVectors( c, a );
  3384. _normal$1.crossVectors( _edge1, _edge2 );
  3385. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3386. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3387. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3388. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3389. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3390. let DdN = this.direction.dot( _normal$1 );
  3391. let sign;
  3392. if ( DdN > 0 ) {
  3393. if ( backfaceCulling ) return null;
  3394. sign = 1;
  3395. } else if ( DdN < 0 ) {
  3396. sign = - 1;
  3397. DdN = - DdN;
  3398. } else {
  3399. return null;
  3400. }
  3401. _diff.subVectors( this.origin, a );
  3402. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3403. // b1 < 0, no intersection
  3404. if ( DdQxE2 < 0 ) {
  3405. return null;
  3406. }
  3407. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3408. // b2 < 0, no intersection
  3409. if ( DdE1xQ < 0 ) {
  3410. return null;
  3411. }
  3412. // b1+b2 > 1, no intersection
  3413. if ( DdQxE2 + DdE1xQ > DdN ) {
  3414. return null;
  3415. }
  3416. // Line intersects triangle, check if ray does.
  3417. const QdN = - sign * _diff.dot( _normal$1 );
  3418. // t < 0, no intersection
  3419. if ( QdN < 0 ) {
  3420. return null;
  3421. }
  3422. // Ray intersects triangle.
  3423. return this.at( QdN / DdN, target );
  3424. }
  3425. applyMatrix4( matrix4 ) {
  3426. this.origin.applyMatrix4( matrix4 );
  3427. this.direction.transformDirection( matrix4 );
  3428. return this;
  3429. }
  3430. equals( ray ) {
  3431. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3432. }
  3433. clone() {
  3434. return new this.constructor().copy( this );
  3435. }
  3436. }
  3437. class Matrix4 {
  3438. constructor() {
  3439. Matrix4.prototype.isMatrix4 = true;
  3440. this.elements = [
  3441. 1, 0, 0, 0,
  3442. 0, 1, 0, 0,
  3443. 0, 0, 1, 0,
  3444. 0, 0, 0, 1
  3445. ];
  3446. }
  3447. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3448. const te = this.elements;
  3449. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3450. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3451. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3452. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3453. return this;
  3454. }
  3455. identity() {
  3456. this.set(
  3457. 1, 0, 0, 0,
  3458. 0, 1, 0, 0,
  3459. 0, 0, 1, 0,
  3460. 0, 0, 0, 1
  3461. );
  3462. return this;
  3463. }
  3464. clone() {
  3465. return new Matrix4().fromArray( this.elements );
  3466. }
  3467. copy( m ) {
  3468. const te = this.elements;
  3469. const me = m.elements;
  3470. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3471. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3472. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3473. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3474. return this;
  3475. }
  3476. copyPosition( m ) {
  3477. const te = this.elements, me = m.elements;
  3478. te[ 12 ] = me[ 12 ];
  3479. te[ 13 ] = me[ 13 ];
  3480. te[ 14 ] = me[ 14 ];
  3481. return this;
  3482. }
  3483. setFromMatrix3( m ) {
  3484. const me = m.elements;
  3485. this.set(
  3486. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3487. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3488. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3489. 0, 0, 0, 1
  3490. );
  3491. return this;
  3492. }
  3493. extractBasis( xAxis, yAxis, zAxis ) {
  3494. xAxis.setFromMatrixColumn( this, 0 );
  3495. yAxis.setFromMatrixColumn( this, 1 );
  3496. zAxis.setFromMatrixColumn( this, 2 );
  3497. return this;
  3498. }
  3499. makeBasis( xAxis, yAxis, zAxis ) {
  3500. this.set(
  3501. xAxis.x, yAxis.x, zAxis.x, 0,
  3502. xAxis.y, yAxis.y, zAxis.y, 0,
  3503. xAxis.z, yAxis.z, zAxis.z, 0,
  3504. 0, 0, 0, 1
  3505. );
  3506. return this;
  3507. }
  3508. extractRotation( m ) {
  3509. // this method does not support reflection matrices
  3510. const te = this.elements;
  3511. const me = m.elements;
  3512. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3513. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3514. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3515. te[ 0 ] = me[ 0 ] * scaleX;
  3516. te[ 1 ] = me[ 1 ] * scaleX;
  3517. te[ 2 ] = me[ 2 ] * scaleX;
  3518. te[ 3 ] = 0;
  3519. te[ 4 ] = me[ 4 ] * scaleY;
  3520. te[ 5 ] = me[ 5 ] * scaleY;
  3521. te[ 6 ] = me[ 6 ] * scaleY;
  3522. te[ 7 ] = 0;
  3523. te[ 8 ] = me[ 8 ] * scaleZ;
  3524. te[ 9 ] = me[ 9 ] * scaleZ;
  3525. te[ 10 ] = me[ 10 ] * scaleZ;
  3526. te[ 11 ] = 0;
  3527. te[ 12 ] = 0;
  3528. te[ 13 ] = 0;
  3529. te[ 14 ] = 0;
  3530. te[ 15 ] = 1;
  3531. return this;
  3532. }
  3533. makeRotationFromEuler( euler ) {
  3534. const te = this.elements;
  3535. const x = euler.x, y = euler.y, z = euler.z;
  3536. const a = Math.cos( x ), b = Math.sin( x );
  3537. const c = Math.cos( y ), d = Math.sin( y );
  3538. const e = Math.cos( z ), f = Math.sin( z );
  3539. if ( euler.order === 'XYZ' ) {
  3540. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3541. te[ 0 ] = c * e;
  3542. te[ 4 ] = - c * f;
  3543. te[ 8 ] = d;
  3544. te[ 1 ] = af + be * d;
  3545. te[ 5 ] = ae - bf * d;
  3546. te[ 9 ] = - b * c;
  3547. te[ 2 ] = bf - ae * d;
  3548. te[ 6 ] = be + af * d;
  3549. te[ 10 ] = a * c;
  3550. } else if ( euler.order === 'YXZ' ) {
  3551. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3552. te[ 0 ] = ce + df * b;
  3553. te[ 4 ] = de * b - cf;
  3554. te[ 8 ] = a * d;
  3555. te[ 1 ] = a * f;
  3556. te[ 5 ] = a * e;
  3557. te[ 9 ] = - b;
  3558. te[ 2 ] = cf * b - de;
  3559. te[ 6 ] = df + ce * b;
  3560. te[ 10 ] = a * c;
  3561. } else if ( euler.order === 'ZXY' ) {
  3562. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3563. te[ 0 ] = ce - df * b;
  3564. te[ 4 ] = - a * f;
  3565. te[ 8 ] = de + cf * b;
  3566. te[ 1 ] = cf + de * b;
  3567. te[ 5 ] = a * e;
  3568. te[ 9 ] = df - ce * b;
  3569. te[ 2 ] = - a * d;
  3570. te[ 6 ] = b;
  3571. te[ 10 ] = a * c;
  3572. } else if ( euler.order === 'ZYX' ) {
  3573. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3574. te[ 0 ] = c * e;
  3575. te[ 4 ] = be * d - af;
  3576. te[ 8 ] = ae * d + bf;
  3577. te[ 1 ] = c * f;
  3578. te[ 5 ] = bf * d + ae;
  3579. te[ 9 ] = af * d - be;
  3580. te[ 2 ] = - d;
  3581. te[ 6 ] = b * c;
  3582. te[ 10 ] = a * c;
  3583. } else if ( euler.order === 'YZX' ) {
  3584. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3585. te[ 0 ] = c * e;
  3586. te[ 4 ] = bd - ac * f;
  3587. te[ 8 ] = bc * f + ad;
  3588. te[ 1 ] = f;
  3589. te[ 5 ] = a * e;
  3590. te[ 9 ] = - b * e;
  3591. te[ 2 ] = - d * e;
  3592. te[ 6 ] = ad * f + bc;
  3593. te[ 10 ] = ac - bd * f;
  3594. } else if ( euler.order === 'XZY' ) {
  3595. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3596. te[ 0 ] = c * e;
  3597. te[ 4 ] = - f;
  3598. te[ 8 ] = d * e;
  3599. te[ 1 ] = ac * f + bd;
  3600. te[ 5 ] = a * e;
  3601. te[ 9 ] = ad * f - bc;
  3602. te[ 2 ] = bc * f - ad;
  3603. te[ 6 ] = b * e;
  3604. te[ 10 ] = bd * f + ac;
  3605. }
  3606. // bottom row
  3607. te[ 3 ] = 0;
  3608. te[ 7 ] = 0;
  3609. te[ 11 ] = 0;
  3610. // last column
  3611. te[ 12 ] = 0;
  3612. te[ 13 ] = 0;
  3613. te[ 14 ] = 0;
  3614. te[ 15 ] = 1;
  3615. return this;
  3616. }
  3617. makeRotationFromQuaternion( q ) {
  3618. return this.compose( _zero, q, _one );
  3619. }
  3620. lookAt( eye, target, up ) {
  3621. const te = this.elements;
  3622. _z.subVectors( eye, target );
  3623. if ( _z.lengthSq() === 0 ) {
  3624. // eye and target are in the same position
  3625. _z.z = 1;
  3626. }
  3627. _z.normalize();
  3628. _x.crossVectors( up, _z );
  3629. if ( _x.lengthSq() === 0 ) {
  3630. // up and z are parallel
  3631. if ( Math.abs( up.z ) === 1 ) {
  3632. _z.x += 0.0001;
  3633. } else {
  3634. _z.z += 0.0001;
  3635. }
  3636. _z.normalize();
  3637. _x.crossVectors( up, _z );
  3638. }
  3639. _x.normalize();
  3640. _y.crossVectors( _z, _x );
  3641. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3642. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3643. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3644. return this;
  3645. }
  3646. multiply( m ) {
  3647. return this.multiplyMatrices( this, m );
  3648. }
  3649. premultiply( m ) {
  3650. return this.multiplyMatrices( m, this );
  3651. }
  3652. multiplyMatrices( a, b ) {
  3653. const ae = a.elements;
  3654. const be = b.elements;
  3655. const te = this.elements;
  3656. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3657. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3658. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3659. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3660. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3661. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3662. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3663. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3664. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3665. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3666. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3667. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3668. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3669. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3670. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3671. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3672. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3673. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3674. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3675. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3676. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3677. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3678. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3679. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3680. return this;
  3681. }
  3682. multiplyScalar( s ) {
  3683. const te = this.elements;
  3684. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3685. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3686. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3687. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3688. return this;
  3689. }
  3690. determinant() {
  3691. const te = this.elements;
  3692. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3693. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3694. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3695. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3696. //TODO: make this more efficient
  3697. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3698. return (
  3699. n41 * (
  3700. + n14 * n23 * n32
  3701. - n13 * n24 * n32
  3702. - n14 * n22 * n33
  3703. + n12 * n24 * n33
  3704. + n13 * n22 * n34
  3705. - n12 * n23 * n34
  3706. ) +
  3707. n42 * (
  3708. + n11 * n23 * n34
  3709. - n11 * n24 * n33
  3710. + n14 * n21 * n33
  3711. - n13 * n21 * n34
  3712. + n13 * n24 * n31
  3713. - n14 * n23 * n31
  3714. ) +
  3715. n43 * (
  3716. + n11 * n24 * n32
  3717. - n11 * n22 * n34
  3718. - n14 * n21 * n32
  3719. + n12 * n21 * n34
  3720. + n14 * n22 * n31
  3721. - n12 * n24 * n31
  3722. ) +
  3723. n44 * (
  3724. - n13 * n22 * n31
  3725. - n11 * n23 * n32
  3726. + n11 * n22 * n33
  3727. + n13 * n21 * n32
  3728. - n12 * n21 * n33
  3729. + n12 * n23 * n31
  3730. )
  3731. );
  3732. }
  3733. transpose() {
  3734. const te = this.elements;
  3735. let tmp;
  3736. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3737. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3738. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3739. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3740. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3741. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3742. return this;
  3743. }
  3744. setPosition( x, y, z ) {
  3745. const te = this.elements;
  3746. if ( x.isVector3 ) {
  3747. te[ 12 ] = x.x;
  3748. te[ 13 ] = x.y;
  3749. te[ 14 ] = x.z;
  3750. } else {
  3751. te[ 12 ] = x;
  3752. te[ 13 ] = y;
  3753. te[ 14 ] = z;
  3754. }
  3755. return this;
  3756. }
  3757. invert() {
  3758. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3759. const te = this.elements,
  3760. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3761. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3762. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3763. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3764. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3765. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3766. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3767. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3768. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3769. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3770. const detInv = 1 / det;
  3771. te[ 0 ] = t11 * detInv;
  3772. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3773. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3774. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3775. te[ 4 ] = t12 * detInv;
  3776. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3777. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3778. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3779. te[ 8 ] = t13 * detInv;
  3780. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3781. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3782. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3783. te[ 12 ] = t14 * detInv;
  3784. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3785. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3786. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3787. return this;
  3788. }
  3789. scale( v ) {
  3790. const te = this.elements;
  3791. const x = v.x, y = v.y, z = v.z;
  3792. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3793. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3794. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3795. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3796. return this;
  3797. }
  3798. getMaxScaleOnAxis() {
  3799. const te = this.elements;
  3800. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3801. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3802. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3803. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3804. }
  3805. makeTranslation( x, y, z ) {
  3806. this.set(
  3807. 1, 0, 0, x,
  3808. 0, 1, 0, y,
  3809. 0, 0, 1, z,
  3810. 0, 0, 0, 1
  3811. );
  3812. return this;
  3813. }
  3814. makeRotationX( theta ) {
  3815. const c = Math.cos( theta ), s = Math.sin( theta );
  3816. this.set(
  3817. 1, 0, 0, 0,
  3818. 0, c, - s, 0,
  3819. 0, s, c, 0,
  3820. 0, 0, 0, 1
  3821. );
  3822. return this;
  3823. }
  3824. makeRotationY( theta ) {
  3825. const c = Math.cos( theta ), s = Math.sin( theta );
  3826. this.set(
  3827. c, 0, s, 0,
  3828. 0, 1, 0, 0,
  3829. - s, 0, c, 0,
  3830. 0, 0, 0, 1
  3831. );
  3832. return this;
  3833. }
  3834. makeRotationZ( theta ) {
  3835. const c = Math.cos( theta ), s = Math.sin( theta );
  3836. this.set(
  3837. c, - s, 0, 0,
  3838. s, c, 0, 0,
  3839. 0, 0, 1, 0,
  3840. 0, 0, 0, 1
  3841. );
  3842. return this;
  3843. }
  3844. makeRotationAxis( axis, angle ) {
  3845. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3846. const c = Math.cos( angle );
  3847. const s = Math.sin( angle );
  3848. const t = 1 - c;
  3849. const x = axis.x, y = axis.y, z = axis.z;
  3850. const tx = t * x, ty = t * y;
  3851. this.set(
  3852. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3853. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3854. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3855. 0, 0, 0, 1
  3856. );
  3857. return this;
  3858. }
  3859. makeScale( x, y, z ) {
  3860. this.set(
  3861. x, 0, 0, 0,
  3862. 0, y, 0, 0,
  3863. 0, 0, z, 0,
  3864. 0, 0, 0, 1
  3865. );
  3866. return this;
  3867. }
  3868. makeShear( xy, xz, yx, yz, zx, zy ) {
  3869. this.set(
  3870. 1, yx, zx, 0,
  3871. xy, 1, zy, 0,
  3872. xz, yz, 1, 0,
  3873. 0, 0, 0, 1
  3874. );
  3875. return this;
  3876. }
  3877. compose( position, quaternion, scale ) {
  3878. const te = this.elements;
  3879. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3880. const x2 = x + x, y2 = y + y, z2 = z + z;
  3881. const xx = x * x2, xy = x * y2, xz = x * z2;
  3882. const yy = y * y2, yz = y * z2, zz = z * z2;
  3883. const wx = w * x2, wy = w * y2, wz = w * z2;
  3884. const sx = scale.x, sy = scale.y, sz = scale.z;
  3885. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3886. te[ 1 ] = ( xy + wz ) * sx;
  3887. te[ 2 ] = ( xz - wy ) * sx;
  3888. te[ 3 ] = 0;
  3889. te[ 4 ] = ( xy - wz ) * sy;
  3890. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3891. te[ 6 ] = ( yz + wx ) * sy;
  3892. te[ 7 ] = 0;
  3893. te[ 8 ] = ( xz + wy ) * sz;
  3894. te[ 9 ] = ( yz - wx ) * sz;
  3895. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3896. te[ 11 ] = 0;
  3897. te[ 12 ] = position.x;
  3898. te[ 13 ] = position.y;
  3899. te[ 14 ] = position.z;
  3900. te[ 15 ] = 1;
  3901. return this;
  3902. }
  3903. decompose( position, quaternion, scale ) {
  3904. const te = this.elements;
  3905. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3906. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3907. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3908. // if determine is negative, we need to invert one scale
  3909. const det = this.determinant();
  3910. if ( det < 0 ) sx = - sx;
  3911. position.x = te[ 12 ];
  3912. position.y = te[ 13 ];
  3913. position.z = te[ 14 ];
  3914. // scale the rotation part
  3915. _m1$2.copy( this );
  3916. const invSX = 1 / sx;
  3917. const invSY = 1 / sy;
  3918. const invSZ = 1 / sz;
  3919. _m1$2.elements[ 0 ] *= invSX;
  3920. _m1$2.elements[ 1 ] *= invSX;
  3921. _m1$2.elements[ 2 ] *= invSX;
  3922. _m1$2.elements[ 4 ] *= invSY;
  3923. _m1$2.elements[ 5 ] *= invSY;
  3924. _m1$2.elements[ 6 ] *= invSY;
  3925. _m1$2.elements[ 8 ] *= invSZ;
  3926. _m1$2.elements[ 9 ] *= invSZ;
  3927. _m1$2.elements[ 10 ] *= invSZ;
  3928. quaternion.setFromRotationMatrix( _m1$2 );
  3929. scale.x = sx;
  3930. scale.y = sy;
  3931. scale.z = sz;
  3932. return this;
  3933. }
  3934. makePerspective( left, right, top, bottom, near, far ) {
  3935. const te = this.elements;
  3936. const x = 2 * near / ( right - left );
  3937. const y = 2 * near / ( top - bottom );
  3938. const a = ( right + left ) / ( right - left );
  3939. const b = ( top + bottom ) / ( top - bottom );
  3940. const c = - ( far + near ) / ( far - near );
  3941. const d = - 2 * far * near / ( far - near );
  3942. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3943. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3944. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3945. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3946. return this;
  3947. }
  3948. makeOrthographic( left, right, top, bottom, near, far ) {
  3949. const te = this.elements;
  3950. const w = 1.0 / ( right - left );
  3951. const h = 1.0 / ( top - bottom );
  3952. const p = 1.0 / ( far - near );
  3953. const x = ( right + left ) * w;
  3954. const y = ( top + bottom ) * h;
  3955. const z = ( far + near ) * p;
  3956. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3957. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3958. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3959. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3960. return this;
  3961. }
  3962. equals( matrix ) {
  3963. const te = this.elements;
  3964. const me = matrix.elements;
  3965. for ( let i = 0; i < 16; i ++ ) {
  3966. if ( te[ i ] !== me[ i ] ) return false;
  3967. }
  3968. return true;
  3969. }
  3970. fromArray( array, offset = 0 ) {
  3971. for ( let i = 0; i < 16; i ++ ) {
  3972. this.elements[ i ] = array[ i + offset ];
  3973. }
  3974. return this;
  3975. }
  3976. toArray( array = [], offset = 0 ) {
  3977. const te = this.elements;
  3978. array[ offset ] = te[ 0 ];
  3979. array[ offset + 1 ] = te[ 1 ];
  3980. array[ offset + 2 ] = te[ 2 ];
  3981. array[ offset + 3 ] = te[ 3 ];
  3982. array[ offset + 4 ] = te[ 4 ];
  3983. array[ offset + 5 ] = te[ 5 ];
  3984. array[ offset + 6 ] = te[ 6 ];
  3985. array[ offset + 7 ] = te[ 7 ];
  3986. array[ offset + 8 ] = te[ 8 ];
  3987. array[ offset + 9 ] = te[ 9 ];
  3988. array[ offset + 10 ] = te[ 10 ];
  3989. array[ offset + 11 ] = te[ 11 ];
  3990. array[ offset + 12 ] = te[ 12 ];
  3991. array[ offset + 13 ] = te[ 13 ];
  3992. array[ offset + 14 ] = te[ 14 ];
  3993. array[ offset + 15 ] = te[ 15 ];
  3994. return array;
  3995. }
  3996. }
  3997. const _v1$5 = /*@__PURE__*/ new Vector3();
  3998. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3999. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4000. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4001. const _x = /*@__PURE__*/ new Vector3();
  4002. const _y = /*@__PURE__*/ new Vector3();
  4003. const _z = /*@__PURE__*/ new Vector3();
  4004. const _matrix = /*@__PURE__*/ new Matrix4();
  4005. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4006. class Euler {
  4007. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4008. this.isEuler = true;
  4009. this._x = x;
  4010. this._y = y;
  4011. this._z = z;
  4012. this._order = order;
  4013. }
  4014. get x() {
  4015. return this._x;
  4016. }
  4017. set x( value ) {
  4018. this._x = value;
  4019. this._onChangeCallback();
  4020. }
  4021. get y() {
  4022. return this._y;
  4023. }
  4024. set y( value ) {
  4025. this._y = value;
  4026. this._onChangeCallback();
  4027. }
  4028. get z() {
  4029. return this._z;
  4030. }
  4031. set z( value ) {
  4032. this._z = value;
  4033. this._onChangeCallback();
  4034. }
  4035. get order() {
  4036. return this._order;
  4037. }
  4038. set order( value ) {
  4039. this._order = value;
  4040. this._onChangeCallback();
  4041. }
  4042. set( x, y, z, order = this._order ) {
  4043. this._x = x;
  4044. this._y = y;
  4045. this._z = z;
  4046. this._order = order;
  4047. this._onChangeCallback();
  4048. return this;
  4049. }
  4050. clone() {
  4051. return new this.constructor( this._x, this._y, this._z, this._order );
  4052. }
  4053. copy( euler ) {
  4054. this._x = euler._x;
  4055. this._y = euler._y;
  4056. this._z = euler._z;
  4057. this._order = euler._order;
  4058. this._onChangeCallback();
  4059. return this;
  4060. }
  4061. setFromRotationMatrix( m, order = this._order, update = true ) {
  4062. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4063. const te = m.elements;
  4064. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4065. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4066. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4067. switch ( order ) {
  4068. case 'XYZ':
  4069. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4070. if ( Math.abs( m13 ) < 0.9999999 ) {
  4071. this._x = Math.atan2( - m23, m33 );
  4072. this._z = Math.atan2( - m12, m11 );
  4073. } else {
  4074. this._x = Math.atan2( m32, m22 );
  4075. this._z = 0;
  4076. }
  4077. break;
  4078. case 'YXZ':
  4079. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4080. if ( Math.abs( m23 ) < 0.9999999 ) {
  4081. this._y = Math.atan2( m13, m33 );
  4082. this._z = Math.atan2( m21, m22 );
  4083. } else {
  4084. this._y = Math.atan2( - m31, m11 );
  4085. this._z = 0;
  4086. }
  4087. break;
  4088. case 'ZXY':
  4089. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4090. if ( Math.abs( m32 ) < 0.9999999 ) {
  4091. this._y = Math.atan2( - m31, m33 );
  4092. this._z = Math.atan2( - m12, m22 );
  4093. } else {
  4094. this._y = 0;
  4095. this._z = Math.atan2( m21, m11 );
  4096. }
  4097. break;
  4098. case 'ZYX':
  4099. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4100. if ( Math.abs( m31 ) < 0.9999999 ) {
  4101. this._x = Math.atan2( m32, m33 );
  4102. this._z = Math.atan2( m21, m11 );
  4103. } else {
  4104. this._x = 0;
  4105. this._z = Math.atan2( - m12, m22 );
  4106. }
  4107. break;
  4108. case 'YZX':
  4109. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4110. if ( Math.abs( m21 ) < 0.9999999 ) {
  4111. this._x = Math.atan2( - m23, m22 );
  4112. this._y = Math.atan2( - m31, m11 );
  4113. } else {
  4114. this._x = 0;
  4115. this._y = Math.atan2( m13, m33 );
  4116. }
  4117. break;
  4118. case 'XZY':
  4119. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4120. if ( Math.abs( m12 ) < 0.9999999 ) {
  4121. this._x = Math.atan2( m32, m22 );
  4122. this._y = Math.atan2( m13, m11 );
  4123. } else {
  4124. this._x = Math.atan2( - m23, m33 );
  4125. this._y = 0;
  4126. }
  4127. break;
  4128. default:
  4129. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4130. }
  4131. this._order = order;
  4132. if ( update === true ) this._onChangeCallback();
  4133. return this;
  4134. }
  4135. setFromQuaternion( q, order, update ) {
  4136. _matrix.makeRotationFromQuaternion( q );
  4137. return this.setFromRotationMatrix( _matrix, order, update );
  4138. }
  4139. setFromVector3( v, order = this._order ) {
  4140. return this.set( v.x, v.y, v.z, order );
  4141. }
  4142. reorder( newOrder ) {
  4143. // WARNING: this discards revolution information -bhouston
  4144. _quaternion$3.setFromEuler( this );
  4145. return this.setFromQuaternion( _quaternion$3, newOrder );
  4146. }
  4147. equals( euler ) {
  4148. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4149. }
  4150. fromArray( array ) {
  4151. this._x = array[ 0 ];
  4152. this._y = array[ 1 ];
  4153. this._z = array[ 2 ];
  4154. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4155. this._onChangeCallback();
  4156. return this;
  4157. }
  4158. toArray( array = [], offset = 0 ) {
  4159. array[ offset ] = this._x;
  4160. array[ offset + 1 ] = this._y;
  4161. array[ offset + 2 ] = this._z;
  4162. array[ offset + 3 ] = this._order;
  4163. return array;
  4164. }
  4165. _onChange( callback ) {
  4166. this._onChangeCallback = callback;
  4167. return this;
  4168. }
  4169. _onChangeCallback() {}
  4170. *[ Symbol.iterator ]() {
  4171. yield this._x;
  4172. yield this._y;
  4173. yield this._z;
  4174. yield this._order;
  4175. }
  4176. }
  4177. Euler.DEFAULT_ORDER = 'XYZ';
  4178. class Layers {
  4179. constructor() {
  4180. this.mask = 1 | 0;
  4181. }
  4182. set( channel ) {
  4183. this.mask = ( 1 << channel | 0 ) >>> 0;
  4184. }
  4185. enable( channel ) {
  4186. this.mask |= 1 << channel | 0;
  4187. }
  4188. enableAll() {
  4189. this.mask = 0xffffffff | 0;
  4190. }
  4191. toggle( channel ) {
  4192. this.mask ^= 1 << channel | 0;
  4193. }
  4194. disable( channel ) {
  4195. this.mask &= ~ ( 1 << channel | 0 );
  4196. }
  4197. disableAll() {
  4198. this.mask = 0;
  4199. }
  4200. test( layers ) {
  4201. return ( this.mask & layers.mask ) !== 0;
  4202. }
  4203. isEnabled( channel ) {
  4204. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4205. }
  4206. }
  4207. let _object3DId = 0;
  4208. const _v1$4 = /*@__PURE__*/ new Vector3();
  4209. const _q1 = /*@__PURE__*/ new Quaternion();
  4210. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4211. const _target = /*@__PURE__*/ new Vector3();
  4212. const _position$3 = /*@__PURE__*/ new Vector3();
  4213. const _scale$2 = /*@__PURE__*/ new Vector3();
  4214. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4215. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4216. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4217. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4218. const _addedEvent = { type: 'added' };
  4219. const _removedEvent = { type: 'removed' };
  4220. class Object3D extends EventDispatcher {
  4221. constructor() {
  4222. super();
  4223. this.isObject3D = true;
  4224. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4225. this.uuid = generateUUID();
  4226. this.name = '';
  4227. this.type = 'Object3D';
  4228. this.parent = null;
  4229. this.children = [];
  4230. this.up = Object3D.DEFAULT_UP.clone();
  4231. const position = new Vector3();
  4232. const rotation = new Euler();
  4233. const quaternion = new Quaternion();
  4234. const scale = new Vector3( 1, 1, 1 );
  4235. function onRotationChange() {
  4236. quaternion.setFromEuler( rotation, false );
  4237. }
  4238. function onQuaternionChange() {
  4239. rotation.setFromQuaternion( quaternion, undefined, false );
  4240. }
  4241. rotation._onChange( onRotationChange );
  4242. quaternion._onChange( onQuaternionChange );
  4243. Object.defineProperties( this, {
  4244. position: {
  4245. configurable: true,
  4246. enumerable: true,
  4247. value: position
  4248. },
  4249. rotation: {
  4250. configurable: true,
  4251. enumerable: true,
  4252. value: rotation
  4253. },
  4254. quaternion: {
  4255. configurable: true,
  4256. enumerable: true,
  4257. value: quaternion
  4258. },
  4259. scale: {
  4260. configurable: true,
  4261. enumerable: true,
  4262. value: scale
  4263. },
  4264. modelViewMatrix: {
  4265. value: new Matrix4()
  4266. },
  4267. normalMatrix: {
  4268. value: new Matrix3()
  4269. }
  4270. } );
  4271. this.matrix = new Matrix4();
  4272. this.matrixWorld = new Matrix4();
  4273. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4274. this.matrixWorldNeedsUpdate = false;
  4275. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4276. this.layers = new Layers();
  4277. this.visible = true;
  4278. this.castShadow = false;
  4279. this.receiveShadow = false;
  4280. this.frustumCulled = true;
  4281. this.renderOrder = 0;
  4282. this.animations = [];
  4283. this.userData = {};
  4284. }
  4285. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4286. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4287. applyMatrix4( matrix ) {
  4288. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4289. this.matrix.premultiply( matrix );
  4290. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4291. }
  4292. applyQuaternion( q ) {
  4293. this.quaternion.premultiply( q );
  4294. return this;
  4295. }
  4296. setRotationFromAxisAngle( axis, angle ) {
  4297. // assumes axis is normalized
  4298. this.quaternion.setFromAxisAngle( axis, angle );
  4299. }
  4300. setRotationFromEuler( euler ) {
  4301. this.quaternion.setFromEuler( euler, true );
  4302. }
  4303. setRotationFromMatrix( m ) {
  4304. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4305. this.quaternion.setFromRotationMatrix( m );
  4306. }
  4307. setRotationFromQuaternion( q ) {
  4308. // assumes q is normalized
  4309. this.quaternion.copy( q );
  4310. }
  4311. rotateOnAxis( axis, angle ) {
  4312. // rotate object on axis in object space
  4313. // axis is assumed to be normalized
  4314. _q1.setFromAxisAngle( axis, angle );
  4315. this.quaternion.multiply( _q1 );
  4316. return this;
  4317. }
  4318. rotateOnWorldAxis( axis, angle ) {
  4319. // rotate object on axis in world space
  4320. // axis is assumed to be normalized
  4321. // method assumes no rotated parent
  4322. _q1.setFromAxisAngle( axis, angle );
  4323. this.quaternion.premultiply( _q1 );
  4324. return this;
  4325. }
  4326. rotateX( angle ) {
  4327. return this.rotateOnAxis( _xAxis, angle );
  4328. }
  4329. rotateY( angle ) {
  4330. return this.rotateOnAxis( _yAxis, angle );
  4331. }
  4332. rotateZ( angle ) {
  4333. return this.rotateOnAxis( _zAxis, angle );
  4334. }
  4335. translateOnAxis( axis, distance ) {
  4336. // translate object by distance along axis in object space
  4337. // axis is assumed to be normalized
  4338. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4339. this.position.add( _v1$4.multiplyScalar( distance ) );
  4340. return this;
  4341. }
  4342. translateX( distance ) {
  4343. return this.translateOnAxis( _xAxis, distance );
  4344. }
  4345. translateY( distance ) {
  4346. return this.translateOnAxis( _yAxis, distance );
  4347. }
  4348. translateZ( distance ) {
  4349. return this.translateOnAxis( _zAxis, distance );
  4350. }
  4351. localToWorld( vector ) {
  4352. this.updateWorldMatrix( true, false );
  4353. return vector.applyMatrix4( this.matrixWorld );
  4354. }
  4355. worldToLocal( vector ) {
  4356. this.updateWorldMatrix( true, false );
  4357. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4358. }
  4359. lookAt( x, y, z ) {
  4360. // This method does not support objects having non-uniformly-scaled parent(s)
  4361. if ( x.isVector3 ) {
  4362. _target.copy( x );
  4363. } else {
  4364. _target.set( x, y, z );
  4365. }
  4366. const parent = this.parent;
  4367. this.updateWorldMatrix( true, false );
  4368. _position$3.setFromMatrixPosition( this.matrixWorld );
  4369. if ( this.isCamera || this.isLight ) {
  4370. _m1$1.lookAt( _position$3, _target, this.up );
  4371. } else {
  4372. _m1$1.lookAt( _target, _position$3, this.up );
  4373. }
  4374. this.quaternion.setFromRotationMatrix( _m1$1 );
  4375. if ( parent ) {
  4376. _m1$1.extractRotation( parent.matrixWorld );
  4377. _q1.setFromRotationMatrix( _m1$1 );
  4378. this.quaternion.premultiply( _q1.invert() );
  4379. }
  4380. }
  4381. add( object ) {
  4382. if ( arguments.length > 1 ) {
  4383. for ( let i = 0; i < arguments.length; i ++ ) {
  4384. this.add( arguments[ i ] );
  4385. }
  4386. return this;
  4387. }
  4388. if ( object === this ) {
  4389. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4390. return this;
  4391. }
  4392. if ( object && object.isObject3D ) {
  4393. if ( object.parent !== null ) {
  4394. object.parent.remove( object );
  4395. }
  4396. object.parent = this;
  4397. this.children.push( object );
  4398. object.dispatchEvent( _addedEvent );
  4399. } else {
  4400. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4401. }
  4402. return this;
  4403. }
  4404. remove( object ) {
  4405. if ( arguments.length > 1 ) {
  4406. for ( let i = 0; i < arguments.length; i ++ ) {
  4407. this.remove( arguments[ i ] );
  4408. }
  4409. return this;
  4410. }
  4411. const index = this.children.indexOf( object );
  4412. if ( index !== - 1 ) {
  4413. object.parent = null;
  4414. this.children.splice( index, 1 );
  4415. object.dispatchEvent( _removedEvent );
  4416. }
  4417. return this;
  4418. }
  4419. removeFromParent() {
  4420. const parent = this.parent;
  4421. if ( parent !== null ) {
  4422. parent.remove( this );
  4423. }
  4424. return this;
  4425. }
  4426. clear() {
  4427. for ( let i = 0; i < this.children.length; i ++ ) {
  4428. const object = this.children[ i ];
  4429. object.parent = null;
  4430. object.dispatchEvent( _removedEvent );
  4431. }
  4432. this.children.length = 0;
  4433. return this;
  4434. }
  4435. attach( object ) {
  4436. // adds object as a child of this, while maintaining the object's world transform
  4437. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4438. this.updateWorldMatrix( true, false );
  4439. _m1$1.copy( this.matrixWorld ).invert();
  4440. if ( object.parent !== null ) {
  4441. object.parent.updateWorldMatrix( true, false );
  4442. _m1$1.multiply( object.parent.matrixWorld );
  4443. }
  4444. object.applyMatrix4( _m1$1 );
  4445. this.add( object );
  4446. object.updateWorldMatrix( false, true );
  4447. return this;
  4448. }
  4449. getObjectById( id ) {
  4450. return this.getObjectByProperty( 'id', id );
  4451. }
  4452. getObjectByName( name ) {
  4453. return this.getObjectByProperty( 'name', name );
  4454. }
  4455. getObjectByProperty( name, value ) {
  4456. if ( this[ name ] === value ) return this;
  4457. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4458. const child = this.children[ i ];
  4459. const object = child.getObjectByProperty( name, value );
  4460. if ( object !== undefined ) {
  4461. return object;
  4462. }
  4463. }
  4464. return undefined;
  4465. }
  4466. getObjectsByProperty( name, value ) {
  4467. let result = [];
  4468. if ( this[ name ] === value ) result.push( this );
  4469. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4470. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4471. if ( childResult.length > 0 ) {
  4472. result = result.concat( childResult );
  4473. }
  4474. }
  4475. return result;
  4476. }
  4477. getWorldPosition( target ) {
  4478. this.updateWorldMatrix( true, false );
  4479. return target.setFromMatrixPosition( this.matrixWorld );
  4480. }
  4481. getWorldQuaternion( target ) {
  4482. this.updateWorldMatrix( true, false );
  4483. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4484. return target;
  4485. }
  4486. getWorldScale( target ) {
  4487. this.updateWorldMatrix( true, false );
  4488. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4489. return target;
  4490. }
  4491. getWorldDirection( target ) {
  4492. this.updateWorldMatrix( true, false );
  4493. const e = this.matrixWorld.elements;
  4494. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4495. }
  4496. raycast( /* raycaster, intersects */ ) {}
  4497. traverse( callback ) {
  4498. callback( this );
  4499. const children = this.children;
  4500. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4501. children[ i ].traverse( callback );
  4502. }
  4503. }
  4504. traverseVisible( callback ) {
  4505. if ( this.visible === false ) return;
  4506. callback( this );
  4507. const children = this.children;
  4508. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4509. children[ i ].traverseVisible( callback );
  4510. }
  4511. }
  4512. traverseAncestors( callback ) {
  4513. const parent = this.parent;
  4514. if ( parent !== null ) {
  4515. callback( parent );
  4516. parent.traverseAncestors( callback );
  4517. }
  4518. }
  4519. updateMatrix() {
  4520. this.matrix.compose( this.position, this.quaternion, this.scale );
  4521. this.matrixWorldNeedsUpdate = true;
  4522. }
  4523. updateMatrixWorld( force ) {
  4524. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4525. if ( this.matrixWorldNeedsUpdate || force ) {
  4526. if ( this.parent === null ) {
  4527. this.matrixWorld.copy( this.matrix );
  4528. } else {
  4529. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4530. }
  4531. this.matrixWorldNeedsUpdate = false;
  4532. force = true;
  4533. }
  4534. // update children
  4535. const children = this.children;
  4536. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4537. const child = children[ i ];
  4538. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4539. child.updateMatrixWorld( force );
  4540. }
  4541. }
  4542. }
  4543. updateWorldMatrix( updateParents, updateChildren ) {
  4544. const parent = this.parent;
  4545. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4546. parent.updateWorldMatrix( true, false );
  4547. }
  4548. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4549. if ( this.parent === null ) {
  4550. this.matrixWorld.copy( this.matrix );
  4551. } else {
  4552. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4553. }
  4554. // update children
  4555. if ( updateChildren === true ) {
  4556. const children = this.children;
  4557. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4558. const child = children[ i ];
  4559. if ( child.matrixWorldAutoUpdate === true ) {
  4560. child.updateWorldMatrix( false, true );
  4561. }
  4562. }
  4563. }
  4564. }
  4565. toJSON( meta ) {
  4566. // meta is a string when called from JSON.stringify
  4567. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4568. const output = {};
  4569. // meta is a hash used to collect geometries, materials.
  4570. // not providing it implies that this is the root object
  4571. // being serialized.
  4572. if ( isRootObject ) {
  4573. // initialize meta obj
  4574. meta = {
  4575. geometries: {},
  4576. materials: {},
  4577. textures: {},
  4578. images: {},
  4579. shapes: {},
  4580. skeletons: {},
  4581. animations: {},
  4582. nodes: {}
  4583. };
  4584. output.metadata = {
  4585. version: 4.5,
  4586. type: 'Object',
  4587. generator: 'Object3D.toJSON'
  4588. };
  4589. }
  4590. // standard Object3D serialization
  4591. const object = {};
  4592. object.uuid = this.uuid;
  4593. object.type = this.type;
  4594. if ( this.name !== '' ) object.name = this.name;
  4595. if ( this.castShadow === true ) object.castShadow = true;
  4596. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4597. if ( this.visible === false ) object.visible = false;
  4598. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4599. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4600. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4601. object.layers = this.layers.mask;
  4602. object.matrix = this.matrix.toArray();
  4603. object.up = this.up.toArray();
  4604. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4605. // object specific properties
  4606. if ( this.isInstancedMesh ) {
  4607. object.type = 'InstancedMesh';
  4608. object.count = this.count;
  4609. object.instanceMatrix = this.instanceMatrix.toJSON();
  4610. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4611. }
  4612. //
  4613. function serialize( library, element ) {
  4614. if ( library[ element.uuid ] === undefined ) {
  4615. library[ element.uuid ] = element.toJSON( meta );
  4616. }
  4617. return element.uuid;
  4618. }
  4619. if ( this.isScene ) {
  4620. if ( this.background ) {
  4621. if ( this.background.isColor ) {
  4622. object.background = this.background.toJSON();
  4623. } else if ( this.background.isTexture ) {
  4624. object.background = this.background.toJSON( meta ).uuid;
  4625. }
  4626. }
  4627. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4628. object.environment = this.environment.toJSON( meta ).uuid;
  4629. }
  4630. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4631. object.geometry = serialize( meta.geometries, this.geometry );
  4632. const parameters = this.geometry.parameters;
  4633. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4634. const shapes = parameters.shapes;
  4635. if ( Array.isArray( shapes ) ) {
  4636. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4637. const shape = shapes[ i ];
  4638. serialize( meta.shapes, shape );
  4639. }
  4640. } else {
  4641. serialize( meta.shapes, shapes );
  4642. }
  4643. }
  4644. }
  4645. if ( this.isSkinnedMesh ) {
  4646. object.bindMode = this.bindMode;
  4647. object.bindMatrix = this.bindMatrix.toArray();
  4648. if ( this.skeleton !== undefined ) {
  4649. serialize( meta.skeletons, this.skeleton );
  4650. object.skeleton = this.skeleton.uuid;
  4651. }
  4652. }
  4653. if ( this.material !== undefined ) {
  4654. if ( Array.isArray( this.material ) ) {
  4655. const uuids = [];
  4656. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4657. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4658. }
  4659. object.material = uuids;
  4660. } else {
  4661. object.material = serialize( meta.materials, this.material );
  4662. }
  4663. }
  4664. //
  4665. if ( this.children.length > 0 ) {
  4666. object.children = [];
  4667. for ( let i = 0; i < this.children.length; i ++ ) {
  4668. object.children.push( this.children[ i ].toJSON( meta ).object );
  4669. }
  4670. }
  4671. //
  4672. if ( this.animations.length > 0 ) {
  4673. object.animations = [];
  4674. for ( let i = 0; i < this.animations.length; i ++ ) {
  4675. const animation = this.animations[ i ];
  4676. object.animations.push( serialize( meta.animations, animation ) );
  4677. }
  4678. }
  4679. if ( isRootObject ) {
  4680. const geometries = extractFromCache( meta.geometries );
  4681. const materials = extractFromCache( meta.materials );
  4682. const textures = extractFromCache( meta.textures );
  4683. const images = extractFromCache( meta.images );
  4684. const shapes = extractFromCache( meta.shapes );
  4685. const skeletons = extractFromCache( meta.skeletons );
  4686. const animations = extractFromCache( meta.animations );
  4687. const nodes = extractFromCache( meta.nodes );
  4688. if ( geometries.length > 0 ) output.geometries = geometries;
  4689. if ( materials.length > 0 ) output.materials = materials;
  4690. if ( textures.length > 0 ) output.textures = textures;
  4691. if ( images.length > 0 ) output.images = images;
  4692. if ( shapes.length > 0 ) output.shapes = shapes;
  4693. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4694. if ( animations.length > 0 ) output.animations = animations;
  4695. if ( nodes.length > 0 ) output.nodes = nodes;
  4696. }
  4697. output.object = object;
  4698. return output;
  4699. // extract data from the cache hash
  4700. // remove metadata on each item
  4701. // and return as array
  4702. function extractFromCache( cache ) {
  4703. const values = [];
  4704. for ( const key in cache ) {
  4705. const data = cache[ key ];
  4706. delete data.metadata;
  4707. values.push( data );
  4708. }
  4709. return values;
  4710. }
  4711. }
  4712. clone( recursive ) {
  4713. return new this.constructor().copy( this, recursive );
  4714. }
  4715. copy( source, recursive = true ) {
  4716. this.name = source.name;
  4717. this.up.copy( source.up );
  4718. this.position.copy( source.position );
  4719. this.rotation.order = source.rotation.order;
  4720. this.quaternion.copy( source.quaternion );
  4721. this.scale.copy( source.scale );
  4722. this.matrix.copy( source.matrix );
  4723. this.matrixWorld.copy( source.matrixWorld );
  4724. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4725. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4726. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4727. this.layers.mask = source.layers.mask;
  4728. this.visible = source.visible;
  4729. this.castShadow = source.castShadow;
  4730. this.receiveShadow = source.receiveShadow;
  4731. this.frustumCulled = source.frustumCulled;
  4732. this.renderOrder = source.renderOrder;
  4733. this.animations = source.animations;
  4734. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4735. if ( recursive === true ) {
  4736. for ( let i = 0; i < source.children.length; i ++ ) {
  4737. const child = source.children[ i ];
  4738. this.add( child.clone() );
  4739. }
  4740. }
  4741. return this;
  4742. }
  4743. }
  4744. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4745. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4746. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4747. const _v0$1 = /*@__PURE__*/ new Vector3();
  4748. const _v1$3 = /*@__PURE__*/ new Vector3();
  4749. const _v2$2 = /*@__PURE__*/ new Vector3();
  4750. const _v3$1 = /*@__PURE__*/ new Vector3();
  4751. const _vab = /*@__PURE__*/ new Vector3();
  4752. const _vac = /*@__PURE__*/ new Vector3();
  4753. const _vbc = /*@__PURE__*/ new Vector3();
  4754. const _vap = /*@__PURE__*/ new Vector3();
  4755. const _vbp = /*@__PURE__*/ new Vector3();
  4756. const _vcp = /*@__PURE__*/ new Vector3();
  4757. let warnedGetUV = false;
  4758. class Triangle {
  4759. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4760. this.a = a;
  4761. this.b = b;
  4762. this.c = c;
  4763. }
  4764. static getNormal( a, b, c, target ) {
  4765. target.subVectors( c, b );
  4766. _v0$1.subVectors( a, b );
  4767. target.cross( _v0$1 );
  4768. const targetLengthSq = target.lengthSq();
  4769. if ( targetLengthSq > 0 ) {
  4770. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4771. }
  4772. return target.set( 0, 0, 0 );
  4773. }
  4774. // static/instance method to calculate barycentric coordinates
  4775. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4776. static getBarycoord( point, a, b, c, target ) {
  4777. _v0$1.subVectors( c, a );
  4778. _v1$3.subVectors( b, a );
  4779. _v2$2.subVectors( point, a );
  4780. const dot00 = _v0$1.dot( _v0$1 );
  4781. const dot01 = _v0$1.dot( _v1$3 );
  4782. const dot02 = _v0$1.dot( _v2$2 );
  4783. const dot11 = _v1$3.dot( _v1$3 );
  4784. const dot12 = _v1$3.dot( _v2$2 );
  4785. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4786. // collinear or singular triangle
  4787. if ( denom === 0 ) {
  4788. // arbitrary location outside of triangle?
  4789. // not sure if this is the best idea, maybe should be returning undefined
  4790. return target.set( - 2, - 1, - 1 );
  4791. }
  4792. const invDenom = 1 / denom;
  4793. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4794. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4795. // barycentric coordinates must always sum to 1
  4796. return target.set( 1 - u - v, v, u );
  4797. }
  4798. static containsPoint( point, a, b, c ) {
  4799. this.getBarycoord( point, a, b, c, _v3$1 );
  4800. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4801. }
  4802. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151
  4803. if ( warnedGetUV === false ) {
  4804. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4805. warnedGetUV = true;
  4806. }
  4807. return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );
  4808. }
  4809. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4810. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4811. target.setScalar( 0 );
  4812. target.addScaledVector( v1, _v3$1.x );
  4813. target.addScaledVector( v2, _v3$1.y );
  4814. target.addScaledVector( v3, _v3$1.z );
  4815. return target;
  4816. }
  4817. static isFrontFacing( a, b, c, direction ) {
  4818. _v0$1.subVectors( c, b );
  4819. _v1$3.subVectors( a, b );
  4820. // strictly front facing
  4821. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4822. }
  4823. set( a, b, c ) {
  4824. this.a.copy( a );
  4825. this.b.copy( b );
  4826. this.c.copy( c );
  4827. return this;
  4828. }
  4829. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4830. this.a.copy( points[ i0 ] );
  4831. this.b.copy( points[ i1 ] );
  4832. this.c.copy( points[ i2 ] );
  4833. return this;
  4834. }
  4835. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4836. this.a.fromBufferAttribute( attribute, i0 );
  4837. this.b.fromBufferAttribute( attribute, i1 );
  4838. this.c.fromBufferAttribute( attribute, i2 );
  4839. return this;
  4840. }
  4841. clone() {
  4842. return new this.constructor().copy( this );
  4843. }
  4844. copy( triangle ) {
  4845. this.a.copy( triangle.a );
  4846. this.b.copy( triangle.b );
  4847. this.c.copy( triangle.c );
  4848. return this;
  4849. }
  4850. getArea() {
  4851. _v0$1.subVectors( this.c, this.b );
  4852. _v1$3.subVectors( this.a, this.b );
  4853. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4854. }
  4855. getMidpoint( target ) {
  4856. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4857. }
  4858. getNormal( target ) {
  4859. return Triangle.getNormal( this.a, this.b, this.c, target );
  4860. }
  4861. getPlane( target ) {
  4862. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4863. }
  4864. getBarycoord( point, target ) {
  4865. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4866. }
  4867. getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151
  4868. if ( warnedGetUV === false ) {
  4869. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4870. warnedGetUV = true;
  4871. }
  4872. return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4873. }
  4874. getInterpolation( point, v1, v2, v3, target ) {
  4875. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4876. }
  4877. containsPoint( point ) {
  4878. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4879. }
  4880. isFrontFacing( direction ) {
  4881. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4882. }
  4883. intersectsBox( box ) {
  4884. return box.intersectsTriangle( this );
  4885. }
  4886. closestPointToPoint( p, target ) {
  4887. const a = this.a, b = this.b, c = this.c;
  4888. let v, w;
  4889. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4890. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4891. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4892. // basically, we're distinguishing which of the voronoi regions of the triangle
  4893. // the point lies in with the minimum amount of redundant computation.
  4894. _vab.subVectors( b, a );
  4895. _vac.subVectors( c, a );
  4896. _vap.subVectors( p, a );
  4897. const d1 = _vab.dot( _vap );
  4898. const d2 = _vac.dot( _vap );
  4899. if ( d1 <= 0 && d2 <= 0 ) {
  4900. // vertex region of A; barycentric coords (1, 0, 0)
  4901. return target.copy( a );
  4902. }
  4903. _vbp.subVectors( p, b );
  4904. const d3 = _vab.dot( _vbp );
  4905. const d4 = _vac.dot( _vbp );
  4906. if ( d3 >= 0 && d4 <= d3 ) {
  4907. // vertex region of B; barycentric coords (0, 1, 0)
  4908. return target.copy( b );
  4909. }
  4910. const vc = d1 * d4 - d3 * d2;
  4911. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4912. v = d1 / ( d1 - d3 );
  4913. // edge region of AB; barycentric coords (1-v, v, 0)
  4914. return target.copy( a ).addScaledVector( _vab, v );
  4915. }
  4916. _vcp.subVectors( p, c );
  4917. const d5 = _vab.dot( _vcp );
  4918. const d6 = _vac.dot( _vcp );
  4919. if ( d6 >= 0 && d5 <= d6 ) {
  4920. // vertex region of C; barycentric coords (0, 0, 1)
  4921. return target.copy( c );
  4922. }
  4923. const vb = d5 * d2 - d1 * d6;
  4924. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4925. w = d2 / ( d2 - d6 );
  4926. // edge region of AC; barycentric coords (1-w, 0, w)
  4927. return target.copy( a ).addScaledVector( _vac, w );
  4928. }
  4929. const va = d3 * d6 - d5 * d4;
  4930. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4931. _vbc.subVectors( c, b );
  4932. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4933. // edge region of BC; barycentric coords (0, 1-w, w)
  4934. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4935. }
  4936. // face region
  4937. const denom = 1 / ( va + vb + vc );
  4938. // u = va * denom
  4939. v = vb * denom;
  4940. w = vc * denom;
  4941. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4942. }
  4943. equals( triangle ) {
  4944. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4945. }
  4946. }
  4947. let materialId = 0;
  4948. class Material extends EventDispatcher {
  4949. constructor() {
  4950. super();
  4951. this.isMaterial = true;
  4952. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4953. this.uuid = generateUUID();
  4954. this.name = '';
  4955. this.type = 'Material';
  4956. this.blending = NormalBlending;
  4957. this.side = FrontSide;
  4958. this.vertexColors = false;
  4959. this.opacity = 1;
  4960. this.transparent = false;
  4961. this.blendSrc = SrcAlphaFactor;
  4962. this.blendDst = OneMinusSrcAlphaFactor;
  4963. this.blendEquation = AddEquation;
  4964. this.blendSrcAlpha = null;
  4965. this.blendDstAlpha = null;
  4966. this.blendEquationAlpha = null;
  4967. this.depthFunc = LessEqualDepth;
  4968. this.depthTest = true;
  4969. this.depthWrite = true;
  4970. this.stencilWriteMask = 0xff;
  4971. this.stencilFunc = AlwaysStencilFunc;
  4972. this.stencilRef = 0;
  4973. this.stencilFuncMask = 0xff;
  4974. this.stencilFail = KeepStencilOp;
  4975. this.stencilZFail = KeepStencilOp;
  4976. this.stencilZPass = KeepStencilOp;
  4977. this.stencilWrite = false;
  4978. this.clippingPlanes = null;
  4979. this.clipIntersection = false;
  4980. this.clipShadows = false;
  4981. this.shadowSide = null;
  4982. this.colorWrite = true;
  4983. this.precision = null; // override the renderer's default precision for this material
  4984. this.polygonOffset = false;
  4985. this.polygonOffsetFactor = 0;
  4986. this.polygonOffsetUnits = 0;
  4987. this.dithering = false;
  4988. this.alphaToCoverage = false;
  4989. this.premultipliedAlpha = false;
  4990. this.forceSinglePass = false;
  4991. this.visible = true;
  4992. this.toneMapped = true;
  4993. this.userData = {};
  4994. this.version = 0;
  4995. this._alphaTest = 0;
  4996. }
  4997. get alphaTest() {
  4998. return this._alphaTest;
  4999. }
  5000. set alphaTest( value ) {
  5001. if ( this._alphaTest > 0 !== value > 0 ) {
  5002. this.version ++;
  5003. }
  5004. this._alphaTest = value;
  5005. }
  5006. onBuild( /* shaderobject, renderer */ ) {}
  5007. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5008. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5009. customProgramCacheKey() {
  5010. return this.onBeforeCompile.toString();
  5011. }
  5012. setValues( values ) {
  5013. if ( values === undefined ) return;
  5014. for ( const key in values ) {
  5015. const newValue = values[ key ];
  5016. if ( newValue === undefined ) {
  5017. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5018. continue;
  5019. }
  5020. const currentValue = this[ key ];
  5021. if ( currentValue === undefined ) {
  5022. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5023. continue;
  5024. }
  5025. if ( currentValue && currentValue.isColor ) {
  5026. currentValue.set( newValue );
  5027. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5028. currentValue.copy( newValue );
  5029. } else {
  5030. this[ key ] = newValue;
  5031. }
  5032. }
  5033. }
  5034. toJSON( meta ) {
  5035. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5036. if ( isRootObject ) {
  5037. meta = {
  5038. textures: {},
  5039. images: {}
  5040. };
  5041. }
  5042. const data = {
  5043. metadata: {
  5044. version: 4.5,
  5045. type: 'Material',
  5046. generator: 'Material.toJSON'
  5047. }
  5048. };
  5049. // standard Material serialization
  5050. data.uuid = this.uuid;
  5051. data.type = this.type;
  5052. if ( this.name !== '' ) data.name = this.name;
  5053. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5054. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5055. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5056. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5057. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5058. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5059. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5060. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5061. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5062. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5063. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5064. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5065. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5066. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5067. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5068. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5069. }
  5070. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5071. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5072. }
  5073. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5074. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5075. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5076. }
  5077. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5078. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5079. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5080. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5081. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5082. }
  5083. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5084. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5085. }
  5086. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5087. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5088. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5089. if ( this.lightMap && this.lightMap.isTexture ) {
  5090. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5091. data.lightMapIntensity = this.lightMapIntensity;
  5092. }
  5093. if ( this.aoMap && this.aoMap.isTexture ) {
  5094. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5095. data.aoMapIntensity = this.aoMapIntensity;
  5096. }
  5097. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5098. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5099. data.bumpScale = this.bumpScale;
  5100. }
  5101. if ( this.normalMap && this.normalMap.isTexture ) {
  5102. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5103. data.normalMapType = this.normalMapType;
  5104. data.normalScale = this.normalScale.toArray();
  5105. }
  5106. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5107. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5108. data.displacementScale = this.displacementScale;
  5109. data.displacementBias = this.displacementBias;
  5110. }
  5111. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5112. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5113. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5114. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5115. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5116. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5117. if ( this.envMap && this.envMap.isTexture ) {
  5118. data.envMap = this.envMap.toJSON( meta ).uuid;
  5119. if ( this.combine !== undefined ) data.combine = this.combine;
  5120. }
  5121. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5122. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5123. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5124. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5125. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5126. }
  5127. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5128. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5129. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5130. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5131. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5132. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5133. if ( this.size !== undefined ) data.size = this.size;
  5134. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5135. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5136. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5137. if ( this.side !== FrontSide ) data.side = this.side;
  5138. if ( this.vertexColors ) data.vertexColors = true;
  5139. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5140. if ( this.transparent === true ) data.transparent = this.transparent;
  5141. data.depthFunc = this.depthFunc;
  5142. data.depthTest = this.depthTest;
  5143. data.depthWrite = this.depthWrite;
  5144. data.colorWrite = this.colorWrite;
  5145. data.stencilWrite = this.stencilWrite;
  5146. data.stencilWriteMask = this.stencilWriteMask;
  5147. data.stencilFunc = this.stencilFunc;
  5148. data.stencilRef = this.stencilRef;
  5149. data.stencilFuncMask = this.stencilFuncMask;
  5150. data.stencilFail = this.stencilFail;
  5151. data.stencilZFail = this.stencilZFail;
  5152. data.stencilZPass = this.stencilZPass;
  5153. // rotation (SpriteMaterial)
  5154. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5155. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5156. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5157. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5158. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5159. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5160. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5161. if ( this.scale !== undefined ) data.scale = this.scale;
  5162. if ( this.dithering === true ) data.dithering = true;
  5163. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5164. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5165. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5166. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5167. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5168. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5169. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5170. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5171. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5172. if ( this.visible === false ) data.visible = false;
  5173. if ( this.toneMapped === false ) data.toneMapped = false;
  5174. if ( this.fog === false ) data.fog = false;
  5175. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5176. // TODO: Copied from Object3D.toJSON
  5177. function extractFromCache( cache ) {
  5178. const values = [];
  5179. for ( const key in cache ) {
  5180. const data = cache[ key ];
  5181. delete data.metadata;
  5182. values.push( data );
  5183. }
  5184. return values;
  5185. }
  5186. if ( isRootObject ) {
  5187. const textures = extractFromCache( meta.textures );
  5188. const images = extractFromCache( meta.images );
  5189. if ( textures.length > 0 ) data.textures = textures;
  5190. if ( images.length > 0 ) data.images = images;
  5191. }
  5192. return data;
  5193. }
  5194. clone() {
  5195. return new this.constructor().copy( this );
  5196. }
  5197. copy( source ) {
  5198. this.name = source.name;
  5199. this.blending = source.blending;
  5200. this.side = source.side;
  5201. this.vertexColors = source.vertexColors;
  5202. this.opacity = source.opacity;
  5203. this.transparent = source.transparent;
  5204. this.blendSrc = source.blendSrc;
  5205. this.blendDst = source.blendDst;
  5206. this.blendEquation = source.blendEquation;
  5207. this.blendSrcAlpha = source.blendSrcAlpha;
  5208. this.blendDstAlpha = source.blendDstAlpha;
  5209. this.blendEquationAlpha = source.blendEquationAlpha;
  5210. this.depthFunc = source.depthFunc;
  5211. this.depthTest = source.depthTest;
  5212. this.depthWrite = source.depthWrite;
  5213. this.stencilWriteMask = source.stencilWriteMask;
  5214. this.stencilFunc = source.stencilFunc;
  5215. this.stencilRef = source.stencilRef;
  5216. this.stencilFuncMask = source.stencilFuncMask;
  5217. this.stencilFail = source.stencilFail;
  5218. this.stencilZFail = source.stencilZFail;
  5219. this.stencilZPass = source.stencilZPass;
  5220. this.stencilWrite = source.stencilWrite;
  5221. const srcPlanes = source.clippingPlanes;
  5222. let dstPlanes = null;
  5223. if ( srcPlanes !== null ) {
  5224. const n = srcPlanes.length;
  5225. dstPlanes = new Array( n );
  5226. for ( let i = 0; i !== n; ++ i ) {
  5227. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5228. }
  5229. }
  5230. this.clippingPlanes = dstPlanes;
  5231. this.clipIntersection = source.clipIntersection;
  5232. this.clipShadows = source.clipShadows;
  5233. this.shadowSide = source.shadowSide;
  5234. this.colorWrite = source.colorWrite;
  5235. this.precision = source.precision;
  5236. this.polygonOffset = source.polygonOffset;
  5237. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5238. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5239. this.dithering = source.dithering;
  5240. this.alphaTest = source.alphaTest;
  5241. this.alphaToCoverage = source.alphaToCoverage;
  5242. this.premultipliedAlpha = source.premultipliedAlpha;
  5243. this.forceSinglePass = source.forceSinglePass;
  5244. this.visible = source.visible;
  5245. this.toneMapped = source.toneMapped;
  5246. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5247. return this;
  5248. }
  5249. dispose() {
  5250. this.dispatchEvent( { type: 'dispose' } );
  5251. }
  5252. set needsUpdate( value ) {
  5253. if ( value === true ) this.version ++;
  5254. }
  5255. }
  5256. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5257. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5258. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5259. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5260. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5261. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5262. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5263. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5264. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5265. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5266. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5267. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5268. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5269. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5270. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5271. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5272. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5273. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5274. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5275. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5276. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5277. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5278. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5279. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5280. const _hslA = { h: 0, s: 0, l: 0 };
  5281. const _hslB = { h: 0, s: 0, l: 0 };
  5282. function hue2rgb( p, q, t ) {
  5283. if ( t < 0 ) t += 1;
  5284. if ( t > 1 ) t -= 1;
  5285. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5286. if ( t < 1 / 2 ) return q;
  5287. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5288. return p;
  5289. }
  5290. class Color {
  5291. constructor( r, g, b ) {
  5292. this.isColor = true;
  5293. this.r = 1;
  5294. this.g = 1;
  5295. this.b = 1;
  5296. if ( g === undefined && b === undefined ) {
  5297. // r is THREE.Color, hex or string
  5298. return this.set( r );
  5299. }
  5300. return this.setRGB( r, g, b );
  5301. }
  5302. set( value ) {
  5303. if ( value && value.isColor ) {
  5304. this.copy( value );
  5305. } else if ( typeof value === 'number' ) {
  5306. this.setHex( value );
  5307. } else if ( typeof value === 'string' ) {
  5308. this.setStyle( value );
  5309. }
  5310. return this;
  5311. }
  5312. setScalar( scalar ) {
  5313. this.r = scalar;
  5314. this.g = scalar;
  5315. this.b = scalar;
  5316. return this;
  5317. }
  5318. setHex( hex, colorSpace = SRGBColorSpace ) {
  5319. hex = Math.floor( hex );
  5320. this.r = ( hex >> 16 & 255 ) / 255;
  5321. this.g = ( hex >> 8 & 255 ) / 255;
  5322. this.b = ( hex & 255 ) / 255;
  5323. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5324. return this;
  5325. }
  5326. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5327. this.r = r;
  5328. this.g = g;
  5329. this.b = b;
  5330. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5331. return this;
  5332. }
  5333. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5334. // h,s,l ranges are in 0.0 - 1.0
  5335. h = euclideanModulo( h, 1 );
  5336. s = clamp( s, 0, 1 );
  5337. l = clamp( l, 0, 1 );
  5338. if ( s === 0 ) {
  5339. this.r = this.g = this.b = l;
  5340. } else {
  5341. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5342. const q = ( 2 * l ) - p;
  5343. this.r = hue2rgb( q, p, h + 1 / 3 );
  5344. this.g = hue2rgb( q, p, h );
  5345. this.b = hue2rgb( q, p, h - 1 / 3 );
  5346. }
  5347. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5348. return this;
  5349. }
  5350. setStyle( style, colorSpace = SRGBColorSpace ) {
  5351. function handleAlpha( string ) {
  5352. if ( string === undefined ) return;
  5353. if ( parseFloat( string ) < 1 ) {
  5354. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5355. }
  5356. }
  5357. let m;
  5358. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5359. // rgb / hsl
  5360. let color;
  5361. const name = m[ 1 ];
  5362. const components = m[ 2 ];
  5363. switch ( name ) {
  5364. case 'rgb':
  5365. case 'rgba':
  5366. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5367. // rgb(255,0,0) rgba(255,0,0,0.5)
  5368. handleAlpha( color[ 4 ] );
  5369. return this.setRGB(
  5370. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5371. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5372. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5373. colorSpace
  5374. );
  5375. }
  5376. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5377. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5378. handleAlpha( color[ 4 ] );
  5379. return this.setRGB(
  5380. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5381. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5382. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5383. colorSpace
  5384. );
  5385. }
  5386. break;
  5387. case 'hsl':
  5388. case 'hsla':
  5389. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5390. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5391. handleAlpha( color[ 4 ] );
  5392. return this.setHSL(
  5393. parseFloat( color[ 1 ] ) / 360,
  5394. parseFloat( color[ 2 ] ) / 100,
  5395. parseFloat( color[ 3 ] ) / 100,
  5396. colorSpace
  5397. );
  5398. }
  5399. break;
  5400. default:
  5401. console.warn( 'THREE.Color: Unknown color model ' + style );
  5402. }
  5403. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5404. // hex color
  5405. const hex = m[ 1 ];
  5406. const size = hex.length;
  5407. if ( size === 3 ) {
  5408. // #ff0
  5409. return this.setRGB(
  5410. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5411. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5412. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5413. colorSpace
  5414. );
  5415. } else if ( size === 6 ) {
  5416. // #ff0000
  5417. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5418. } else {
  5419. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5420. }
  5421. } else if ( style && style.length > 0 ) {
  5422. return this.setColorName( style, colorSpace );
  5423. }
  5424. return this;
  5425. }
  5426. setColorName( style, colorSpace = SRGBColorSpace ) {
  5427. // color keywords
  5428. const hex = _colorKeywords[ style.toLowerCase() ];
  5429. if ( hex !== undefined ) {
  5430. // red
  5431. this.setHex( hex, colorSpace );
  5432. } else {
  5433. // unknown color
  5434. console.warn( 'THREE.Color: Unknown color ' + style );
  5435. }
  5436. return this;
  5437. }
  5438. clone() {
  5439. return new this.constructor( this.r, this.g, this.b );
  5440. }
  5441. copy( color ) {
  5442. this.r = color.r;
  5443. this.g = color.g;
  5444. this.b = color.b;
  5445. return this;
  5446. }
  5447. copySRGBToLinear( color ) {
  5448. this.r = SRGBToLinear( color.r );
  5449. this.g = SRGBToLinear( color.g );
  5450. this.b = SRGBToLinear( color.b );
  5451. return this;
  5452. }
  5453. copyLinearToSRGB( color ) {
  5454. this.r = LinearToSRGB( color.r );
  5455. this.g = LinearToSRGB( color.g );
  5456. this.b = LinearToSRGB( color.b );
  5457. return this;
  5458. }
  5459. convertSRGBToLinear() {
  5460. this.copySRGBToLinear( this );
  5461. return this;
  5462. }
  5463. convertLinearToSRGB() {
  5464. this.copyLinearToSRGB( this );
  5465. return this;
  5466. }
  5467. getHex( colorSpace = SRGBColorSpace ) {
  5468. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5469. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  5470. }
  5471. getHexString( colorSpace = SRGBColorSpace ) {
  5472. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5473. }
  5474. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5475. // h,s,l ranges are in 0.0 - 1.0
  5476. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5477. const r = _color.r, g = _color.g, b = _color.b;
  5478. const max = Math.max( r, g, b );
  5479. const min = Math.min( r, g, b );
  5480. let hue, saturation;
  5481. const lightness = ( min + max ) / 2.0;
  5482. if ( min === max ) {
  5483. hue = 0;
  5484. saturation = 0;
  5485. } else {
  5486. const delta = max - min;
  5487. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5488. switch ( max ) {
  5489. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5490. case g: hue = ( b - r ) / delta + 2; break;
  5491. case b: hue = ( r - g ) / delta + 4; break;
  5492. }
  5493. hue /= 6;
  5494. }
  5495. target.h = hue;
  5496. target.s = saturation;
  5497. target.l = lightness;
  5498. return target;
  5499. }
  5500. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5501. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5502. target.r = _color.r;
  5503. target.g = _color.g;
  5504. target.b = _color.b;
  5505. return target;
  5506. }
  5507. getStyle( colorSpace = SRGBColorSpace ) {
  5508. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5509. const r = _color.r, g = _color.g, b = _color.b;
  5510. if ( colorSpace !== SRGBColorSpace ) {
  5511. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5512. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5513. }
  5514. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5515. }
  5516. offsetHSL( h, s, l ) {
  5517. this.getHSL( _hslA );
  5518. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5519. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5520. return this;
  5521. }
  5522. add( color ) {
  5523. this.r += color.r;
  5524. this.g += color.g;
  5525. this.b += color.b;
  5526. return this;
  5527. }
  5528. addColors( color1, color2 ) {
  5529. this.r = color1.r + color2.r;
  5530. this.g = color1.g + color2.g;
  5531. this.b = color1.b + color2.b;
  5532. return this;
  5533. }
  5534. addScalar( s ) {
  5535. this.r += s;
  5536. this.g += s;
  5537. this.b += s;
  5538. return this;
  5539. }
  5540. sub( color ) {
  5541. this.r = Math.max( 0, this.r - color.r );
  5542. this.g = Math.max( 0, this.g - color.g );
  5543. this.b = Math.max( 0, this.b - color.b );
  5544. return this;
  5545. }
  5546. multiply( color ) {
  5547. this.r *= color.r;
  5548. this.g *= color.g;
  5549. this.b *= color.b;
  5550. return this;
  5551. }
  5552. multiplyScalar( s ) {
  5553. this.r *= s;
  5554. this.g *= s;
  5555. this.b *= s;
  5556. return this;
  5557. }
  5558. lerp( color, alpha ) {
  5559. this.r += ( color.r - this.r ) * alpha;
  5560. this.g += ( color.g - this.g ) * alpha;
  5561. this.b += ( color.b - this.b ) * alpha;
  5562. return this;
  5563. }
  5564. lerpColors( color1, color2, alpha ) {
  5565. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5566. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5567. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5568. return this;
  5569. }
  5570. lerpHSL( color, alpha ) {
  5571. this.getHSL( _hslA );
  5572. color.getHSL( _hslB );
  5573. const h = lerp( _hslA.h, _hslB.h, alpha );
  5574. const s = lerp( _hslA.s, _hslB.s, alpha );
  5575. const l = lerp( _hslA.l, _hslB.l, alpha );
  5576. this.setHSL( h, s, l );
  5577. return this;
  5578. }
  5579. setFromVector3( v ) {
  5580. this.r = v.x;
  5581. this.g = v.y;
  5582. this.b = v.z;
  5583. return this;
  5584. }
  5585. applyMatrix3( m ) {
  5586. const r = this.r, g = this.g, b = this.b;
  5587. const e = m.elements;
  5588. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5589. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5590. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5591. return this;
  5592. }
  5593. equals( c ) {
  5594. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5595. }
  5596. fromArray( array, offset = 0 ) {
  5597. this.r = array[ offset ];
  5598. this.g = array[ offset + 1 ];
  5599. this.b = array[ offset + 2 ];
  5600. return this;
  5601. }
  5602. toArray( array = [], offset = 0 ) {
  5603. array[ offset ] = this.r;
  5604. array[ offset + 1 ] = this.g;
  5605. array[ offset + 2 ] = this.b;
  5606. return array;
  5607. }
  5608. fromBufferAttribute( attribute, index ) {
  5609. this.r = attribute.getX( index );
  5610. this.g = attribute.getY( index );
  5611. this.b = attribute.getZ( index );
  5612. return this;
  5613. }
  5614. toJSON() {
  5615. return this.getHex();
  5616. }
  5617. *[ Symbol.iterator ]() {
  5618. yield this.r;
  5619. yield this.g;
  5620. yield this.b;
  5621. }
  5622. }
  5623. const _color = /*@__PURE__*/ new Color();
  5624. Color.NAMES = _colorKeywords;
  5625. class MeshBasicMaterial extends Material {
  5626. constructor( parameters ) {
  5627. super();
  5628. this.isMeshBasicMaterial = true;
  5629. this.type = 'MeshBasicMaterial';
  5630. this.color = new Color( 0xffffff ); // emissive
  5631. this.map = null;
  5632. this.lightMap = null;
  5633. this.lightMapIntensity = 1.0;
  5634. this.aoMap = null;
  5635. this.aoMapIntensity = 1.0;
  5636. this.specularMap = null;
  5637. this.alphaMap = null;
  5638. this.envMap = null;
  5639. this.combine = MultiplyOperation;
  5640. this.reflectivity = 1;
  5641. this.refractionRatio = 0.98;
  5642. this.wireframe = false;
  5643. this.wireframeLinewidth = 1;
  5644. this.wireframeLinecap = 'round';
  5645. this.wireframeLinejoin = 'round';
  5646. this.fog = true;
  5647. this.setValues( parameters );
  5648. }
  5649. copy( source ) {
  5650. super.copy( source );
  5651. this.color.copy( source.color );
  5652. this.map = source.map;
  5653. this.lightMap = source.lightMap;
  5654. this.lightMapIntensity = source.lightMapIntensity;
  5655. this.aoMap = source.aoMap;
  5656. this.aoMapIntensity = source.aoMapIntensity;
  5657. this.specularMap = source.specularMap;
  5658. this.alphaMap = source.alphaMap;
  5659. this.envMap = source.envMap;
  5660. this.combine = source.combine;
  5661. this.reflectivity = source.reflectivity;
  5662. this.refractionRatio = source.refractionRatio;
  5663. this.wireframe = source.wireframe;
  5664. this.wireframeLinewidth = source.wireframeLinewidth;
  5665. this.wireframeLinecap = source.wireframeLinecap;
  5666. this.wireframeLinejoin = source.wireframeLinejoin;
  5667. this.fog = source.fog;
  5668. return this;
  5669. }
  5670. }
  5671. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5672. const _tables = /*@__PURE__*/ _generateTables();
  5673. function _generateTables() {
  5674. // float32 to float16 helpers
  5675. const buffer = new ArrayBuffer( 4 );
  5676. const floatView = new Float32Array( buffer );
  5677. const uint32View = new Uint32Array( buffer );
  5678. const baseTable = new Uint32Array( 512 );
  5679. const shiftTable = new Uint32Array( 512 );
  5680. for ( let i = 0; i < 256; ++ i ) {
  5681. const e = i - 127;
  5682. // very small number (0, -0)
  5683. if ( e < - 27 ) {
  5684. baseTable[ i ] = 0x0000;
  5685. baseTable[ i | 0x100 ] = 0x8000;
  5686. shiftTable[ i ] = 24;
  5687. shiftTable[ i | 0x100 ] = 24;
  5688. // small number (denorm)
  5689. } else if ( e < - 14 ) {
  5690. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5691. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5692. shiftTable[ i ] = - e - 1;
  5693. shiftTable[ i | 0x100 ] = - e - 1;
  5694. // normal number
  5695. } else if ( e <= 15 ) {
  5696. baseTable[ i ] = ( e + 15 ) << 10;
  5697. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5698. shiftTable[ i ] = 13;
  5699. shiftTable[ i | 0x100 ] = 13;
  5700. // large number (Infinity, -Infinity)
  5701. } else if ( e < 128 ) {
  5702. baseTable[ i ] = 0x7c00;
  5703. baseTable[ i | 0x100 ] = 0xfc00;
  5704. shiftTable[ i ] = 24;
  5705. shiftTable[ i | 0x100 ] = 24;
  5706. // stay (NaN, Infinity, -Infinity)
  5707. } else {
  5708. baseTable[ i ] = 0x7c00;
  5709. baseTable[ i | 0x100 ] = 0xfc00;
  5710. shiftTable[ i ] = 13;
  5711. shiftTable[ i | 0x100 ] = 13;
  5712. }
  5713. }
  5714. // float16 to float32 helpers
  5715. const mantissaTable = new Uint32Array( 2048 );
  5716. const exponentTable = new Uint32Array( 64 );
  5717. const offsetTable = new Uint32Array( 64 );
  5718. for ( let i = 1; i < 1024; ++ i ) {
  5719. let m = i << 13; // zero pad mantissa bits
  5720. let e = 0; // zero exponent
  5721. // normalized
  5722. while ( ( m & 0x00800000 ) === 0 ) {
  5723. m <<= 1;
  5724. e -= 0x00800000; // decrement exponent
  5725. }
  5726. m &= ~ 0x00800000; // clear leading 1 bit
  5727. e += 0x38800000; // adjust bias
  5728. mantissaTable[ i ] = m | e;
  5729. }
  5730. for ( let i = 1024; i < 2048; ++ i ) {
  5731. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5732. }
  5733. for ( let i = 1; i < 31; ++ i ) {
  5734. exponentTable[ i ] = i << 23;
  5735. }
  5736. exponentTable[ 31 ] = 0x47800000;
  5737. exponentTable[ 32 ] = 0x80000000;
  5738. for ( let i = 33; i < 63; ++ i ) {
  5739. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5740. }
  5741. exponentTable[ 63 ] = 0xc7800000;
  5742. for ( let i = 1; i < 64; ++ i ) {
  5743. if ( i !== 32 ) {
  5744. offsetTable[ i ] = 1024;
  5745. }
  5746. }
  5747. return {
  5748. floatView: floatView,
  5749. uint32View: uint32View,
  5750. baseTable: baseTable,
  5751. shiftTable: shiftTable,
  5752. mantissaTable: mantissaTable,
  5753. exponentTable: exponentTable,
  5754. offsetTable: offsetTable
  5755. };
  5756. }
  5757. // float32 to float16
  5758. function toHalfFloat( val ) {
  5759. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5760. val = clamp( val, - 65504, 65504 );
  5761. _tables.floatView[ 0 ] = val;
  5762. const f = _tables.uint32View[ 0 ];
  5763. const e = ( f >> 23 ) & 0x1ff;
  5764. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5765. }
  5766. // float16 to float32
  5767. function fromHalfFloat( val ) {
  5768. const m = val >> 10;
  5769. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5770. return _tables.floatView[ 0 ];
  5771. }
  5772. const DataUtils = {
  5773. toHalfFloat: toHalfFloat,
  5774. fromHalfFloat: fromHalfFloat,
  5775. };
  5776. const _vector$8 = /*@__PURE__*/ new Vector3();
  5777. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5778. class BufferAttribute {
  5779. constructor( array, itemSize, normalized = false ) {
  5780. if ( Array.isArray( array ) ) {
  5781. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5782. }
  5783. this.isBufferAttribute = true;
  5784. this.name = '';
  5785. this.array = array;
  5786. this.itemSize = itemSize;
  5787. this.count = array !== undefined ? array.length / itemSize : 0;
  5788. this.normalized = normalized;
  5789. this.usage = StaticDrawUsage;
  5790. this.updateRange = { offset: 0, count: - 1 };
  5791. this.version = 0;
  5792. }
  5793. onUploadCallback() {}
  5794. set needsUpdate( value ) {
  5795. if ( value === true ) this.version ++;
  5796. }
  5797. setUsage( value ) {
  5798. this.usage = value;
  5799. return this;
  5800. }
  5801. copy( source ) {
  5802. this.name = source.name;
  5803. this.array = new source.array.constructor( source.array );
  5804. this.itemSize = source.itemSize;
  5805. this.count = source.count;
  5806. this.normalized = source.normalized;
  5807. this.usage = source.usage;
  5808. return this;
  5809. }
  5810. copyAt( index1, attribute, index2 ) {
  5811. index1 *= this.itemSize;
  5812. index2 *= attribute.itemSize;
  5813. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5814. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5815. }
  5816. return this;
  5817. }
  5818. copyArray( array ) {
  5819. this.array.set( array );
  5820. return this;
  5821. }
  5822. applyMatrix3( m ) {
  5823. if ( this.itemSize === 2 ) {
  5824. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5825. _vector2$1.fromBufferAttribute( this, i );
  5826. _vector2$1.applyMatrix3( m );
  5827. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5828. }
  5829. } else if ( this.itemSize === 3 ) {
  5830. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5831. _vector$8.fromBufferAttribute( this, i );
  5832. _vector$8.applyMatrix3( m );
  5833. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5834. }
  5835. }
  5836. return this;
  5837. }
  5838. applyMatrix4( m ) {
  5839. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5840. _vector$8.fromBufferAttribute( this, i );
  5841. _vector$8.applyMatrix4( m );
  5842. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5843. }
  5844. return this;
  5845. }
  5846. applyNormalMatrix( m ) {
  5847. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5848. _vector$8.fromBufferAttribute( this, i );
  5849. _vector$8.applyNormalMatrix( m );
  5850. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5851. }
  5852. return this;
  5853. }
  5854. transformDirection( m ) {
  5855. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5856. _vector$8.fromBufferAttribute( this, i );
  5857. _vector$8.transformDirection( m );
  5858. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5859. }
  5860. return this;
  5861. }
  5862. set( value, offset = 0 ) {
  5863. // Matching BufferAttribute constructor, do not normalize the array.
  5864. this.array.set( value, offset );
  5865. return this;
  5866. }
  5867. getX( index ) {
  5868. let x = this.array[ index * this.itemSize ];
  5869. if ( this.normalized ) x = denormalize( x, this.array );
  5870. return x;
  5871. }
  5872. setX( index, x ) {
  5873. if ( this.normalized ) x = normalize( x, this.array );
  5874. this.array[ index * this.itemSize ] = x;
  5875. return this;
  5876. }
  5877. getY( index ) {
  5878. let y = this.array[ index * this.itemSize + 1 ];
  5879. if ( this.normalized ) y = denormalize( y, this.array );
  5880. return y;
  5881. }
  5882. setY( index, y ) {
  5883. if ( this.normalized ) y = normalize( y, this.array );
  5884. this.array[ index * this.itemSize + 1 ] = y;
  5885. return this;
  5886. }
  5887. getZ( index ) {
  5888. let z = this.array[ index * this.itemSize + 2 ];
  5889. if ( this.normalized ) z = denormalize( z, this.array );
  5890. return z;
  5891. }
  5892. setZ( index, z ) {
  5893. if ( this.normalized ) z = normalize( z, this.array );
  5894. this.array[ index * this.itemSize + 2 ] = z;
  5895. return this;
  5896. }
  5897. getW( index ) {
  5898. let w = this.array[ index * this.itemSize + 3 ];
  5899. if ( this.normalized ) w = denormalize( w, this.array );
  5900. return w;
  5901. }
  5902. setW( index, w ) {
  5903. if ( this.normalized ) w = normalize( w, this.array );
  5904. this.array[ index * this.itemSize + 3 ] = w;
  5905. return this;
  5906. }
  5907. setXY( index, x, y ) {
  5908. index *= this.itemSize;
  5909. if ( this.normalized ) {
  5910. x = normalize( x, this.array );
  5911. y = normalize( y, this.array );
  5912. }
  5913. this.array[ index + 0 ] = x;
  5914. this.array[ index + 1 ] = y;
  5915. return this;
  5916. }
  5917. setXYZ( index, x, y, z ) {
  5918. index *= this.itemSize;
  5919. if ( this.normalized ) {
  5920. x = normalize( x, this.array );
  5921. y = normalize( y, this.array );
  5922. z = normalize( z, this.array );
  5923. }
  5924. this.array[ index + 0 ] = x;
  5925. this.array[ index + 1 ] = y;
  5926. this.array[ index + 2 ] = z;
  5927. return this;
  5928. }
  5929. setXYZW( index, x, y, z, w ) {
  5930. index *= this.itemSize;
  5931. if ( this.normalized ) {
  5932. x = normalize( x, this.array );
  5933. y = normalize( y, this.array );
  5934. z = normalize( z, this.array );
  5935. w = normalize( w, this.array );
  5936. }
  5937. this.array[ index + 0 ] = x;
  5938. this.array[ index + 1 ] = y;
  5939. this.array[ index + 2 ] = z;
  5940. this.array[ index + 3 ] = w;
  5941. return this;
  5942. }
  5943. onUpload( callback ) {
  5944. this.onUploadCallback = callback;
  5945. return this;
  5946. }
  5947. clone() {
  5948. return new this.constructor( this.array, this.itemSize ).copy( this );
  5949. }
  5950. toJSON() {
  5951. const data = {
  5952. itemSize: this.itemSize,
  5953. type: this.array.constructor.name,
  5954. array: Array.from( this.array ),
  5955. normalized: this.normalized
  5956. };
  5957. if ( this.name !== '' ) data.name = this.name;
  5958. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5959. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5960. return data;
  5961. }
  5962. copyColorsArray() { // @deprecated, r144
  5963. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5964. }
  5965. copyVector2sArray() { // @deprecated, r144
  5966. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5967. }
  5968. copyVector3sArray() { // @deprecated, r144
  5969. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5970. }
  5971. copyVector4sArray() { // @deprecated, r144
  5972. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5973. }
  5974. }
  5975. //
  5976. class Int8BufferAttribute extends BufferAttribute {
  5977. constructor( array, itemSize, normalized ) {
  5978. super( new Int8Array( array ), itemSize, normalized );
  5979. }
  5980. }
  5981. class Uint8BufferAttribute extends BufferAttribute {
  5982. constructor( array, itemSize, normalized ) {
  5983. super( new Uint8Array( array ), itemSize, normalized );
  5984. }
  5985. }
  5986. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5987. constructor( array, itemSize, normalized ) {
  5988. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5989. }
  5990. }
  5991. class Int16BufferAttribute extends BufferAttribute {
  5992. constructor( array, itemSize, normalized ) {
  5993. super( new Int16Array( array ), itemSize, normalized );
  5994. }
  5995. }
  5996. class Uint16BufferAttribute extends BufferAttribute {
  5997. constructor( array, itemSize, normalized ) {
  5998. super( new Uint16Array( array ), itemSize, normalized );
  5999. }
  6000. }
  6001. class Int32BufferAttribute extends BufferAttribute {
  6002. constructor( array, itemSize, normalized ) {
  6003. super( new Int32Array( array ), itemSize, normalized );
  6004. }
  6005. }
  6006. class Uint32BufferAttribute extends BufferAttribute {
  6007. constructor( array, itemSize, normalized ) {
  6008. super( new Uint32Array( array ), itemSize, normalized );
  6009. }
  6010. }
  6011. class Float16BufferAttribute extends BufferAttribute {
  6012. constructor( array, itemSize, normalized ) {
  6013. super( new Uint16Array( array ), itemSize, normalized );
  6014. this.isFloat16BufferAttribute = true;
  6015. }
  6016. getX( index ) {
  6017. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6018. if ( this.normalized ) x = denormalize( x, this.array );
  6019. return x;
  6020. }
  6021. setX( index, x ) {
  6022. if ( this.normalized ) x = normalize( x, this.array );
  6023. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6024. return this;
  6025. }
  6026. getY( index ) {
  6027. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6028. if ( this.normalized ) y = denormalize( y, this.array );
  6029. return y;
  6030. }
  6031. setY( index, y ) {
  6032. if ( this.normalized ) y = normalize( y, this.array );
  6033. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6034. return this;
  6035. }
  6036. getZ( index ) {
  6037. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6038. if ( this.normalized ) z = denormalize( z, this.array );
  6039. return z;
  6040. }
  6041. setZ( index, z ) {
  6042. if ( this.normalized ) z = normalize( z, this.array );
  6043. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6044. return this;
  6045. }
  6046. getW( index ) {
  6047. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6048. if ( this.normalized ) w = denormalize( w, this.array );
  6049. return w;
  6050. }
  6051. setW( index, w ) {
  6052. if ( this.normalized ) w = normalize( w, this.array );
  6053. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6054. return this;
  6055. }
  6056. setXY( index, x, y ) {
  6057. index *= this.itemSize;
  6058. if ( this.normalized ) {
  6059. x = normalize( x, this.array );
  6060. y = normalize( y, this.array );
  6061. }
  6062. this.array[ index + 0 ] = toHalfFloat( x );
  6063. this.array[ index + 1 ] = toHalfFloat( y );
  6064. return this;
  6065. }
  6066. setXYZ( index, x, y, z ) {
  6067. index *= this.itemSize;
  6068. if ( this.normalized ) {
  6069. x = normalize( x, this.array );
  6070. y = normalize( y, this.array );
  6071. z = normalize( z, this.array );
  6072. }
  6073. this.array[ index + 0 ] = toHalfFloat( x );
  6074. this.array[ index + 1 ] = toHalfFloat( y );
  6075. this.array[ index + 2 ] = toHalfFloat( z );
  6076. return this;
  6077. }
  6078. setXYZW( index, x, y, z, w ) {
  6079. index *= this.itemSize;
  6080. if ( this.normalized ) {
  6081. x = normalize( x, this.array );
  6082. y = normalize( y, this.array );
  6083. z = normalize( z, this.array );
  6084. w = normalize( w, this.array );
  6085. }
  6086. this.array[ index + 0 ] = toHalfFloat( x );
  6087. this.array[ index + 1 ] = toHalfFloat( y );
  6088. this.array[ index + 2 ] = toHalfFloat( z );
  6089. this.array[ index + 3 ] = toHalfFloat( w );
  6090. return this;
  6091. }
  6092. }
  6093. class Float32BufferAttribute extends BufferAttribute {
  6094. constructor( array, itemSize, normalized ) {
  6095. super( new Float32Array( array ), itemSize, normalized );
  6096. }
  6097. }
  6098. class Float64BufferAttribute extends BufferAttribute {
  6099. constructor( array, itemSize, normalized ) {
  6100. super( new Float64Array( array ), itemSize, normalized );
  6101. }
  6102. }
  6103. let _id$1 = 0;
  6104. const _m1 = /*@__PURE__*/ new Matrix4();
  6105. const _obj = /*@__PURE__*/ new Object3D();
  6106. const _offset = /*@__PURE__*/ new Vector3();
  6107. const _box$1 = /*@__PURE__*/ new Box3();
  6108. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6109. const _vector$7 = /*@__PURE__*/ new Vector3();
  6110. class BufferGeometry extends EventDispatcher {
  6111. constructor() {
  6112. super();
  6113. this.isBufferGeometry = true;
  6114. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  6115. this.uuid = generateUUID();
  6116. this.name = '';
  6117. this.type = 'BufferGeometry';
  6118. this.index = null;
  6119. this.attributes = {};
  6120. this.morphAttributes = {};
  6121. this.morphTargetsRelative = false;
  6122. this.groups = [];
  6123. this.boundingBox = null;
  6124. this.boundingSphere = null;
  6125. this.drawRange = { start: 0, count: Infinity };
  6126. this.userData = {};
  6127. }
  6128. getIndex() {
  6129. return this.index;
  6130. }
  6131. setIndex( index ) {
  6132. if ( Array.isArray( index ) ) {
  6133. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6134. } else {
  6135. this.index = index;
  6136. }
  6137. return this;
  6138. }
  6139. getAttribute( name ) {
  6140. return this.attributes[ name ];
  6141. }
  6142. setAttribute( name, attribute ) {
  6143. this.attributes[ name ] = attribute;
  6144. return this;
  6145. }
  6146. deleteAttribute( name ) {
  6147. delete this.attributes[ name ];
  6148. return this;
  6149. }
  6150. hasAttribute( name ) {
  6151. return this.attributes[ name ] !== undefined;
  6152. }
  6153. addGroup( start, count, materialIndex = 0 ) {
  6154. this.groups.push( {
  6155. start: start,
  6156. count: count,
  6157. materialIndex: materialIndex
  6158. } );
  6159. }
  6160. clearGroups() {
  6161. this.groups = [];
  6162. }
  6163. setDrawRange( start, count ) {
  6164. this.drawRange.start = start;
  6165. this.drawRange.count = count;
  6166. }
  6167. applyMatrix4( matrix ) {
  6168. const position = this.attributes.position;
  6169. if ( position !== undefined ) {
  6170. position.applyMatrix4( matrix );
  6171. position.needsUpdate = true;
  6172. }
  6173. const normal = this.attributes.normal;
  6174. if ( normal !== undefined ) {
  6175. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6176. normal.applyNormalMatrix( normalMatrix );
  6177. normal.needsUpdate = true;
  6178. }
  6179. const tangent = this.attributes.tangent;
  6180. if ( tangent !== undefined ) {
  6181. tangent.transformDirection( matrix );
  6182. tangent.needsUpdate = true;
  6183. }
  6184. if ( this.boundingBox !== null ) {
  6185. this.computeBoundingBox();
  6186. }
  6187. if ( this.boundingSphere !== null ) {
  6188. this.computeBoundingSphere();
  6189. }
  6190. return this;
  6191. }
  6192. applyQuaternion( q ) {
  6193. _m1.makeRotationFromQuaternion( q );
  6194. this.applyMatrix4( _m1 );
  6195. return this;
  6196. }
  6197. rotateX( angle ) {
  6198. // rotate geometry around world x-axis
  6199. _m1.makeRotationX( angle );
  6200. this.applyMatrix4( _m1 );
  6201. return this;
  6202. }
  6203. rotateY( angle ) {
  6204. // rotate geometry around world y-axis
  6205. _m1.makeRotationY( angle );
  6206. this.applyMatrix4( _m1 );
  6207. return this;
  6208. }
  6209. rotateZ( angle ) {
  6210. // rotate geometry around world z-axis
  6211. _m1.makeRotationZ( angle );
  6212. this.applyMatrix4( _m1 );
  6213. return this;
  6214. }
  6215. translate( x, y, z ) {
  6216. // translate geometry
  6217. _m1.makeTranslation( x, y, z );
  6218. this.applyMatrix4( _m1 );
  6219. return this;
  6220. }
  6221. scale( x, y, z ) {
  6222. // scale geometry
  6223. _m1.makeScale( x, y, z );
  6224. this.applyMatrix4( _m1 );
  6225. return this;
  6226. }
  6227. lookAt( vector ) {
  6228. _obj.lookAt( vector );
  6229. _obj.updateMatrix();
  6230. this.applyMatrix4( _obj.matrix );
  6231. return this;
  6232. }
  6233. center() {
  6234. this.computeBoundingBox();
  6235. this.boundingBox.getCenter( _offset ).negate();
  6236. this.translate( _offset.x, _offset.y, _offset.z );
  6237. return this;
  6238. }
  6239. setFromPoints( points ) {
  6240. const position = [];
  6241. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6242. const point = points[ i ];
  6243. position.push( point.x, point.y, point.z || 0 );
  6244. }
  6245. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6246. return this;
  6247. }
  6248. computeBoundingBox() {
  6249. if ( this.boundingBox === null ) {
  6250. this.boundingBox = new Box3();
  6251. }
  6252. const position = this.attributes.position;
  6253. const morphAttributesPosition = this.morphAttributes.position;
  6254. if ( position && position.isGLBufferAttribute ) {
  6255. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6256. this.boundingBox.set(
  6257. new Vector3( - Infinity, - Infinity, - Infinity ),
  6258. new Vector3( + Infinity, + Infinity, + Infinity )
  6259. );
  6260. return;
  6261. }
  6262. if ( position !== undefined ) {
  6263. this.boundingBox.setFromBufferAttribute( position );
  6264. // process morph attributes if present
  6265. if ( morphAttributesPosition ) {
  6266. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6267. const morphAttribute = morphAttributesPosition[ i ];
  6268. _box$1.setFromBufferAttribute( morphAttribute );
  6269. if ( this.morphTargetsRelative ) {
  6270. _vector$7.addVectors( this.boundingBox.min, _box$1.min );
  6271. this.boundingBox.expandByPoint( _vector$7 );
  6272. _vector$7.addVectors( this.boundingBox.max, _box$1.max );
  6273. this.boundingBox.expandByPoint( _vector$7 );
  6274. } else {
  6275. this.boundingBox.expandByPoint( _box$1.min );
  6276. this.boundingBox.expandByPoint( _box$1.max );
  6277. }
  6278. }
  6279. }
  6280. } else {
  6281. this.boundingBox.makeEmpty();
  6282. }
  6283. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6284. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6285. }
  6286. }
  6287. computeBoundingSphere() {
  6288. if ( this.boundingSphere === null ) {
  6289. this.boundingSphere = new Sphere();
  6290. }
  6291. const position = this.attributes.position;
  6292. const morphAttributesPosition = this.morphAttributes.position;
  6293. if ( position && position.isGLBufferAttribute ) {
  6294. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6295. this.boundingSphere.set( new Vector3(), Infinity );
  6296. return;
  6297. }
  6298. if ( position ) {
  6299. // first, find the center of the bounding sphere
  6300. const center = this.boundingSphere.center;
  6301. _box$1.setFromBufferAttribute( position );
  6302. // process morph attributes if present
  6303. if ( morphAttributesPosition ) {
  6304. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6305. const morphAttribute = morphAttributesPosition[ i ];
  6306. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6307. if ( this.morphTargetsRelative ) {
  6308. _vector$7.addVectors( _box$1.min, _boxMorphTargets.min );
  6309. _box$1.expandByPoint( _vector$7 );
  6310. _vector$7.addVectors( _box$1.max, _boxMorphTargets.max );
  6311. _box$1.expandByPoint( _vector$7 );
  6312. } else {
  6313. _box$1.expandByPoint( _boxMorphTargets.min );
  6314. _box$1.expandByPoint( _boxMorphTargets.max );
  6315. }
  6316. }
  6317. }
  6318. _box$1.getCenter( center );
  6319. // second, try to find a boundingSphere with a radius smaller than the
  6320. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6321. let maxRadiusSq = 0;
  6322. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6323. _vector$7.fromBufferAttribute( position, i );
  6324. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6325. }
  6326. // process morph attributes if present
  6327. if ( morphAttributesPosition ) {
  6328. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6329. const morphAttribute = morphAttributesPosition[ i ];
  6330. const morphTargetsRelative = this.morphTargetsRelative;
  6331. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6332. _vector$7.fromBufferAttribute( morphAttribute, j );
  6333. if ( morphTargetsRelative ) {
  6334. _offset.fromBufferAttribute( position, j );
  6335. _vector$7.add( _offset );
  6336. }
  6337. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6338. }
  6339. }
  6340. }
  6341. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6342. if ( isNaN( this.boundingSphere.radius ) ) {
  6343. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6344. }
  6345. }
  6346. }
  6347. computeTangents() {
  6348. const index = this.index;
  6349. const attributes = this.attributes;
  6350. // based on http://www.terathon.com/code/tangent.html
  6351. // (per vertex tangents)
  6352. if ( index === null ||
  6353. attributes.position === undefined ||
  6354. attributes.normal === undefined ||
  6355. attributes.uv === undefined ) {
  6356. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6357. return;
  6358. }
  6359. const indices = index.array;
  6360. const positions = attributes.position.array;
  6361. const normals = attributes.normal.array;
  6362. const uvs = attributes.uv.array;
  6363. const nVertices = positions.length / 3;
  6364. if ( this.hasAttribute( 'tangent' ) === false ) {
  6365. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6366. }
  6367. const tangents = this.getAttribute( 'tangent' ).array;
  6368. const tan1 = [], tan2 = [];
  6369. for ( let i = 0; i < nVertices; i ++ ) {
  6370. tan1[ i ] = new Vector3();
  6371. tan2[ i ] = new Vector3();
  6372. }
  6373. const vA = new Vector3(),
  6374. vB = new Vector3(),
  6375. vC = new Vector3(),
  6376. uvA = new Vector2(),
  6377. uvB = new Vector2(),
  6378. uvC = new Vector2(),
  6379. sdir = new Vector3(),
  6380. tdir = new Vector3();
  6381. function handleTriangle( a, b, c ) {
  6382. vA.fromArray( positions, a * 3 );
  6383. vB.fromArray( positions, b * 3 );
  6384. vC.fromArray( positions, c * 3 );
  6385. uvA.fromArray( uvs, a * 2 );
  6386. uvB.fromArray( uvs, b * 2 );
  6387. uvC.fromArray( uvs, c * 2 );
  6388. vB.sub( vA );
  6389. vC.sub( vA );
  6390. uvB.sub( uvA );
  6391. uvC.sub( uvA );
  6392. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6393. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6394. if ( ! isFinite( r ) ) return;
  6395. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6396. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6397. tan1[ a ].add( sdir );
  6398. tan1[ b ].add( sdir );
  6399. tan1[ c ].add( sdir );
  6400. tan2[ a ].add( tdir );
  6401. tan2[ b ].add( tdir );
  6402. tan2[ c ].add( tdir );
  6403. }
  6404. let groups = this.groups;
  6405. if ( groups.length === 0 ) {
  6406. groups = [ {
  6407. start: 0,
  6408. count: indices.length
  6409. } ];
  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. handleTriangle(
  6417. indices[ j + 0 ],
  6418. indices[ j + 1 ],
  6419. indices[ j + 2 ]
  6420. );
  6421. }
  6422. }
  6423. const tmp = new Vector3(), tmp2 = new Vector3();
  6424. const n = new Vector3(), n2 = new Vector3();
  6425. function handleVertex( v ) {
  6426. n.fromArray( normals, v * 3 );
  6427. n2.copy( n );
  6428. const t = tan1[ v ];
  6429. // Gram-Schmidt orthogonalize
  6430. tmp.copy( t );
  6431. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6432. // Calculate handedness
  6433. tmp2.crossVectors( n2, t );
  6434. const test = tmp2.dot( tan2[ v ] );
  6435. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6436. tangents[ v * 4 ] = tmp.x;
  6437. tangents[ v * 4 + 1 ] = tmp.y;
  6438. tangents[ v * 4 + 2 ] = tmp.z;
  6439. tangents[ v * 4 + 3 ] = w;
  6440. }
  6441. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6442. const group = groups[ i ];
  6443. const start = group.start;
  6444. const count = group.count;
  6445. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6446. handleVertex( indices[ j + 0 ] );
  6447. handleVertex( indices[ j + 1 ] );
  6448. handleVertex( indices[ j + 2 ] );
  6449. }
  6450. }
  6451. }
  6452. computeVertexNormals() {
  6453. const index = this.index;
  6454. const positionAttribute = this.getAttribute( 'position' );
  6455. if ( positionAttribute !== undefined ) {
  6456. let normalAttribute = this.getAttribute( 'normal' );
  6457. if ( normalAttribute === undefined ) {
  6458. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6459. this.setAttribute( 'normal', normalAttribute );
  6460. } else {
  6461. // reset existing normals to zero
  6462. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6463. normalAttribute.setXYZ( i, 0, 0, 0 );
  6464. }
  6465. }
  6466. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6467. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6468. const cb = new Vector3(), ab = new Vector3();
  6469. // indexed elements
  6470. if ( index ) {
  6471. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6472. const vA = index.getX( i + 0 );
  6473. const vB = index.getX( i + 1 );
  6474. const vC = index.getX( i + 2 );
  6475. pA.fromBufferAttribute( positionAttribute, vA );
  6476. pB.fromBufferAttribute( positionAttribute, vB );
  6477. pC.fromBufferAttribute( positionAttribute, vC );
  6478. cb.subVectors( pC, pB );
  6479. ab.subVectors( pA, pB );
  6480. cb.cross( ab );
  6481. nA.fromBufferAttribute( normalAttribute, vA );
  6482. nB.fromBufferAttribute( normalAttribute, vB );
  6483. nC.fromBufferAttribute( normalAttribute, vC );
  6484. nA.add( cb );
  6485. nB.add( cb );
  6486. nC.add( cb );
  6487. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6488. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6489. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6490. }
  6491. } else {
  6492. // non-indexed elements (unconnected triangle soup)
  6493. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6494. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6495. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6496. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6497. cb.subVectors( pC, pB );
  6498. ab.subVectors( pA, pB );
  6499. cb.cross( ab );
  6500. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6501. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6502. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6503. }
  6504. }
  6505. this.normalizeNormals();
  6506. normalAttribute.needsUpdate = true;
  6507. }
  6508. }
  6509. merge() { // @deprecated, r144
  6510. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeGeometries() instead.' );
  6511. return this;
  6512. }
  6513. normalizeNormals() {
  6514. const normals = this.attributes.normal;
  6515. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6516. _vector$7.fromBufferAttribute( normals, i );
  6517. _vector$7.normalize();
  6518. normals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  6519. }
  6520. }
  6521. toNonIndexed() {
  6522. function convertBufferAttribute( attribute, indices ) {
  6523. const array = attribute.array;
  6524. const itemSize = attribute.itemSize;
  6525. const normalized = attribute.normalized;
  6526. const array2 = new array.constructor( indices.length * itemSize );
  6527. let index = 0, index2 = 0;
  6528. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6529. if ( attribute.isInterleavedBufferAttribute ) {
  6530. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6531. } else {
  6532. index = indices[ i ] * itemSize;
  6533. }
  6534. for ( let j = 0; j < itemSize; j ++ ) {
  6535. array2[ index2 ++ ] = array[ index ++ ];
  6536. }
  6537. }
  6538. return new BufferAttribute( array2, itemSize, normalized );
  6539. }
  6540. //
  6541. if ( this.index === null ) {
  6542. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6543. return this;
  6544. }
  6545. const geometry2 = new BufferGeometry();
  6546. const indices = this.index.array;
  6547. const attributes = this.attributes;
  6548. // attributes
  6549. for ( const name in attributes ) {
  6550. const attribute = attributes[ name ];
  6551. const newAttribute = convertBufferAttribute( attribute, indices );
  6552. geometry2.setAttribute( name, newAttribute );
  6553. }
  6554. // morph attributes
  6555. const morphAttributes = this.morphAttributes;
  6556. for ( const name in morphAttributes ) {
  6557. const morphArray = [];
  6558. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6559. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6560. const attribute = morphAttribute[ i ];
  6561. const newAttribute = convertBufferAttribute( attribute, indices );
  6562. morphArray.push( newAttribute );
  6563. }
  6564. geometry2.morphAttributes[ name ] = morphArray;
  6565. }
  6566. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6567. // groups
  6568. const groups = this.groups;
  6569. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6570. const group = groups[ i ];
  6571. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6572. }
  6573. return geometry2;
  6574. }
  6575. toJSON() {
  6576. const data = {
  6577. metadata: {
  6578. version: 4.5,
  6579. type: 'BufferGeometry',
  6580. generator: 'BufferGeometry.toJSON'
  6581. }
  6582. };
  6583. // standard BufferGeometry serialization
  6584. data.uuid = this.uuid;
  6585. data.type = this.type;
  6586. if ( this.name !== '' ) data.name = this.name;
  6587. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6588. if ( this.parameters !== undefined ) {
  6589. const parameters = this.parameters;
  6590. for ( const key in parameters ) {
  6591. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6592. }
  6593. return data;
  6594. }
  6595. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6596. data.data = { attributes: {} };
  6597. const index = this.index;
  6598. if ( index !== null ) {
  6599. data.data.index = {
  6600. type: index.array.constructor.name,
  6601. array: Array.prototype.slice.call( index.array )
  6602. };
  6603. }
  6604. const attributes = this.attributes;
  6605. for ( const key in attributes ) {
  6606. const attribute = attributes[ key ];
  6607. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6608. }
  6609. const morphAttributes = {};
  6610. let hasMorphAttributes = false;
  6611. for ( const key in this.morphAttributes ) {
  6612. const attributeArray = this.morphAttributes[ key ];
  6613. const array = [];
  6614. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6615. const attribute = attributeArray[ i ];
  6616. array.push( attribute.toJSON( data.data ) );
  6617. }
  6618. if ( array.length > 0 ) {
  6619. morphAttributes[ key ] = array;
  6620. hasMorphAttributes = true;
  6621. }
  6622. }
  6623. if ( hasMorphAttributes ) {
  6624. data.data.morphAttributes = morphAttributes;
  6625. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6626. }
  6627. const groups = this.groups;
  6628. if ( groups.length > 0 ) {
  6629. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6630. }
  6631. const boundingSphere = this.boundingSphere;
  6632. if ( boundingSphere !== null ) {
  6633. data.data.boundingSphere = {
  6634. center: boundingSphere.center.toArray(),
  6635. radius: boundingSphere.radius
  6636. };
  6637. }
  6638. return data;
  6639. }
  6640. clone() {
  6641. return new this.constructor().copy( this );
  6642. }
  6643. copy( source ) {
  6644. // reset
  6645. this.index = null;
  6646. this.attributes = {};
  6647. this.morphAttributes = {};
  6648. this.groups = [];
  6649. this.boundingBox = null;
  6650. this.boundingSphere = null;
  6651. // used for storing cloned, shared data
  6652. const data = {};
  6653. // name
  6654. this.name = source.name;
  6655. // index
  6656. const index = source.index;
  6657. if ( index !== null ) {
  6658. this.setIndex( index.clone( data ) );
  6659. }
  6660. // attributes
  6661. const attributes = source.attributes;
  6662. for ( const name in attributes ) {
  6663. const attribute = attributes[ name ];
  6664. this.setAttribute( name, attribute.clone( data ) );
  6665. }
  6666. // morph attributes
  6667. const morphAttributes = source.morphAttributes;
  6668. for ( const name in morphAttributes ) {
  6669. const array = [];
  6670. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6671. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6672. array.push( morphAttribute[ i ].clone( data ) );
  6673. }
  6674. this.morphAttributes[ name ] = array;
  6675. }
  6676. this.morphTargetsRelative = source.morphTargetsRelative;
  6677. // groups
  6678. const groups = source.groups;
  6679. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6680. const group = groups[ i ];
  6681. this.addGroup( group.start, group.count, group.materialIndex );
  6682. }
  6683. // bounding box
  6684. const boundingBox = source.boundingBox;
  6685. if ( boundingBox !== null ) {
  6686. this.boundingBox = boundingBox.clone();
  6687. }
  6688. // bounding sphere
  6689. const boundingSphere = source.boundingSphere;
  6690. if ( boundingSphere !== null ) {
  6691. this.boundingSphere = boundingSphere.clone();
  6692. }
  6693. // draw range
  6694. this.drawRange.start = source.drawRange.start;
  6695. this.drawRange.count = source.drawRange.count;
  6696. // user data
  6697. this.userData = source.userData;
  6698. return this;
  6699. }
  6700. dispose() {
  6701. this.dispatchEvent( { type: 'dispose' } );
  6702. }
  6703. }
  6704. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6705. const _ray$2 = /*@__PURE__*/ new Ray();
  6706. const _sphere$4 = /*@__PURE__*/ new Sphere();
  6707. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6708. const _vA$1 = /*@__PURE__*/ new Vector3();
  6709. const _vB$1 = /*@__PURE__*/ new Vector3();
  6710. const _vC$1 = /*@__PURE__*/ new Vector3();
  6711. const _tempA = /*@__PURE__*/ new Vector3();
  6712. const _morphA = /*@__PURE__*/ new Vector3();
  6713. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6714. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6715. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6716. const _normalA = /*@__PURE__*/ new Vector3();
  6717. const _normalB = /*@__PURE__*/ new Vector3();
  6718. const _normalC = /*@__PURE__*/ new Vector3();
  6719. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6720. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6721. class Mesh extends Object3D {
  6722. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6723. super();
  6724. this.isMesh = true;
  6725. this.type = 'Mesh';
  6726. this.geometry = geometry;
  6727. this.material = material;
  6728. this.updateMorphTargets();
  6729. }
  6730. copy( source, recursive ) {
  6731. super.copy( source, recursive );
  6732. if ( source.morphTargetInfluences !== undefined ) {
  6733. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6734. }
  6735. if ( source.morphTargetDictionary !== undefined ) {
  6736. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6737. }
  6738. this.material = source.material;
  6739. this.geometry = source.geometry;
  6740. return this;
  6741. }
  6742. updateMorphTargets() {
  6743. const geometry = this.geometry;
  6744. const morphAttributes = geometry.morphAttributes;
  6745. const keys = Object.keys( morphAttributes );
  6746. if ( keys.length > 0 ) {
  6747. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6748. if ( morphAttribute !== undefined ) {
  6749. this.morphTargetInfluences = [];
  6750. this.morphTargetDictionary = {};
  6751. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6752. const name = morphAttribute[ m ].name || String( m );
  6753. this.morphTargetInfluences.push( 0 );
  6754. this.morphTargetDictionary[ name ] = m;
  6755. }
  6756. }
  6757. }
  6758. }
  6759. getVertexPosition( index, target ) {
  6760. const geometry = this.geometry;
  6761. const position = geometry.attributes.position;
  6762. const morphPosition = geometry.morphAttributes.position;
  6763. const morphTargetsRelative = geometry.morphTargetsRelative;
  6764. target.fromBufferAttribute( position, index );
  6765. const morphInfluences = this.morphTargetInfluences;
  6766. if ( morphPosition && morphInfluences ) {
  6767. _morphA.set( 0, 0, 0 );
  6768. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6769. const influence = morphInfluences[ i ];
  6770. const morphAttribute = morphPosition[ i ];
  6771. if ( influence === 0 ) continue;
  6772. _tempA.fromBufferAttribute( morphAttribute, index );
  6773. if ( morphTargetsRelative ) {
  6774. _morphA.addScaledVector( _tempA, influence );
  6775. } else {
  6776. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6777. }
  6778. }
  6779. target.add( _morphA );
  6780. }
  6781. return target;
  6782. }
  6783. raycast( raycaster, intersects ) {
  6784. const geometry = this.geometry;
  6785. const material = this.material;
  6786. const matrixWorld = this.matrixWorld;
  6787. if ( material === undefined ) return;
  6788. // Checking boundingSphere distance to ray
  6789. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6790. _sphere$4.copy( geometry.boundingSphere );
  6791. _sphere$4.applyMatrix4( matrixWorld );
  6792. _ray$2.copy( raycaster.ray ).recast( raycaster.near );
  6793. if ( _sphere$4.containsPoint( _ray$2.origin ) === false ) {
  6794. if ( _ray$2.intersectSphere( _sphere$4, _sphereHitAt ) === null ) return;
  6795. if ( _ray$2.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6796. }
  6797. //
  6798. _inverseMatrix$2.copy( matrixWorld ).invert();
  6799. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6800. // Check boundingBox before continuing
  6801. if ( geometry.boundingBox !== null ) {
  6802. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6803. }
  6804. this._computeIntersections( raycaster, intersects );
  6805. }
  6806. _computeIntersections( raycaster, intersects ) {
  6807. let intersection;
  6808. const geometry = this.geometry;
  6809. const material = this.material;
  6810. const index = geometry.index;
  6811. const position = geometry.attributes.position;
  6812. const uv = geometry.attributes.uv;
  6813. const uv1 = geometry.attributes.uv1;
  6814. const normal = geometry.attributes.normal;
  6815. const groups = geometry.groups;
  6816. const drawRange = geometry.drawRange;
  6817. if ( index !== null ) {
  6818. // indexed buffer geometry
  6819. if ( Array.isArray( material ) ) {
  6820. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6821. const group = groups[ i ];
  6822. const groupMaterial = material[ group.materialIndex ];
  6823. const start = Math.max( group.start, drawRange.start );
  6824. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6825. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6826. const a = index.getX( j );
  6827. const b = index.getX( j + 1 );
  6828. const c = index.getX( j + 2 );
  6829. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv1, normal, a, b, c );
  6830. if ( intersection ) {
  6831. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6832. intersection.face.materialIndex = group.materialIndex;
  6833. intersects.push( intersection );
  6834. }
  6835. }
  6836. }
  6837. } else {
  6838. const start = Math.max( 0, drawRange.start );
  6839. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6840. for ( let i = start, il = end; i < il; i += 3 ) {
  6841. const a = index.getX( i );
  6842. const b = index.getX( i + 1 );
  6843. const c = index.getX( i + 2 );
  6844. intersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv1, normal, a, b, c );
  6845. if ( intersection ) {
  6846. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6847. intersects.push( intersection );
  6848. }
  6849. }
  6850. }
  6851. } else if ( position !== undefined ) {
  6852. // non-indexed buffer geometry
  6853. if ( Array.isArray( material ) ) {
  6854. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6855. const group = groups[ i ];
  6856. const groupMaterial = material[ group.materialIndex ];
  6857. const start = Math.max( group.start, drawRange.start );
  6858. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6859. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6860. const a = j;
  6861. const b = j + 1;
  6862. const c = j + 2;
  6863. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv1, normal, a, b, c );
  6864. if ( intersection ) {
  6865. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6866. intersection.face.materialIndex = group.materialIndex;
  6867. intersects.push( intersection );
  6868. }
  6869. }
  6870. }
  6871. } else {
  6872. const start = Math.max( 0, drawRange.start );
  6873. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6874. for ( let i = start, il = end; i < il; i += 3 ) {
  6875. const a = i;
  6876. const b = i + 1;
  6877. const c = i + 2;
  6878. intersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv1, normal, a, b, c );
  6879. if ( intersection ) {
  6880. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6881. intersects.push( intersection );
  6882. }
  6883. }
  6884. }
  6885. }
  6886. }
  6887. }
  6888. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6889. let intersect;
  6890. if ( material.side === BackSide ) {
  6891. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6892. } else {
  6893. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6894. }
  6895. if ( intersect === null ) return null;
  6896. _intersectionPointWorld.copy( point );
  6897. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6898. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6899. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6900. return {
  6901. distance: distance,
  6902. point: _intersectionPointWorld.clone(),
  6903. object: object
  6904. };
  6905. }
  6906. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  6907. object.getVertexPosition( a, _vA$1 );
  6908. object.getVertexPosition( b, _vB$1 );
  6909. object.getVertexPosition( c, _vC$1 );
  6910. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6911. if ( intersection ) {
  6912. if ( uv ) {
  6913. _uvA$1.fromBufferAttribute( uv, a );
  6914. _uvB$1.fromBufferAttribute( uv, b );
  6915. _uvC$1.fromBufferAttribute( uv, c );
  6916. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6917. }
  6918. if ( uv1 ) {
  6919. _uvA$1.fromBufferAttribute( uv1, a );
  6920. _uvB$1.fromBufferAttribute( uv1, b );
  6921. _uvC$1.fromBufferAttribute( uv1, c );
  6922. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6923. intersection.uv2 = intersection.uv1; // Backwards compatibility
  6924. }
  6925. if ( normal ) {
  6926. _normalA.fromBufferAttribute( normal, a );
  6927. _normalB.fromBufferAttribute( normal, b );
  6928. _normalC.fromBufferAttribute( normal, c );
  6929. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  6930. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  6931. intersection.normal.multiplyScalar( - 1 );
  6932. }
  6933. }
  6934. const face = {
  6935. a: a,
  6936. b: b,
  6937. c: c,
  6938. normal: new Vector3(),
  6939. materialIndex: 0
  6940. };
  6941. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6942. intersection.face = face;
  6943. }
  6944. return intersection;
  6945. }
  6946. class BoxGeometry extends BufferGeometry {
  6947. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6948. super();
  6949. this.type = 'BoxGeometry';
  6950. this.parameters = {
  6951. width: width,
  6952. height: height,
  6953. depth: depth,
  6954. widthSegments: widthSegments,
  6955. heightSegments: heightSegments,
  6956. depthSegments: depthSegments
  6957. };
  6958. const scope = this;
  6959. // segments
  6960. widthSegments = Math.floor( widthSegments );
  6961. heightSegments = Math.floor( heightSegments );
  6962. depthSegments = Math.floor( depthSegments );
  6963. // buffers
  6964. const indices = [];
  6965. const vertices = [];
  6966. const normals = [];
  6967. const uvs = [];
  6968. // helper variables
  6969. let numberOfVertices = 0;
  6970. let groupStart = 0;
  6971. // build each side of the box geometry
  6972. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6973. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6974. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6975. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6976. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6977. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6978. // build geometry
  6979. this.setIndex( indices );
  6980. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6981. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6982. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6983. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6984. const segmentWidth = width / gridX;
  6985. const segmentHeight = height / gridY;
  6986. const widthHalf = width / 2;
  6987. const heightHalf = height / 2;
  6988. const depthHalf = depth / 2;
  6989. const gridX1 = gridX + 1;
  6990. const gridY1 = gridY + 1;
  6991. let vertexCounter = 0;
  6992. let groupCount = 0;
  6993. const vector = new Vector3();
  6994. // generate vertices, normals and uvs
  6995. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6996. const y = iy * segmentHeight - heightHalf;
  6997. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6998. const x = ix * segmentWidth - widthHalf;
  6999. // set values to correct vector component
  7000. vector[ u ] = x * udir;
  7001. vector[ v ] = y * vdir;
  7002. vector[ w ] = depthHalf;
  7003. // now apply vector to vertex buffer
  7004. vertices.push( vector.x, vector.y, vector.z );
  7005. // set values to correct vector component
  7006. vector[ u ] = 0;
  7007. vector[ v ] = 0;
  7008. vector[ w ] = depth > 0 ? 1 : - 1;
  7009. // now apply vector to normal buffer
  7010. normals.push( vector.x, vector.y, vector.z );
  7011. // uvs
  7012. uvs.push( ix / gridX );
  7013. uvs.push( 1 - ( iy / gridY ) );
  7014. // counters
  7015. vertexCounter += 1;
  7016. }
  7017. }
  7018. // indices
  7019. // 1. you need three indices to draw a single face
  7020. // 2. a single segment consists of two faces
  7021. // 3. so we need to generate six (2*3) indices per segment
  7022. for ( let iy = 0; iy < gridY; iy ++ ) {
  7023. for ( let ix = 0; ix < gridX; ix ++ ) {
  7024. const a = numberOfVertices + ix + gridX1 * iy;
  7025. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7026. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7027. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7028. // faces
  7029. indices.push( a, b, d );
  7030. indices.push( b, c, d );
  7031. // increase counter
  7032. groupCount += 6;
  7033. }
  7034. }
  7035. // add a group to the geometry. this will ensure multi material support
  7036. scope.addGroup( groupStart, groupCount, materialIndex );
  7037. // calculate new start value for groups
  7038. groupStart += groupCount;
  7039. // update total number of vertices
  7040. numberOfVertices += vertexCounter;
  7041. }
  7042. }
  7043. copy( source ) {
  7044. super.copy( source );
  7045. this.parameters = Object.assign( {}, source.parameters );
  7046. return this;
  7047. }
  7048. static fromJSON( data ) {
  7049. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7050. }
  7051. }
  7052. /**
  7053. * Uniform Utilities
  7054. */
  7055. function cloneUniforms( src ) {
  7056. const dst = {};
  7057. for ( const u in src ) {
  7058. dst[ u ] = {};
  7059. for ( const p in src[ u ] ) {
  7060. const property = src[ u ][ p ];
  7061. if ( property && ( property.isColor ||
  7062. property.isMatrix3 || property.isMatrix4 ||
  7063. property.isVector2 || property.isVector3 || property.isVector4 ||
  7064. property.isTexture || property.isQuaternion ) ) {
  7065. if ( property.isRenderTargetTexture ) {
  7066. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7067. dst[ u ][ p ] = null;
  7068. } else {
  7069. dst[ u ][ p ] = property.clone();
  7070. }
  7071. } else if ( Array.isArray( property ) ) {
  7072. dst[ u ][ p ] = property.slice();
  7073. } else {
  7074. dst[ u ][ p ] = property;
  7075. }
  7076. }
  7077. }
  7078. return dst;
  7079. }
  7080. function mergeUniforms( uniforms ) {
  7081. const merged = {};
  7082. for ( let u = 0; u < uniforms.length; u ++ ) {
  7083. const tmp = cloneUniforms( uniforms[ u ] );
  7084. for ( const p in tmp ) {
  7085. merged[ p ] = tmp[ p ];
  7086. }
  7087. }
  7088. return merged;
  7089. }
  7090. function cloneUniformsGroups( src ) {
  7091. const dst = [];
  7092. for ( let u = 0; u < src.length; u ++ ) {
  7093. dst.push( src[ u ].clone() );
  7094. }
  7095. return dst;
  7096. }
  7097. function getUnlitUniformColorSpace( renderer ) {
  7098. if ( renderer.getRenderTarget() === null ) {
  7099. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7100. return renderer.outputColorSpace;
  7101. }
  7102. return LinearSRGBColorSpace;
  7103. }
  7104. // Legacy
  7105. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7106. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7107. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7108. class ShaderMaterial extends Material {
  7109. constructor( parameters ) {
  7110. super();
  7111. this.isShaderMaterial = true;
  7112. this.type = 'ShaderMaterial';
  7113. this.defines = {};
  7114. this.uniforms = {};
  7115. this.uniformsGroups = [];
  7116. this.vertexShader = default_vertex;
  7117. this.fragmentShader = default_fragment;
  7118. this.linewidth = 1;
  7119. this.wireframe = false;
  7120. this.wireframeLinewidth = 1;
  7121. this.fog = false; // set to use scene fog
  7122. this.lights = false; // set to use scene lights
  7123. this.clipping = false; // set to use user-defined clipping planes
  7124. this.forceSinglePass = true;
  7125. this.extensions = {
  7126. derivatives: false, // set to use derivatives
  7127. fragDepth: false, // set to use fragment depth values
  7128. drawBuffers: false, // set to use draw buffers
  7129. shaderTextureLOD: false // set to use shader texture LOD
  7130. };
  7131. // When rendered geometry doesn't include these attributes but the material does,
  7132. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7133. this.defaultAttributeValues = {
  7134. 'color': [ 1, 1, 1 ],
  7135. 'uv': [ 0, 0 ],
  7136. 'uv1': [ 0, 0 ]
  7137. };
  7138. this.index0AttributeName = undefined;
  7139. this.uniformsNeedUpdate = false;
  7140. this.glslVersion = null;
  7141. if ( parameters !== undefined ) {
  7142. this.setValues( parameters );
  7143. }
  7144. }
  7145. copy( source ) {
  7146. super.copy( source );
  7147. this.fragmentShader = source.fragmentShader;
  7148. this.vertexShader = source.vertexShader;
  7149. this.uniforms = cloneUniforms( source.uniforms );
  7150. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7151. this.defines = Object.assign( {}, source.defines );
  7152. this.wireframe = source.wireframe;
  7153. this.wireframeLinewidth = source.wireframeLinewidth;
  7154. this.fog = source.fog;
  7155. this.lights = source.lights;
  7156. this.clipping = source.clipping;
  7157. this.extensions = Object.assign( {}, source.extensions );
  7158. this.glslVersion = source.glslVersion;
  7159. return this;
  7160. }
  7161. toJSON( meta ) {
  7162. const data = super.toJSON( meta );
  7163. data.glslVersion = this.glslVersion;
  7164. data.uniforms = {};
  7165. for ( const name in this.uniforms ) {
  7166. const uniform = this.uniforms[ name ];
  7167. const value = uniform.value;
  7168. if ( value && value.isTexture ) {
  7169. data.uniforms[ name ] = {
  7170. type: 't',
  7171. value: value.toJSON( meta ).uuid
  7172. };
  7173. } else if ( value && value.isColor ) {
  7174. data.uniforms[ name ] = {
  7175. type: 'c',
  7176. value: value.getHex()
  7177. };
  7178. } else if ( value && value.isVector2 ) {
  7179. data.uniforms[ name ] = {
  7180. type: 'v2',
  7181. value: value.toArray()
  7182. };
  7183. } else if ( value && value.isVector3 ) {
  7184. data.uniforms[ name ] = {
  7185. type: 'v3',
  7186. value: value.toArray()
  7187. };
  7188. } else if ( value && value.isVector4 ) {
  7189. data.uniforms[ name ] = {
  7190. type: 'v4',
  7191. value: value.toArray()
  7192. };
  7193. } else if ( value && value.isMatrix3 ) {
  7194. data.uniforms[ name ] = {
  7195. type: 'm3',
  7196. value: value.toArray()
  7197. };
  7198. } else if ( value && value.isMatrix4 ) {
  7199. data.uniforms[ name ] = {
  7200. type: 'm4',
  7201. value: value.toArray()
  7202. };
  7203. } else {
  7204. data.uniforms[ name ] = {
  7205. value: value
  7206. };
  7207. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7208. }
  7209. }
  7210. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7211. data.vertexShader = this.vertexShader;
  7212. data.fragmentShader = this.fragmentShader;
  7213. data.lights = this.lights;
  7214. data.clipping = this.clipping;
  7215. const extensions = {};
  7216. for ( const key in this.extensions ) {
  7217. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7218. }
  7219. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7220. return data;
  7221. }
  7222. }
  7223. class Camera extends Object3D {
  7224. constructor() {
  7225. super();
  7226. this.isCamera = true;
  7227. this.type = 'Camera';
  7228. this.matrixWorldInverse = new Matrix4();
  7229. this.projectionMatrix = new Matrix4();
  7230. this.projectionMatrixInverse = new Matrix4();
  7231. }
  7232. copy( source, recursive ) {
  7233. super.copy( source, recursive );
  7234. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7235. this.projectionMatrix.copy( source.projectionMatrix );
  7236. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7237. return this;
  7238. }
  7239. getWorldDirection( target ) {
  7240. this.updateWorldMatrix( true, false );
  7241. const e = this.matrixWorld.elements;
  7242. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7243. }
  7244. updateMatrixWorld( force ) {
  7245. super.updateMatrixWorld( force );
  7246. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7247. }
  7248. updateWorldMatrix( updateParents, updateChildren ) {
  7249. super.updateWorldMatrix( updateParents, updateChildren );
  7250. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7251. }
  7252. clone() {
  7253. return new this.constructor().copy( this );
  7254. }
  7255. }
  7256. class PerspectiveCamera extends Camera {
  7257. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7258. super();
  7259. this.isPerspectiveCamera = true;
  7260. this.type = 'PerspectiveCamera';
  7261. this.fov = fov;
  7262. this.zoom = 1;
  7263. this.near = near;
  7264. this.far = far;
  7265. this.focus = 10;
  7266. this.aspect = aspect;
  7267. this.view = null;
  7268. this.filmGauge = 35; // width of the film (default in millimeters)
  7269. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7270. this.updateProjectionMatrix();
  7271. }
  7272. copy( source, recursive ) {
  7273. super.copy( source, recursive );
  7274. this.fov = source.fov;
  7275. this.zoom = source.zoom;
  7276. this.near = source.near;
  7277. this.far = source.far;
  7278. this.focus = source.focus;
  7279. this.aspect = source.aspect;
  7280. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7281. this.filmGauge = source.filmGauge;
  7282. this.filmOffset = source.filmOffset;
  7283. return this;
  7284. }
  7285. /**
  7286. * Sets the FOV by focal length in respect to the current .filmGauge.
  7287. *
  7288. * The default film gauge is 35, so that the focal length can be specified for
  7289. * a 35mm (full frame) camera.
  7290. *
  7291. * Values for focal length and film gauge must have the same unit.
  7292. */
  7293. setFocalLength( focalLength ) {
  7294. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7295. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7296. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7297. this.updateProjectionMatrix();
  7298. }
  7299. /**
  7300. * Calculates the focal length from the current .fov and .filmGauge.
  7301. */
  7302. getFocalLength() {
  7303. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7304. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7305. }
  7306. getEffectiveFOV() {
  7307. return RAD2DEG * 2 * Math.atan(
  7308. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7309. }
  7310. getFilmWidth() {
  7311. // film not completely covered in portrait format (aspect < 1)
  7312. return this.filmGauge * Math.min( this.aspect, 1 );
  7313. }
  7314. getFilmHeight() {
  7315. // film not completely covered in landscape format (aspect > 1)
  7316. return this.filmGauge / Math.max( this.aspect, 1 );
  7317. }
  7318. /**
  7319. * Sets an offset in a larger frustum. This is useful for multi-window or
  7320. * multi-monitor/multi-machine setups.
  7321. *
  7322. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7323. * the monitors are in grid like this
  7324. *
  7325. * +---+---+---+
  7326. * | A | B | C |
  7327. * +---+---+---+
  7328. * | D | E | F |
  7329. * +---+---+---+
  7330. *
  7331. * then for each monitor you would call it like this
  7332. *
  7333. * const w = 1920;
  7334. * const h = 1080;
  7335. * const fullWidth = w * 3;
  7336. * const fullHeight = h * 2;
  7337. *
  7338. * --A--
  7339. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7340. * --B--
  7341. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7342. * --C--
  7343. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7344. * --D--
  7345. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7346. * --E--
  7347. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7348. * --F--
  7349. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7350. *
  7351. * Note there is no reason monitors have to be the same size or in a grid.
  7352. */
  7353. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7354. this.aspect = fullWidth / fullHeight;
  7355. if ( this.view === null ) {
  7356. this.view = {
  7357. enabled: true,
  7358. fullWidth: 1,
  7359. fullHeight: 1,
  7360. offsetX: 0,
  7361. offsetY: 0,
  7362. width: 1,
  7363. height: 1
  7364. };
  7365. }
  7366. this.view.enabled = true;
  7367. this.view.fullWidth = fullWidth;
  7368. this.view.fullHeight = fullHeight;
  7369. this.view.offsetX = x;
  7370. this.view.offsetY = y;
  7371. this.view.width = width;
  7372. this.view.height = height;
  7373. this.updateProjectionMatrix();
  7374. }
  7375. clearViewOffset() {
  7376. if ( this.view !== null ) {
  7377. this.view.enabled = false;
  7378. }
  7379. this.updateProjectionMatrix();
  7380. }
  7381. updateProjectionMatrix() {
  7382. const near = this.near;
  7383. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7384. let height = 2 * top;
  7385. let width = this.aspect * height;
  7386. let left = - 0.5 * width;
  7387. const view = this.view;
  7388. if ( this.view !== null && this.view.enabled ) {
  7389. const fullWidth = view.fullWidth,
  7390. fullHeight = view.fullHeight;
  7391. left += view.offsetX * width / fullWidth;
  7392. top -= view.offsetY * height / fullHeight;
  7393. width *= view.width / fullWidth;
  7394. height *= view.height / fullHeight;
  7395. }
  7396. const skew = this.filmOffset;
  7397. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7398. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7399. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7400. }
  7401. toJSON( meta ) {
  7402. const data = super.toJSON( meta );
  7403. data.object.fov = this.fov;
  7404. data.object.zoom = this.zoom;
  7405. data.object.near = this.near;
  7406. data.object.far = this.far;
  7407. data.object.focus = this.focus;
  7408. data.object.aspect = this.aspect;
  7409. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7410. data.object.filmGauge = this.filmGauge;
  7411. data.object.filmOffset = this.filmOffset;
  7412. return data;
  7413. }
  7414. }
  7415. const fov = - 90; // negative fov is not an error
  7416. const aspect = 1;
  7417. class CubeCamera extends Object3D {
  7418. constructor( near, far, renderTarget ) {
  7419. super();
  7420. this.type = 'CubeCamera';
  7421. this.renderTarget = renderTarget;
  7422. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7423. cameraPX.layers = this.layers;
  7424. cameraPX.up.set( 0, 1, 0 );
  7425. cameraPX.lookAt( 1, 0, 0 );
  7426. this.add( cameraPX );
  7427. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7428. cameraNX.layers = this.layers;
  7429. cameraNX.up.set( 0, 1, 0 );
  7430. cameraNX.lookAt( - 1, 0, 0 );
  7431. this.add( cameraNX );
  7432. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7433. cameraPY.layers = this.layers;
  7434. cameraPY.up.set( 0, 0, - 1 );
  7435. cameraPY.lookAt( 0, 1, 0 );
  7436. this.add( cameraPY );
  7437. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7438. cameraNY.layers = this.layers;
  7439. cameraNY.up.set( 0, 0, 1 );
  7440. cameraNY.lookAt( 0, - 1, 0 );
  7441. this.add( cameraNY );
  7442. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7443. cameraPZ.layers = this.layers;
  7444. cameraPZ.up.set( 0, 1, 0 );
  7445. cameraPZ.lookAt( 0, 0, 1 );
  7446. this.add( cameraPZ );
  7447. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7448. cameraNZ.layers = this.layers;
  7449. cameraNZ.up.set( 0, 1, 0 );
  7450. cameraNZ.lookAt( 0, 0, - 1 );
  7451. this.add( cameraNZ );
  7452. }
  7453. update( renderer, scene ) {
  7454. if ( this.parent === null ) this.updateMatrixWorld();
  7455. const renderTarget = this.renderTarget;
  7456. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7457. const currentRenderTarget = renderer.getRenderTarget();
  7458. const currentToneMapping = renderer.toneMapping;
  7459. const currentXrEnabled = renderer.xr.enabled;
  7460. renderer.toneMapping = NoToneMapping;
  7461. renderer.xr.enabled = false;
  7462. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7463. renderTarget.texture.generateMipmaps = false;
  7464. renderer.setRenderTarget( renderTarget, 0 );
  7465. renderer.render( scene, cameraPX );
  7466. renderer.setRenderTarget( renderTarget, 1 );
  7467. renderer.render( scene, cameraNX );
  7468. renderer.setRenderTarget( renderTarget, 2 );
  7469. renderer.render( scene, cameraPY );
  7470. renderer.setRenderTarget( renderTarget, 3 );
  7471. renderer.render( scene, cameraNY );
  7472. renderer.setRenderTarget( renderTarget, 4 );
  7473. renderer.render( scene, cameraPZ );
  7474. renderTarget.texture.generateMipmaps = generateMipmaps;
  7475. renderer.setRenderTarget( renderTarget, 5 );
  7476. renderer.render( scene, cameraNZ );
  7477. renderer.setRenderTarget( currentRenderTarget );
  7478. renderer.toneMapping = currentToneMapping;
  7479. renderer.xr.enabled = currentXrEnabled;
  7480. renderTarget.texture.needsPMREMUpdate = true;
  7481. }
  7482. }
  7483. class CubeTexture extends Texture {
  7484. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7485. images = images !== undefined ? images : [];
  7486. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7487. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7488. this.isCubeTexture = true;
  7489. this.flipY = false;
  7490. }
  7491. get images() {
  7492. return this.image;
  7493. }
  7494. set images( value ) {
  7495. this.image = value;
  7496. }
  7497. }
  7498. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7499. constructor( size = 1, options = {} ) {
  7500. super( size, size, options );
  7501. this.isWebGLCubeRenderTarget = true;
  7502. const image = { width: size, height: size, depth: 1 };
  7503. const images = [ image, image, image, image, image, image ];
  7504. if ( options.encoding !== undefined ) {
  7505. // @deprecated, r152
  7506. warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  7507. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  7508. }
  7509. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7510. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7511. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7512. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7513. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7514. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7515. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7516. this.texture.isRenderTargetTexture = true;
  7517. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7518. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7519. }
  7520. fromEquirectangularTexture( renderer, texture ) {
  7521. this.texture.type = texture.type;
  7522. this.texture.colorSpace = texture.colorSpace;
  7523. this.texture.generateMipmaps = texture.generateMipmaps;
  7524. this.texture.minFilter = texture.minFilter;
  7525. this.texture.magFilter = texture.magFilter;
  7526. const shader = {
  7527. uniforms: {
  7528. tEquirect: { value: null },
  7529. },
  7530. vertexShader: /* glsl */`
  7531. varying vec3 vWorldDirection;
  7532. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7533. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7534. }
  7535. void main() {
  7536. vWorldDirection = transformDirection( position, modelMatrix );
  7537. #include <begin_vertex>
  7538. #include <project_vertex>
  7539. }
  7540. `,
  7541. fragmentShader: /* glsl */`
  7542. uniform sampler2D tEquirect;
  7543. varying vec3 vWorldDirection;
  7544. #include <common>
  7545. void main() {
  7546. vec3 direction = normalize( vWorldDirection );
  7547. vec2 sampleUV = equirectUv( direction );
  7548. gl_FragColor = texture2D( tEquirect, sampleUV );
  7549. }
  7550. `
  7551. };
  7552. const geometry = new BoxGeometry( 5, 5, 5 );
  7553. const material = new ShaderMaterial( {
  7554. name: 'CubemapFromEquirect',
  7555. uniforms: cloneUniforms( shader.uniforms ),
  7556. vertexShader: shader.vertexShader,
  7557. fragmentShader: shader.fragmentShader,
  7558. side: BackSide,
  7559. blending: NoBlending
  7560. } );
  7561. material.uniforms.tEquirect.value = texture;
  7562. const mesh = new Mesh( geometry, material );
  7563. const currentMinFilter = texture.minFilter;
  7564. // Avoid blurred poles
  7565. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7566. const camera = new CubeCamera( 1, 10, this );
  7567. camera.update( renderer, mesh );
  7568. texture.minFilter = currentMinFilter;
  7569. mesh.geometry.dispose();
  7570. mesh.material.dispose();
  7571. return this;
  7572. }
  7573. clear( renderer, color, depth, stencil ) {
  7574. const currentRenderTarget = renderer.getRenderTarget();
  7575. for ( let i = 0; i < 6; i ++ ) {
  7576. renderer.setRenderTarget( this, i );
  7577. renderer.clear( color, depth, stencil );
  7578. }
  7579. renderer.setRenderTarget( currentRenderTarget );
  7580. }
  7581. }
  7582. const _vector1 = /*@__PURE__*/ new Vector3();
  7583. const _vector2 = /*@__PURE__*/ new Vector3();
  7584. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7585. class Plane {
  7586. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7587. this.isPlane = true;
  7588. // normal is assumed to be normalized
  7589. this.normal = normal;
  7590. this.constant = constant;
  7591. }
  7592. set( normal, constant ) {
  7593. this.normal.copy( normal );
  7594. this.constant = constant;
  7595. return this;
  7596. }
  7597. setComponents( x, y, z, w ) {
  7598. this.normal.set( x, y, z );
  7599. this.constant = w;
  7600. return this;
  7601. }
  7602. setFromNormalAndCoplanarPoint( normal, point ) {
  7603. this.normal.copy( normal );
  7604. this.constant = - point.dot( this.normal );
  7605. return this;
  7606. }
  7607. setFromCoplanarPoints( a, b, c ) {
  7608. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7609. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7610. this.setFromNormalAndCoplanarPoint( normal, a );
  7611. return this;
  7612. }
  7613. copy( plane ) {
  7614. this.normal.copy( plane.normal );
  7615. this.constant = plane.constant;
  7616. return this;
  7617. }
  7618. normalize() {
  7619. // Note: will lead to a divide by zero if the plane is invalid.
  7620. const inverseNormalLength = 1.0 / this.normal.length();
  7621. this.normal.multiplyScalar( inverseNormalLength );
  7622. this.constant *= inverseNormalLength;
  7623. return this;
  7624. }
  7625. negate() {
  7626. this.constant *= - 1;
  7627. this.normal.negate();
  7628. return this;
  7629. }
  7630. distanceToPoint( point ) {
  7631. return this.normal.dot( point ) + this.constant;
  7632. }
  7633. distanceToSphere( sphere ) {
  7634. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7635. }
  7636. projectPoint( point, target ) {
  7637. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7638. }
  7639. intersectLine( line, target ) {
  7640. const direction = line.delta( _vector1 );
  7641. const denominator = this.normal.dot( direction );
  7642. if ( denominator === 0 ) {
  7643. // line is coplanar, return origin
  7644. if ( this.distanceToPoint( line.start ) === 0 ) {
  7645. return target.copy( line.start );
  7646. }
  7647. // Unsure if this is the correct method to handle this case.
  7648. return null;
  7649. }
  7650. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7651. if ( t < 0 || t > 1 ) {
  7652. return null;
  7653. }
  7654. return target.copy( line.start ).addScaledVector( direction, t );
  7655. }
  7656. intersectsLine( line ) {
  7657. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7658. const startSign = this.distanceToPoint( line.start );
  7659. const endSign = this.distanceToPoint( line.end );
  7660. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7661. }
  7662. intersectsBox( box ) {
  7663. return box.intersectsPlane( this );
  7664. }
  7665. intersectsSphere( sphere ) {
  7666. return sphere.intersectsPlane( this );
  7667. }
  7668. coplanarPoint( target ) {
  7669. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7670. }
  7671. applyMatrix4( matrix, optionalNormalMatrix ) {
  7672. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7673. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7674. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7675. this.constant = - referencePoint.dot( normal );
  7676. return this;
  7677. }
  7678. translate( offset ) {
  7679. this.constant -= offset.dot( this.normal );
  7680. return this;
  7681. }
  7682. equals( plane ) {
  7683. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7684. }
  7685. clone() {
  7686. return new this.constructor().copy( this );
  7687. }
  7688. }
  7689. const _sphere$3 = /*@__PURE__*/ new Sphere();
  7690. const _vector$6 = /*@__PURE__*/ new Vector3();
  7691. class Frustum {
  7692. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7693. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7694. }
  7695. set( p0, p1, p2, p3, p4, p5 ) {
  7696. const planes = this.planes;
  7697. planes[ 0 ].copy( p0 );
  7698. planes[ 1 ].copy( p1 );
  7699. planes[ 2 ].copy( p2 );
  7700. planes[ 3 ].copy( p3 );
  7701. planes[ 4 ].copy( p4 );
  7702. planes[ 5 ].copy( p5 );
  7703. return this;
  7704. }
  7705. copy( frustum ) {
  7706. const planes = this.planes;
  7707. for ( let i = 0; i < 6; i ++ ) {
  7708. planes[ i ].copy( frustum.planes[ i ] );
  7709. }
  7710. return this;
  7711. }
  7712. setFromProjectionMatrix( m ) {
  7713. const planes = this.planes;
  7714. const me = m.elements;
  7715. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7716. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7717. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7718. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7719. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7720. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7721. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7722. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7723. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7724. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7725. return this;
  7726. }
  7727. intersectsObject( object ) {
  7728. if ( object.boundingSphere !== undefined ) {
  7729. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7730. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7731. } else {
  7732. const geometry = object.geometry;
  7733. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7734. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7735. }
  7736. return this.intersectsSphere( _sphere$3 );
  7737. }
  7738. intersectsSprite( sprite ) {
  7739. _sphere$3.center.set( 0, 0, 0 );
  7740. _sphere$3.radius = 0.7071067811865476;
  7741. _sphere$3.applyMatrix4( sprite.matrixWorld );
  7742. return this.intersectsSphere( _sphere$3 );
  7743. }
  7744. intersectsSphere( sphere ) {
  7745. const planes = this.planes;
  7746. const center = sphere.center;
  7747. const negRadius = - sphere.radius;
  7748. for ( let i = 0; i < 6; i ++ ) {
  7749. const distance = planes[ i ].distanceToPoint( center );
  7750. if ( distance < negRadius ) {
  7751. return false;
  7752. }
  7753. }
  7754. return true;
  7755. }
  7756. intersectsBox( box ) {
  7757. const planes = this.planes;
  7758. for ( let i = 0; i < 6; i ++ ) {
  7759. const plane = planes[ i ];
  7760. // corner at max distance
  7761. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7762. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7763. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7764. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  7765. return false;
  7766. }
  7767. }
  7768. return true;
  7769. }
  7770. containsPoint( point ) {
  7771. const planes = this.planes;
  7772. for ( let i = 0; i < 6; i ++ ) {
  7773. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7774. return false;
  7775. }
  7776. }
  7777. return true;
  7778. }
  7779. clone() {
  7780. return new this.constructor().copy( this );
  7781. }
  7782. }
  7783. function WebGLAnimation() {
  7784. let context = null;
  7785. let isAnimating = false;
  7786. let animationLoop = null;
  7787. let requestId = null;
  7788. function onAnimationFrame( time, frame ) {
  7789. animationLoop( time, frame );
  7790. requestId = context.requestAnimationFrame( onAnimationFrame );
  7791. }
  7792. return {
  7793. start: function () {
  7794. if ( isAnimating === true ) return;
  7795. if ( animationLoop === null ) return;
  7796. requestId = context.requestAnimationFrame( onAnimationFrame );
  7797. isAnimating = true;
  7798. },
  7799. stop: function () {
  7800. context.cancelAnimationFrame( requestId );
  7801. isAnimating = false;
  7802. },
  7803. setAnimationLoop: function ( callback ) {
  7804. animationLoop = callback;
  7805. },
  7806. setContext: function ( value ) {
  7807. context = value;
  7808. }
  7809. };
  7810. }
  7811. function WebGLAttributes( gl, capabilities ) {
  7812. const isWebGL2 = capabilities.isWebGL2;
  7813. const buffers = new WeakMap();
  7814. function createBuffer( attribute, bufferType ) {
  7815. const array = attribute.array;
  7816. const usage = attribute.usage;
  7817. const buffer = gl.createBuffer();
  7818. gl.bindBuffer( bufferType, buffer );
  7819. gl.bufferData( bufferType, array, usage );
  7820. attribute.onUploadCallback();
  7821. let type;
  7822. if ( array instanceof Float32Array ) {
  7823. type = gl.FLOAT;
  7824. } else if ( array instanceof Uint16Array ) {
  7825. if ( attribute.isFloat16BufferAttribute ) {
  7826. if ( isWebGL2 ) {
  7827. type = gl.HALF_FLOAT;
  7828. } else {
  7829. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7830. }
  7831. } else {
  7832. type = gl.UNSIGNED_SHORT;
  7833. }
  7834. } else if ( array instanceof Int16Array ) {
  7835. type = gl.SHORT;
  7836. } else if ( array instanceof Uint32Array ) {
  7837. type = gl.UNSIGNED_INT;
  7838. } else if ( array instanceof Int32Array ) {
  7839. type = gl.INT;
  7840. } else if ( array instanceof Int8Array ) {
  7841. type = gl.BYTE;
  7842. } else if ( array instanceof Uint8Array ) {
  7843. type = gl.UNSIGNED_BYTE;
  7844. } else if ( array instanceof Uint8ClampedArray ) {
  7845. type = gl.UNSIGNED_BYTE;
  7846. } else {
  7847. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7848. }
  7849. return {
  7850. buffer: buffer,
  7851. type: type,
  7852. bytesPerElement: array.BYTES_PER_ELEMENT,
  7853. version: attribute.version
  7854. };
  7855. }
  7856. function updateBuffer( buffer, attribute, bufferType ) {
  7857. const array = attribute.array;
  7858. const updateRange = attribute.updateRange;
  7859. gl.bindBuffer( bufferType, buffer );
  7860. if ( updateRange.count === - 1 ) {
  7861. // Not using update ranges
  7862. gl.bufferSubData( bufferType, 0, array );
  7863. } else {
  7864. if ( isWebGL2 ) {
  7865. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7866. array, updateRange.offset, updateRange.count );
  7867. } else {
  7868. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7869. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7870. }
  7871. updateRange.count = - 1; // reset range
  7872. }
  7873. attribute.onUploadCallback();
  7874. }
  7875. //
  7876. function get( attribute ) {
  7877. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7878. return buffers.get( attribute );
  7879. }
  7880. function remove( attribute ) {
  7881. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7882. const data = buffers.get( attribute );
  7883. if ( data ) {
  7884. gl.deleteBuffer( data.buffer );
  7885. buffers.delete( attribute );
  7886. }
  7887. }
  7888. function update( attribute, bufferType ) {
  7889. if ( attribute.isGLBufferAttribute ) {
  7890. const cached = buffers.get( attribute );
  7891. if ( ! cached || cached.version < attribute.version ) {
  7892. buffers.set( attribute, {
  7893. buffer: attribute.buffer,
  7894. type: attribute.type,
  7895. bytesPerElement: attribute.elementSize,
  7896. version: attribute.version
  7897. } );
  7898. }
  7899. return;
  7900. }
  7901. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7902. const data = buffers.get( attribute );
  7903. if ( data === undefined ) {
  7904. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7905. } else if ( data.version < attribute.version ) {
  7906. updateBuffer( data.buffer, attribute, bufferType );
  7907. data.version = attribute.version;
  7908. }
  7909. }
  7910. return {
  7911. get: get,
  7912. remove: remove,
  7913. update: update
  7914. };
  7915. }
  7916. class PlaneGeometry extends BufferGeometry {
  7917. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7918. super();
  7919. this.type = 'PlaneGeometry';
  7920. this.parameters = {
  7921. width: width,
  7922. height: height,
  7923. widthSegments: widthSegments,
  7924. heightSegments: heightSegments
  7925. };
  7926. const width_half = width / 2;
  7927. const height_half = height / 2;
  7928. const gridX = Math.floor( widthSegments );
  7929. const gridY = Math.floor( heightSegments );
  7930. const gridX1 = gridX + 1;
  7931. const gridY1 = gridY + 1;
  7932. const segment_width = width / gridX;
  7933. const segment_height = height / gridY;
  7934. //
  7935. const indices = [];
  7936. const vertices = [];
  7937. const normals = [];
  7938. const uvs = [];
  7939. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7940. const y = iy * segment_height - height_half;
  7941. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7942. const x = ix * segment_width - width_half;
  7943. vertices.push( x, - y, 0 );
  7944. normals.push( 0, 0, 1 );
  7945. uvs.push( ix / gridX );
  7946. uvs.push( 1 - ( iy / gridY ) );
  7947. }
  7948. }
  7949. for ( let iy = 0; iy < gridY; iy ++ ) {
  7950. for ( let ix = 0; ix < gridX; ix ++ ) {
  7951. const a = ix + gridX1 * iy;
  7952. const b = ix + gridX1 * ( iy + 1 );
  7953. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7954. const d = ( ix + 1 ) + gridX1 * iy;
  7955. indices.push( a, b, d );
  7956. indices.push( b, c, d );
  7957. }
  7958. }
  7959. this.setIndex( indices );
  7960. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7961. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7962. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7963. }
  7964. copy( source ) {
  7965. super.copy( source );
  7966. this.parameters = Object.assign( {}, source.parameters );
  7967. return this;
  7968. }
  7969. static fromJSON( data ) {
  7970. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7971. }
  7972. }
  7973. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  7974. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7975. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7976. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7977. 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";
  7978. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7979. var begin_vertex = "vec3 transformed = vec3( position );";
  7980. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7981. 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";
  7982. 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";
  7983. 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";
  7984. 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";
  7985. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7986. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7987. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7988. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7989. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7990. 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";
  7991. 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";
  7992. 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";
  7993. 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";
  7994. 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";
  7995. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7996. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  7997. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7998. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7999. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8000. 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}";
  8001. 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";
  8002. 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";
  8003. 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";
  8004. 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";
  8005. 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";
  8006. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8007. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8008. 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";
  8009. 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";
  8010. 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}";
  8011. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8012. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8013. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8014. 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";
  8015. 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";
  8016. 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";
  8017. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8018. 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";
  8019. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8020. 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";
  8021. 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";
  8022. 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}";
  8023. 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";
  8024. 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";
  8025. 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";
  8026. 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";
  8027. 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";
  8028. 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";
  8029. 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";
  8030. var map_fragment = "#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, vMapUv );\n#endif";
  8031. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8032. 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";
  8033. 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";
  8034. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8035. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8036. 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";
  8037. 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";
  8038. 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";
  8039. 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";
  8040. 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;";
  8041. 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";
  8042. 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";
  8043. 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";
  8044. 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";
  8045. 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";
  8046. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8047. 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";
  8048. 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";
  8049. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8050. 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 );";
  8051. 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}";
  8052. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8053. 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;";
  8054. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8055. 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";
  8056. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8057. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8058. 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";
  8059. 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";
  8060. 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";
  8061. 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}";
  8062. 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";
  8063. 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";
  8064. 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";
  8065. 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";
  8066. 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";
  8067. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8068. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8069. 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; }";
  8070. 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";
  8071. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 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";
  8072. 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";
  8073. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_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";
  8074. 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";
  8075. 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";
  8076. 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}";
  8077. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8078. 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}";
  8079. 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}";
  8080. 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}";
  8081. 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}";
  8082. 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}";
  8083. 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}";
  8084. 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}";
  8085. 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}";
  8086. 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}";
  8087. 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}";
  8088. 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}";
  8089. 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}";
  8090. 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}";
  8091. 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}";
  8092. 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}";
  8093. 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}";
  8094. 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}";
  8095. 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}";
  8096. 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}";
  8097. 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}";
  8098. 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}";
  8099. 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}";
  8100. 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}";
  8101. 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}";
  8102. 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}";
  8103. 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}";
  8104. 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}";
  8105. 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}";
  8106. 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}";
  8107. 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}";
  8108. 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}";
  8109. 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}";
  8110. const ShaderChunk = {
  8111. alphamap_fragment: alphamap_fragment,
  8112. alphamap_pars_fragment: alphamap_pars_fragment,
  8113. alphatest_fragment: alphatest_fragment,
  8114. alphatest_pars_fragment: alphatest_pars_fragment,
  8115. aomap_fragment: aomap_fragment,
  8116. aomap_pars_fragment: aomap_pars_fragment,
  8117. begin_vertex: begin_vertex,
  8118. beginnormal_vertex: beginnormal_vertex,
  8119. bsdfs: bsdfs,
  8120. iridescence_fragment: iridescence_fragment,
  8121. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8122. clipping_planes_fragment: clipping_planes_fragment,
  8123. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8124. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8125. clipping_planes_vertex: clipping_planes_vertex,
  8126. color_fragment: color_fragment,
  8127. color_pars_fragment: color_pars_fragment,
  8128. color_pars_vertex: color_pars_vertex,
  8129. color_vertex: color_vertex,
  8130. common: common,
  8131. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8132. defaultnormal_vertex: defaultnormal_vertex,
  8133. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8134. displacementmap_vertex: displacementmap_vertex,
  8135. emissivemap_fragment: emissivemap_fragment,
  8136. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8137. encodings_fragment: encodings_fragment,
  8138. encodings_pars_fragment: encodings_pars_fragment,
  8139. envmap_fragment: envmap_fragment,
  8140. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8141. envmap_pars_fragment: envmap_pars_fragment,
  8142. envmap_pars_vertex: envmap_pars_vertex,
  8143. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8144. envmap_vertex: envmap_vertex,
  8145. fog_vertex: fog_vertex,
  8146. fog_pars_vertex: fog_pars_vertex,
  8147. fog_fragment: fog_fragment,
  8148. fog_pars_fragment: fog_pars_fragment,
  8149. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8150. lightmap_fragment: lightmap_fragment,
  8151. lightmap_pars_fragment: lightmap_pars_fragment,
  8152. lights_lambert_fragment: lights_lambert_fragment,
  8153. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8154. lights_pars_begin: lights_pars_begin,
  8155. lights_toon_fragment: lights_toon_fragment,
  8156. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8157. lights_phong_fragment: lights_phong_fragment,
  8158. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8159. lights_physical_fragment: lights_physical_fragment,
  8160. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8161. lights_fragment_begin: lights_fragment_begin,
  8162. lights_fragment_maps: lights_fragment_maps,
  8163. lights_fragment_end: lights_fragment_end,
  8164. logdepthbuf_fragment: logdepthbuf_fragment,
  8165. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8166. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8167. logdepthbuf_vertex: logdepthbuf_vertex,
  8168. map_fragment: map_fragment,
  8169. map_pars_fragment: map_pars_fragment,
  8170. map_particle_fragment: map_particle_fragment,
  8171. map_particle_pars_fragment: map_particle_pars_fragment,
  8172. metalnessmap_fragment: metalnessmap_fragment,
  8173. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8174. morphcolor_vertex: morphcolor_vertex,
  8175. morphnormal_vertex: morphnormal_vertex,
  8176. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8177. morphtarget_vertex: morphtarget_vertex,
  8178. normal_fragment_begin: normal_fragment_begin,
  8179. normal_fragment_maps: normal_fragment_maps,
  8180. normal_pars_fragment: normal_pars_fragment,
  8181. normal_pars_vertex: normal_pars_vertex,
  8182. normal_vertex: normal_vertex,
  8183. normalmap_pars_fragment: normalmap_pars_fragment,
  8184. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8185. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8186. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8187. iridescence_pars_fragment: iridescence_pars_fragment,
  8188. output_fragment: output_fragment,
  8189. packing: packing,
  8190. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8191. project_vertex: project_vertex,
  8192. dithering_fragment: dithering_fragment,
  8193. dithering_pars_fragment: dithering_pars_fragment,
  8194. roughnessmap_fragment: roughnessmap_fragment,
  8195. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8196. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8197. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8198. shadowmap_vertex: shadowmap_vertex,
  8199. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8200. skinbase_vertex: skinbase_vertex,
  8201. skinning_pars_vertex: skinning_pars_vertex,
  8202. skinning_vertex: skinning_vertex,
  8203. skinnormal_vertex: skinnormal_vertex,
  8204. specularmap_fragment: specularmap_fragment,
  8205. specularmap_pars_fragment: specularmap_pars_fragment,
  8206. tonemapping_fragment: tonemapping_fragment,
  8207. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8208. transmission_fragment: transmission_fragment,
  8209. transmission_pars_fragment: transmission_pars_fragment,
  8210. uv_pars_fragment: uv_pars_fragment,
  8211. uv_pars_vertex: uv_pars_vertex,
  8212. uv_vertex: uv_vertex,
  8213. worldpos_vertex: worldpos_vertex,
  8214. background_vert: vertex$h,
  8215. background_frag: fragment$h,
  8216. backgroundCube_vert: vertex$g,
  8217. backgroundCube_frag: fragment$g,
  8218. cube_vert: vertex$f,
  8219. cube_frag: fragment$f,
  8220. depth_vert: vertex$e,
  8221. depth_frag: fragment$e,
  8222. distanceRGBA_vert: vertex$d,
  8223. distanceRGBA_frag: fragment$d,
  8224. equirect_vert: vertex$c,
  8225. equirect_frag: fragment$c,
  8226. linedashed_vert: vertex$b,
  8227. linedashed_frag: fragment$b,
  8228. meshbasic_vert: vertex$a,
  8229. meshbasic_frag: fragment$a,
  8230. meshlambert_vert: vertex$9,
  8231. meshlambert_frag: fragment$9,
  8232. meshmatcap_vert: vertex$8,
  8233. meshmatcap_frag: fragment$8,
  8234. meshnormal_vert: vertex$7,
  8235. meshnormal_frag: fragment$7,
  8236. meshphong_vert: vertex$6,
  8237. meshphong_frag: fragment$6,
  8238. meshphysical_vert: vertex$5,
  8239. meshphysical_frag: fragment$5,
  8240. meshtoon_vert: vertex$4,
  8241. meshtoon_frag: fragment$4,
  8242. points_vert: vertex$3,
  8243. points_frag: fragment$3,
  8244. shadow_vert: vertex$2,
  8245. shadow_frag: fragment$2,
  8246. sprite_vert: vertex$1,
  8247. sprite_frag: fragment$1
  8248. };
  8249. /**
  8250. * Uniforms library for shared webgl shaders
  8251. */
  8252. const UniformsLib = {
  8253. common: {
  8254. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8255. opacity: { value: 1.0 },
  8256. map: { value: null },
  8257. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8258. alphaMap: { value: null },
  8259. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8260. alphaTest: { value: 0 }
  8261. },
  8262. specularmap: {
  8263. specularMap: { value: null },
  8264. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8265. },
  8266. envmap: {
  8267. envMap: { value: null },
  8268. flipEnvMap: { value: - 1 },
  8269. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8270. ior: { value: 1.5 }, // physical
  8271. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8272. },
  8273. aomap: {
  8274. aoMap: { value: null },
  8275. aoMapIntensity: { value: 1 },
  8276. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8277. },
  8278. lightmap: {
  8279. lightMap: { value: null },
  8280. lightMapIntensity: { value: 1 },
  8281. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8282. },
  8283. bumpmap: {
  8284. bumpMap: { value: null },
  8285. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8286. bumpScale: { value: 1 }
  8287. },
  8288. normalmap: {
  8289. normalMap: { value: null },
  8290. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8291. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8292. },
  8293. displacementmap: {
  8294. displacementMap: { value: null },
  8295. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8296. displacementScale: { value: 1 },
  8297. displacementBias: { value: 0 }
  8298. },
  8299. emissivemap: {
  8300. emissiveMap: { value: null },
  8301. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8302. },
  8303. metalnessmap: {
  8304. metalnessMap: { value: null },
  8305. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8306. },
  8307. roughnessmap: {
  8308. roughnessMap: { value: null },
  8309. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8310. },
  8311. gradientmap: {
  8312. gradientMap: { value: null }
  8313. },
  8314. fog: {
  8315. fogDensity: { value: 0.00025 },
  8316. fogNear: { value: 1 },
  8317. fogFar: { value: 2000 },
  8318. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8319. },
  8320. lights: {
  8321. ambientLightColor: { value: [] },
  8322. lightProbe: { value: [] },
  8323. directionalLights: { value: [], properties: {
  8324. direction: {},
  8325. color: {}
  8326. } },
  8327. directionalLightShadows: { value: [], properties: {
  8328. shadowBias: {},
  8329. shadowNormalBias: {},
  8330. shadowRadius: {},
  8331. shadowMapSize: {}
  8332. } },
  8333. directionalShadowMap: { value: [] },
  8334. directionalShadowMatrix: { value: [] },
  8335. spotLights: { value: [], properties: {
  8336. color: {},
  8337. position: {},
  8338. direction: {},
  8339. distance: {},
  8340. coneCos: {},
  8341. penumbraCos: {},
  8342. decay: {}
  8343. } },
  8344. spotLightShadows: { value: [], properties: {
  8345. shadowBias: {},
  8346. shadowNormalBias: {},
  8347. shadowRadius: {},
  8348. shadowMapSize: {}
  8349. } },
  8350. spotLightMap: { value: [] },
  8351. spotShadowMap: { value: [] },
  8352. spotLightMatrix: { value: [] },
  8353. pointLights: { value: [], properties: {
  8354. color: {},
  8355. position: {},
  8356. decay: {},
  8357. distance: {}
  8358. } },
  8359. pointLightShadows: { value: [], properties: {
  8360. shadowBias: {},
  8361. shadowNormalBias: {},
  8362. shadowRadius: {},
  8363. shadowMapSize: {},
  8364. shadowCameraNear: {},
  8365. shadowCameraFar: {}
  8366. } },
  8367. pointShadowMap: { value: [] },
  8368. pointShadowMatrix: { value: [] },
  8369. hemisphereLights: { value: [], properties: {
  8370. direction: {},
  8371. skyColor: {},
  8372. groundColor: {}
  8373. } },
  8374. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8375. rectAreaLights: { value: [], properties: {
  8376. color: {},
  8377. position: {},
  8378. width: {},
  8379. height: {}
  8380. } },
  8381. ltc_1: { value: null },
  8382. ltc_2: { value: null }
  8383. },
  8384. points: {
  8385. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8386. opacity: { value: 1.0 },
  8387. size: { value: 1.0 },
  8388. scale: { value: 1.0 },
  8389. map: { value: null },
  8390. alphaMap: { value: null },
  8391. alphaTest: { value: 0 },
  8392. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8393. },
  8394. sprite: {
  8395. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8396. opacity: { value: 1.0 },
  8397. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8398. rotation: { value: 0.0 },
  8399. map: { value: null },
  8400. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8401. alphaMap: { value: null },
  8402. alphaTest: { value: 0 }
  8403. }
  8404. };
  8405. const ShaderLib = {
  8406. basic: {
  8407. uniforms: /*@__PURE__*/ mergeUniforms( [
  8408. UniformsLib.common,
  8409. UniformsLib.specularmap,
  8410. UniformsLib.envmap,
  8411. UniformsLib.aomap,
  8412. UniformsLib.lightmap,
  8413. UniformsLib.fog
  8414. ] ),
  8415. vertexShader: ShaderChunk.meshbasic_vert,
  8416. fragmentShader: ShaderChunk.meshbasic_frag
  8417. },
  8418. lambert: {
  8419. uniforms: /*@__PURE__*/ mergeUniforms( [
  8420. UniformsLib.common,
  8421. UniformsLib.specularmap,
  8422. UniformsLib.envmap,
  8423. UniformsLib.aomap,
  8424. UniformsLib.lightmap,
  8425. UniformsLib.emissivemap,
  8426. UniformsLib.bumpmap,
  8427. UniformsLib.normalmap,
  8428. UniformsLib.displacementmap,
  8429. UniformsLib.fog,
  8430. UniformsLib.lights,
  8431. {
  8432. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8433. }
  8434. ] ),
  8435. vertexShader: ShaderChunk.meshlambert_vert,
  8436. fragmentShader: ShaderChunk.meshlambert_frag
  8437. },
  8438. phong: {
  8439. uniforms: /*@__PURE__*/ mergeUniforms( [
  8440. UniformsLib.common,
  8441. UniformsLib.specularmap,
  8442. UniformsLib.envmap,
  8443. UniformsLib.aomap,
  8444. UniformsLib.lightmap,
  8445. UniformsLib.emissivemap,
  8446. UniformsLib.bumpmap,
  8447. UniformsLib.normalmap,
  8448. UniformsLib.displacementmap,
  8449. UniformsLib.fog,
  8450. UniformsLib.lights,
  8451. {
  8452. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8453. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8454. shininess: { value: 30 }
  8455. }
  8456. ] ),
  8457. vertexShader: ShaderChunk.meshphong_vert,
  8458. fragmentShader: ShaderChunk.meshphong_frag
  8459. },
  8460. standard: {
  8461. uniforms: /*@__PURE__*/ mergeUniforms( [
  8462. UniformsLib.common,
  8463. UniformsLib.envmap,
  8464. UniformsLib.aomap,
  8465. UniformsLib.lightmap,
  8466. UniformsLib.emissivemap,
  8467. UniformsLib.bumpmap,
  8468. UniformsLib.normalmap,
  8469. UniformsLib.displacementmap,
  8470. UniformsLib.roughnessmap,
  8471. UniformsLib.metalnessmap,
  8472. UniformsLib.fog,
  8473. UniformsLib.lights,
  8474. {
  8475. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8476. roughness: { value: 1.0 },
  8477. metalness: { value: 0.0 },
  8478. envMapIntensity: { value: 1 } // temporary
  8479. }
  8480. ] ),
  8481. vertexShader: ShaderChunk.meshphysical_vert,
  8482. fragmentShader: ShaderChunk.meshphysical_frag
  8483. },
  8484. toon: {
  8485. uniforms: /*@__PURE__*/ mergeUniforms( [
  8486. UniformsLib.common,
  8487. UniformsLib.aomap,
  8488. UniformsLib.lightmap,
  8489. UniformsLib.emissivemap,
  8490. UniformsLib.bumpmap,
  8491. UniformsLib.normalmap,
  8492. UniformsLib.displacementmap,
  8493. UniformsLib.gradientmap,
  8494. UniformsLib.fog,
  8495. UniformsLib.lights,
  8496. {
  8497. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8498. }
  8499. ] ),
  8500. vertexShader: ShaderChunk.meshtoon_vert,
  8501. fragmentShader: ShaderChunk.meshtoon_frag
  8502. },
  8503. matcap: {
  8504. uniforms: /*@__PURE__*/ mergeUniforms( [
  8505. UniformsLib.common,
  8506. UniformsLib.bumpmap,
  8507. UniformsLib.normalmap,
  8508. UniformsLib.displacementmap,
  8509. UniformsLib.fog,
  8510. {
  8511. matcap: { value: null }
  8512. }
  8513. ] ),
  8514. vertexShader: ShaderChunk.meshmatcap_vert,
  8515. fragmentShader: ShaderChunk.meshmatcap_frag
  8516. },
  8517. points: {
  8518. uniforms: /*@__PURE__*/ mergeUniforms( [
  8519. UniformsLib.points,
  8520. UniformsLib.fog
  8521. ] ),
  8522. vertexShader: ShaderChunk.points_vert,
  8523. fragmentShader: ShaderChunk.points_frag
  8524. },
  8525. dashed: {
  8526. uniforms: /*@__PURE__*/ mergeUniforms( [
  8527. UniformsLib.common,
  8528. UniformsLib.fog,
  8529. {
  8530. scale: { value: 1 },
  8531. dashSize: { value: 1 },
  8532. totalSize: { value: 2 }
  8533. }
  8534. ] ),
  8535. vertexShader: ShaderChunk.linedashed_vert,
  8536. fragmentShader: ShaderChunk.linedashed_frag
  8537. },
  8538. depth: {
  8539. uniforms: /*@__PURE__*/ mergeUniforms( [
  8540. UniformsLib.common,
  8541. UniformsLib.displacementmap
  8542. ] ),
  8543. vertexShader: ShaderChunk.depth_vert,
  8544. fragmentShader: ShaderChunk.depth_frag
  8545. },
  8546. normal: {
  8547. uniforms: /*@__PURE__*/ mergeUniforms( [
  8548. UniformsLib.common,
  8549. UniformsLib.bumpmap,
  8550. UniformsLib.normalmap,
  8551. UniformsLib.displacementmap,
  8552. {
  8553. opacity: { value: 1.0 }
  8554. }
  8555. ] ),
  8556. vertexShader: ShaderChunk.meshnormal_vert,
  8557. fragmentShader: ShaderChunk.meshnormal_frag
  8558. },
  8559. sprite: {
  8560. uniforms: /*@__PURE__*/ mergeUniforms( [
  8561. UniformsLib.sprite,
  8562. UniformsLib.fog
  8563. ] ),
  8564. vertexShader: ShaderChunk.sprite_vert,
  8565. fragmentShader: ShaderChunk.sprite_frag
  8566. },
  8567. background: {
  8568. uniforms: {
  8569. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8570. t2D: { value: null },
  8571. backgroundIntensity: { value: 1 }
  8572. },
  8573. vertexShader: ShaderChunk.background_vert,
  8574. fragmentShader: ShaderChunk.background_frag
  8575. },
  8576. backgroundCube: {
  8577. uniforms: {
  8578. envMap: { value: null },
  8579. flipEnvMap: { value: - 1 },
  8580. backgroundBlurriness: { value: 0 },
  8581. backgroundIntensity: { value: 1 }
  8582. },
  8583. vertexShader: ShaderChunk.backgroundCube_vert,
  8584. fragmentShader: ShaderChunk.backgroundCube_frag
  8585. },
  8586. cube: {
  8587. uniforms: {
  8588. tCube: { value: null },
  8589. tFlip: { value: - 1 },
  8590. opacity: { value: 1.0 }
  8591. },
  8592. vertexShader: ShaderChunk.cube_vert,
  8593. fragmentShader: ShaderChunk.cube_frag
  8594. },
  8595. equirect: {
  8596. uniforms: {
  8597. tEquirect: { value: null },
  8598. },
  8599. vertexShader: ShaderChunk.equirect_vert,
  8600. fragmentShader: ShaderChunk.equirect_frag
  8601. },
  8602. distanceRGBA: {
  8603. uniforms: /*@__PURE__*/ mergeUniforms( [
  8604. UniformsLib.common,
  8605. UniformsLib.displacementmap,
  8606. {
  8607. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8608. nearDistance: { value: 1 },
  8609. farDistance: { value: 1000 }
  8610. }
  8611. ] ),
  8612. vertexShader: ShaderChunk.distanceRGBA_vert,
  8613. fragmentShader: ShaderChunk.distanceRGBA_frag
  8614. },
  8615. shadow: {
  8616. uniforms: /*@__PURE__*/ mergeUniforms( [
  8617. UniformsLib.lights,
  8618. UniformsLib.fog,
  8619. {
  8620. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8621. opacity: { value: 1.0 }
  8622. },
  8623. ] ),
  8624. vertexShader: ShaderChunk.shadow_vert,
  8625. fragmentShader: ShaderChunk.shadow_frag
  8626. }
  8627. };
  8628. ShaderLib.physical = {
  8629. uniforms: /*@__PURE__*/ mergeUniforms( [
  8630. ShaderLib.standard.uniforms,
  8631. {
  8632. clearcoat: { value: 0 },
  8633. clearcoatMap: { value: null },
  8634. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8635. clearcoatNormalMap: { value: null },
  8636. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8637. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8638. clearcoatRoughness: { value: 0 },
  8639. clearcoatRoughnessMap: { value: null },
  8640. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8641. iridescence: { value: 0 },
  8642. iridescenceMap: { value: null },
  8643. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8644. iridescenceIOR: { value: 1.3 },
  8645. iridescenceThicknessMinimum: { value: 100 },
  8646. iridescenceThicknessMaximum: { value: 400 },
  8647. iridescenceThicknessMap: { value: null },
  8648. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8649. sheen: { value: 0 },
  8650. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8651. sheenColorMap: { value: null },
  8652. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8653. sheenRoughness: { value: 1 },
  8654. sheenRoughnessMap: { value: null },
  8655. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8656. transmission: { value: 0 },
  8657. transmissionMap: { value: null },
  8658. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8659. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8660. transmissionSamplerMap: { value: null },
  8661. thickness: { value: 0 },
  8662. thicknessMap: { value: null },
  8663. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8664. attenuationDistance: { value: 0 },
  8665. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8666. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8667. specularColorMap: { value: null },
  8668. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8669. specularIntensity: { value: 1 },
  8670. specularIntensityMap: { value: null },
  8671. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8672. }
  8673. ] ),
  8674. vertexShader: ShaderChunk.meshphysical_vert,
  8675. fragmentShader: ShaderChunk.meshphysical_frag
  8676. };
  8677. const _rgb = { r: 0, b: 0, g: 0 };
  8678. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8679. const clearColor = new Color( 0x000000 );
  8680. let clearAlpha = alpha === true ? 0 : 1;
  8681. let planeMesh;
  8682. let boxMesh;
  8683. let currentBackground = null;
  8684. let currentBackgroundVersion = 0;
  8685. let currentTonemapping = null;
  8686. function render( renderList, scene ) {
  8687. let forceClear = false;
  8688. let background = scene.isScene === true ? scene.background : null;
  8689. if ( background && background.isTexture ) {
  8690. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8691. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8692. }
  8693. if ( background === null ) {
  8694. setClear( clearColor, clearAlpha );
  8695. } else if ( background && background.isColor ) {
  8696. setClear( background, 1 );
  8697. forceClear = true;
  8698. }
  8699. const xr = renderer.xr;
  8700. const environmentBlendMode = xr.getEnvironmentBlendMode();
  8701. switch ( environmentBlendMode ) {
  8702. case 'opaque':
  8703. forceClear = true;
  8704. break;
  8705. case 'additive':
  8706. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8707. forceClear = true;
  8708. break;
  8709. case 'alpha-blend':
  8710. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8711. forceClear = true;
  8712. break;
  8713. }
  8714. if ( renderer.autoClear || forceClear ) {
  8715. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8716. }
  8717. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8718. if ( boxMesh === undefined ) {
  8719. boxMesh = new Mesh(
  8720. new BoxGeometry( 1, 1, 1 ),
  8721. new ShaderMaterial( {
  8722. name: 'BackgroundCubeMaterial',
  8723. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8724. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8725. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8726. side: BackSide,
  8727. depthTest: false,
  8728. depthWrite: false,
  8729. fog: false
  8730. } )
  8731. );
  8732. boxMesh.geometry.deleteAttribute( 'normal' );
  8733. boxMesh.geometry.deleteAttribute( 'uv' );
  8734. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8735. this.matrixWorld.copyPosition( camera.matrixWorld );
  8736. };
  8737. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8738. Object.defineProperty( boxMesh.material, 'envMap', {
  8739. get: function () {
  8740. return this.uniforms.envMap.value;
  8741. }
  8742. } );
  8743. objects.update( boxMesh );
  8744. }
  8745. boxMesh.material.uniforms.envMap.value = background;
  8746. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8747. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8748. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8749. boxMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;
  8750. if ( currentBackground !== background ||
  8751. currentBackgroundVersion !== background.version ||
  8752. currentTonemapping !== renderer.toneMapping ) {
  8753. boxMesh.material.needsUpdate = true;
  8754. currentBackground = background;
  8755. currentBackgroundVersion = background.version;
  8756. currentTonemapping = renderer.toneMapping;
  8757. }
  8758. boxMesh.layers.enableAll();
  8759. // push to the pre-sorted opaque render list
  8760. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8761. } else if ( background && background.isTexture ) {
  8762. if ( planeMesh === undefined ) {
  8763. planeMesh = new Mesh(
  8764. new PlaneGeometry( 2, 2 ),
  8765. new ShaderMaterial( {
  8766. name: 'BackgroundMaterial',
  8767. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8768. vertexShader: ShaderLib.background.vertexShader,
  8769. fragmentShader: ShaderLib.background.fragmentShader,
  8770. side: FrontSide,
  8771. depthTest: false,
  8772. depthWrite: false,
  8773. fog: false
  8774. } )
  8775. );
  8776. planeMesh.geometry.deleteAttribute( 'normal' );
  8777. // add "map" material property so the renderer can evaluate it like for built-in materials
  8778. Object.defineProperty( planeMesh.material, 'map', {
  8779. get: function () {
  8780. return this.uniforms.t2D.value;
  8781. }
  8782. } );
  8783. objects.update( planeMesh );
  8784. }
  8785. planeMesh.material.uniforms.t2D.value = background;
  8786. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8787. planeMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;
  8788. if ( background.matrixAutoUpdate === true ) {
  8789. background.updateMatrix();
  8790. }
  8791. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8792. if ( currentBackground !== background ||
  8793. currentBackgroundVersion !== background.version ||
  8794. currentTonemapping !== renderer.toneMapping ) {
  8795. planeMesh.material.needsUpdate = true;
  8796. currentBackground = background;
  8797. currentBackgroundVersion = background.version;
  8798. currentTonemapping = renderer.toneMapping;
  8799. }
  8800. planeMesh.layers.enableAll();
  8801. // push to the pre-sorted opaque render list
  8802. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8803. }
  8804. }
  8805. function setClear( color, alpha ) {
  8806. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8807. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8808. }
  8809. return {
  8810. getClearColor: function () {
  8811. return clearColor;
  8812. },
  8813. setClearColor: function ( color, alpha = 1 ) {
  8814. clearColor.set( color );
  8815. clearAlpha = alpha;
  8816. setClear( clearColor, clearAlpha );
  8817. },
  8818. getClearAlpha: function () {
  8819. return clearAlpha;
  8820. },
  8821. setClearAlpha: function ( alpha ) {
  8822. clearAlpha = alpha;
  8823. setClear( clearColor, clearAlpha );
  8824. },
  8825. render: render
  8826. };
  8827. }
  8828. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8829. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8830. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8831. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8832. const bindingStates = {};
  8833. const defaultState = createBindingState( null );
  8834. let currentState = defaultState;
  8835. let forceUpdate = false;
  8836. function setup( object, material, program, geometry, index ) {
  8837. let updateBuffers = false;
  8838. if ( vaoAvailable ) {
  8839. const state = getBindingState( geometry, program, material );
  8840. if ( currentState !== state ) {
  8841. currentState = state;
  8842. bindVertexArrayObject( currentState.object );
  8843. }
  8844. updateBuffers = needsUpdate( object, geometry, program, index );
  8845. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8846. } else {
  8847. const wireframe = ( material.wireframe === true );
  8848. if ( currentState.geometry !== geometry.id ||
  8849. currentState.program !== program.id ||
  8850. currentState.wireframe !== wireframe ) {
  8851. currentState.geometry = geometry.id;
  8852. currentState.program = program.id;
  8853. currentState.wireframe = wireframe;
  8854. updateBuffers = true;
  8855. }
  8856. }
  8857. if ( index !== null ) {
  8858. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  8859. }
  8860. if ( updateBuffers || forceUpdate ) {
  8861. forceUpdate = false;
  8862. setupVertexAttributes( object, material, program, geometry );
  8863. if ( index !== null ) {
  8864. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  8865. }
  8866. }
  8867. }
  8868. function createVertexArrayObject() {
  8869. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8870. return extension.createVertexArrayOES();
  8871. }
  8872. function bindVertexArrayObject( vao ) {
  8873. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8874. return extension.bindVertexArrayOES( vao );
  8875. }
  8876. function deleteVertexArrayObject( vao ) {
  8877. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8878. return extension.deleteVertexArrayOES( vao );
  8879. }
  8880. function getBindingState( geometry, program, material ) {
  8881. const wireframe = ( material.wireframe === true );
  8882. let programMap = bindingStates[ geometry.id ];
  8883. if ( programMap === undefined ) {
  8884. programMap = {};
  8885. bindingStates[ geometry.id ] = programMap;
  8886. }
  8887. let stateMap = programMap[ program.id ];
  8888. if ( stateMap === undefined ) {
  8889. stateMap = {};
  8890. programMap[ program.id ] = stateMap;
  8891. }
  8892. let state = stateMap[ wireframe ];
  8893. if ( state === undefined ) {
  8894. state = createBindingState( createVertexArrayObject() );
  8895. stateMap[ wireframe ] = state;
  8896. }
  8897. return state;
  8898. }
  8899. function createBindingState( vao ) {
  8900. const newAttributes = [];
  8901. const enabledAttributes = [];
  8902. const attributeDivisors = [];
  8903. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8904. newAttributes[ i ] = 0;
  8905. enabledAttributes[ i ] = 0;
  8906. attributeDivisors[ i ] = 0;
  8907. }
  8908. return {
  8909. // for backward compatibility on non-VAO support browser
  8910. geometry: null,
  8911. program: null,
  8912. wireframe: false,
  8913. newAttributes: newAttributes,
  8914. enabledAttributes: enabledAttributes,
  8915. attributeDivisors: attributeDivisors,
  8916. object: vao,
  8917. attributes: {},
  8918. index: null
  8919. };
  8920. }
  8921. function needsUpdate( object, geometry, program, index ) {
  8922. const cachedAttributes = currentState.attributes;
  8923. const geometryAttributes = geometry.attributes;
  8924. let attributesNum = 0;
  8925. const programAttributes = program.getAttributes();
  8926. for ( const name in programAttributes ) {
  8927. const programAttribute = programAttributes[ name ];
  8928. if ( programAttribute.location >= 0 ) {
  8929. const cachedAttribute = cachedAttributes[ name ];
  8930. let geometryAttribute = geometryAttributes[ name ];
  8931. if ( geometryAttribute === undefined ) {
  8932. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8933. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8934. }
  8935. if ( cachedAttribute === undefined ) return true;
  8936. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8937. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8938. attributesNum ++;
  8939. }
  8940. }
  8941. if ( currentState.attributesNum !== attributesNum ) return true;
  8942. if ( currentState.index !== index ) return true;
  8943. return false;
  8944. }
  8945. function saveCache( object, geometry, program, index ) {
  8946. const cache = {};
  8947. const attributes = geometry.attributes;
  8948. let attributesNum = 0;
  8949. const programAttributes = program.getAttributes();
  8950. for ( const name in programAttributes ) {
  8951. const programAttribute = programAttributes[ name ];
  8952. if ( programAttribute.location >= 0 ) {
  8953. let attribute = attributes[ name ];
  8954. if ( attribute === undefined ) {
  8955. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8956. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8957. }
  8958. const data = {};
  8959. data.attribute = attribute;
  8960. if ( attribute && attribute.data ) {
  8961. data.data = attribute.data;
  8962. }
  8963. cache[ name ] = data;
  8964. attributesNum ++;
  8965. }
  8966. }
  8967. currentState.attributes = cache;
  8968. currentState.attributesNum = attributesNum;
  8969. currentState.index = index;
  8970. }
  8971. function initAttributes() {
  8972. const newAttributes = currentState.newAttributes;
  8973. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8974. newAttributes[ i ] = 0;
  8975. }
  8976. }
  8977. function enableAttribute( attribute ) {
  8978. enableAttributeAndDivisor( attribute, 0 );
  8979. }
  8980. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8981. const newAttributes = currentState.newAttributes;
  8982. const enabledAttributes = currentState.enabledAttributes;
  8983. const attributeDivisors = currentState.attributeDivisors;
  8984. newAttributes[ attribute ] = 1;
  8985. if ( enabledAttributes[ attribute ] === 0 ) {
  8986. gl.enableVertexAttribArray( attribute );
  8987. enabledAttributes[ attribute ] = 1;
  8988. }
  8989. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8990. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8991. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8992. attributeDivisors[ attribute ] = meshPerAttribute;
  8993. }
  8994. }
  8995. function disableUnusedAttributes() {
  8996. const newAttributes = currentState.newAttributes;
  8997. const enabledAttributes = currentState.enabledAttributes;
  8998. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8999. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9000. gl.disableVertexAttribArray( i );
  9001. enabledAttributes[ i ] = 0;
  9002. }
  9003. }
  9004. }
  9005. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  9006. if ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) {
  9007. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9008. } else {
  9009. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9010. }
  9011. }
  9012. function setupVertexAttributes( object, material, program, geometry ) {
  9013. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9014. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9015. }
  9016. initAttributes();
  9017. const geometryAttributes = geometry.attributes;
  9018. const programAttributes = program.getAttributes();
  9019. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9020. for ( const name in programAttributes ) {
  9021. const programAttribute = programAttributes[ name ];
  9022. if ( programAttribute.location >= 0 ) {
  9023. let geometryAttribute = geometryAttributes[ name ];
  9024. if ( geometryAttribute === undefined ) {
  9025. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9026. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9027. }
  9028. if ( geometryAttribute !== undefined ) {
  9029. const normalized = geometryAttribute.normalized;
  9030. const size = geometryAttribute.itemSize;
  9031. const attribute = attributes.get( geometryAttribute );
  9032. // TODO Attribute may not be available on context restore
  9033. if ( attribute === undefined ) continue;
  9034. const buffer = attribute.buffer;
  9035. const type = attribute.type;
  9036. const bytesPerElement = attribute.bytesPerElement;
  9037. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9038. const data = geometryAttribute.data;
  9039. const stride = data.stride;
  9040. const offset = geometryAttribute.offset;
  9041. if ( data.isInstancedInterleavedBuffer ) {
  9042. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9043. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9044. }
  9045. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9046. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9047. }
  9048. } else {
  9049. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9050. enableAttribute( programAttribute.location + i );
  9051. }
  9052. }
  9053. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9054. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9055. vertexAttribPointer(
  9056. programAttribute.location + i,
  9057. size / programAttribute.locationSize,
  9058. type,
  9059. normalized,
  9060. stride * bytesPerElement,
  9061. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  9062. );
  9063. }
  9064. } else {
  9065. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9066. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9067. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9068. }
  9069. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9070. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9071. }
  9072. } else {
  9073. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9074. enableAttribute( programAttribute.location + i );
  9075. }
  9076. }
  9077. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9078. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9079. vertexAttribPointer(
  9080. programAttribute.location + i,
  9081. size / programAttribute.locationSize,
  9082. type,
  9083. normalized,
  9084. size * bytesPerElement,
  9085. ( size / programAttribute.locationSize ) * i * bytesPerElement
  9086. );
  9087. }
  9088. }
  9089. } else if ( materialDefaultAttributeValues !== undefined ) {
  9090. const value = materialDefaultAttributeValues[ name ];
  9091. if ( value !== undefined ) {
  9092. switch ( value.length ) {
  9093. case 2:
  9094. gl.vertexAttrib2fv( programAttribute.location, value );
  9095. break;
  9096. case 3:
  9097. gl.vertexAttrib3fv( programAttribute.location, value );
  9098. break;
  9099. case 4:
  9100. gl.vertexAttrib4fv( programAttribute.location, value );
  9101. break;
  9102. default:
  9103. gl.vertexAttrib1fv( programAttribute.location, value );
  9104. }
  9105. }
  9106. }
  9107. }
  9108. }
  9109. disableUnusedAttributes();
  9110. }
  9111. function dispose() {
  9112. reset();
  9113. for ( const geometryId in bindingStates ) {
  9114. const programMap = bindingStates[ geometryId ];
  9115. for ( const programId in programMap ) {
  9116. const stateMap = programMap[ programId ];
  9117. for ( const wireframe in stateMap ) {
  9118. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9119. delete stateMap[ wireframe ];
  9120. }
  9121. delete programMap[ programId ];
  9122. }
  9123. delete bindingStates[ geometryId ];
  9124. }
  9125. }
  9126. function releaseStatesOfGeometry( geometry ) {
  9127. if ( bindingStates[ geometry.id ] === undefined ) return;
  9128. const programMap = bindingStates[ geometry.id ];
  9129. for ( const programId in programMap ) {
  9130. const stateMap = programMap[ programId ];
  9131. for ( const wireframe in stateMap ) {
  9132. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9133. delete stateMap[ wireframe ];
  9134. }
  9135. delete programMap[ programId ];
  9136. }
  9137. delete bindingStates[ geometry.id ];
  9138. }
  9139. function releaseStatesOfProgram( program ) {
  9140. for ( const geometryId in bindingStates ) {
  9141. const programMap = bindingStates[ geometryId ];
  9142. if ( programMap[ program.id ] === undefined ) continue;
  9143. const stateMap = programMap[ program.id ];
  9144. for ( const wireframe in stateMap ) {
  9145. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9146. delete stateMap[ wireframe ];
  9147. }
  9148. delete programMap[ program.id ];
  9149. }
  9150. }
  9151. function reset() {
  9152. resetDefaultState();
  9153. forceUpdate = true;
  9154. if ( currentState === defaultState ) return;
  9155. currentState = defaultState;
  9156. bindVertexArrayObject( currentState.object );
  9157. }
  9158. // for backward-compatibility
  9159. function resetDefaultState() {
  9160. defaultState.geometry = null;
  9161. defaultState.program = null;
  9162. defaultState.wireframe = false;
  9163. }
  9164. return {
  9165. setup: setup,
  9166. reset: reset,
  9167. resetDefaultState: resetDefaultState,
  9168. dispose: dispose,
  9169. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9170. releaseStatesOfProgram: releaseStatesOfProgram,
  9171. initAttributes: initAttributes,
  9172. enableAttribute: enableAttribute,
  9173. disableUnusedAttributes: disableUnusedAttributes
  9174. };
  9175. }
  9176. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9177. const isWebGL2 = capabilities.isWebGL2;
  9178. let mode;
  9179. function setMode( value ) {
  9180. mode = value;
  9181. }
  9182. function render( start, count ) {
  9183. gl.drawArrays( mode, start, count );
  9184. info.update( count, mode, 1 );
  9185. }
  9186. function renderInstances( start, count, primcount ) {
  9187. if ( primcount === 0 ) return;
  9188. let extension, methodName;
  9189. if ( isWebGL2 ) {
  9190. extension = gl;
  9191. methodName = 'drawArraysInstanced';
  9192. } else {
  9193. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9194. methodName = 'drawArraysInstancedANGLE';
  9195. if ( extension === null ) {
  9196. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9197. return;
  9198. }
  9199. }
  9200. extension[ methodName ]( mode, start, count, primcount );
  9201. info.update( count, mode, primcount );
  9202. }
  9203. //
  9204. this.setMode = setMode;
  9205. this.render = render;
  9206. this.renderInstances = renderInstances;
  9207. }
  9208. function WebGLCapabilities( gl, extensions, parameters ) {
  9209. let maxAnisotropy;
  9210. function getMaxAnisotropy() {
  9211. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9212. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9213. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9214. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9215. } else {
  9216. maxAnisotropy = 0;
  9217. }
  9218. return maxAnisotropy;
  9219. }
  9220. function getMaxPrecision( precision ) {
  9221. if ( precision === 'highp' ) {
  9222. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9223. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9224. return 'highp';
  9225. }
  9226. precision = 'mediump';
  9227. }
  9228. if ( precision === 'mediump' ) {
  9229. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9230. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9231. return 'mediump';
  9232. }
  9233. }
  9234. return 'lowp';
  9235. }
  9236. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9237. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9238. const maxPrecision = getMaxPrecision( precision );
  9239. if ( maxPrecision !== precision ) {
  9240. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9241. precision = maxPrecision;
  9242. }
  9243. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9244. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9245. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9246. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9247. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9248. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9249. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9250. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9251. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9252. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9253. const vertexTextures = maxVertexTextures > 0;
  9254. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9255. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9256. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  9257. return {
  9258. isWebGL2: isWebGL2,
  9259. drawBuffers: drawBuffers,
  9260. getMaxAnisotropy: getMaxAnisotropy,
  9261. getMaxPrecision: getMaxPrecision,
  9262. precision: precision,
  9263. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9264. maxTextures: maxTextures,
  9265. maxVertexTextures: maxVertexTextures,
  9266. maxTextureSize: maxTextureSize,
  9267. maxCubemapSize: maxCubemapSize,
  9268. maxAttributes: maxAttributes,
  9269. maxVertexUniforms: maxVertexUniforms,
  9270. maxVaryings: maxVaryings,
  9271. maxFragmentUniforms: maxFragmentUniforms,
  9272. vertexTextures: vertexTextures,
  9273. floatFragmentTextures: floatFragmentTextures,
  9274. floatVertexTextures: floatVertexTextures,
  9275. maxSamples: maxSamples
  9276. };
  9277. }
  9278. function WebGLClipping( properties ) {
  9279. const scope = this;
  9280. let globalState = null,
  9281. numGlobalPlanes = 0,
  9282. localClippingEnabled = false,
  9283. renderingShadows = false;
  9284. const plane = new Plane(),
  9285. viewNormalMatrix = new Matrix3(),
  9286. uniform = { value: null, needsUpdate: false };
  9287. this.uniform = uniform;
  9288. this.numPlanes = 0;
  9289. this.numIntersection = 0;
  9290. this.init = function ( planes, enableLocalClipping ) {
  9291. const enabled =
  9292. planes.length !== 0 ||
  9293. enableLocalClipping ||
  9294. // enable state of previous frame - the clipping code has to
  9295. // run another frame in order to reset the state:
  9296. numGlobalPlanes !== 0 ||
  9297. localClippingEnabled;
  9298. localClippingEnabled = enableLocalClipping;
  9299. numGlobalPlanes = planes.length;
  9300. return enabled;
  9301. };
  9302. this.beginShadows = function () {
  9303. renderingShadows = true;
  9304. projectPlanes( null );
  9305. };
  9306. this.endShadows = function () {
  9307. renderingShadows = false;
  9308. };
  9309. this.setGlobalState = function ( planes, camera ) {
  9310. globalState = projectPlanes( planes, camera, 0 );
  9311. };
  9312. this.setState = function ( material, camera, useCache ) {
  9313. const planes = material.clippingPlanes,
  9314. clipIntersection = material.clipIntersection,
  9315. clipShadows = material.clipShadows;
  9316. const materialProperties = properties.get( material );
  9317. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9318. // there's no local clipping
  9319. if ( renderingShadows ) {
  9320. // there's no global clipping
  9321. projectPlanes( null );
  9322. } else {
  9323. resetGlobalState();
  9324. }
  9325. } else {
  9326. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9327. lGlobal = nGlobal * 4;
  9328. let dstArray = materialProperties.clippingState || null;
  9329. uniform.value = dstArray; // ensure unique state
  9330. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9331. for ( let i = 0; i !== lGlobal; ++ i ) {
  9332. dstArray[ i ] = globalState[ i ];
  9333. }
  9334. materialProperties.clippingState = dstArray;
  9335. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9336. this.numPlanes += nGlobal;
  9337. }
  9338. };
  9339. function resetGlobalState() {
  9340. if ( uniform.value !== globalState ) {
  9341. uniform.value = globalState;
  9342. uniform.needsUpdate = numGlobalPlanes > 0;
  9343. }
  9344. scope.numPlanes = numGlobalPlanes;
  9345. scope.numIntersection = 0;
  9346. }
  9347. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9348. const nPlanes = planes !== null ? planes.length : 0;
  9349. let dstArray = null;
  9350. if ( nPlanes !== 0 ) {
  9351. dstArray = uniform.value;
  9352. if ( skipTransform !== true || dstArray === null ) {
  9353. const flatSize = dstOffset + nPlanes * 4,
  9354. viewMatrix = camera.matrixWorldInverse;
  9355. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9356. if ( dstArray === null || dstArray.length < flatSize ) {
  9357. dstArray = new Float32Array( flatSize );
  9358. }
  9359. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9360. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9361. plane.normal.toArray( dstArray, i4 );
  9362. dstArray[ i4 + 3 ] = plane.constant;
  9363. }
  9364. }
  9365. uniform.value = dstArray;
  9366. uniform.needsUpdate = true;
  9367. }
  9368. scope.numPlanes = nPlanes;
  9369. scope.numIntersection = 0;
  9370. return dstArray;
  9371. }
  9372. }
  9373. function WebGLCubeMaps( renderer ) {
  9374. let cubemaps = new WeakMap();
  9375. function mapTextureMapping( texture, mapping ) {
  9376. if ( mapping === EquirectangularReflectionMapping ) {
  9377. texture.mapping = CubeReflectionMapping;
  9378. } else if ( mapping === EquirectangularRefractionMapping ) {
  9379. texture.mapping = CubeRefractionMapping;
  9380. }
  9381. return texture;
  9382. }
  9383. function get( texture ) {
  9384. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9385. const mapping = texture.mapping;
  9386. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9387. if ( cubemaps.has( texture ) ) {
  9388. const cubemap = cubemaps.get( texture ).texture;
  9389. return mapTextureMapping( cubemap, texture.mapping );
  9390. } else {
  9391. const image = texture.image;
  9392. if ( image && image.height > 0 ) {
  9393. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9394. renderTarget.fromEquirectangularTexture( renderer, texture );
  9395. cubemaps.set( texture, renderTarget );
  9396. texture.addEventListener( 'dispose', onTextureDispose );
  9397. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9398. } else {
  9399. // image not yet ready. try the conversion next frame
  9400. return null;
  9401. }
  9402. }
  9403. }
  9404. }
  9405. return texture;
  9406. }
  9407. function onTextureDispose( event ) {
  9408. const texture = event.target;
  9409. texture.removeEventListener( 'dispose', onTextureDispose );
  9410. const cubemap = cubemaps.get( texture );
  9411. if ( cubemap !== undefined ) {
  9412. cubemaps.delete( texture );
  9413. cubemap.dispose();
  9414. }
  9415. }
  9416. function dispose() {
  9417. cubemaps = new WeakMap();
  9418. }
  9419. return {
  9420. get: get,
  9421. dispose: dispose
  9422. };
  9423. }
  9424. class OrthographicCamera extends Camera {
  9425. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9426. super();
  9427. this.isOrthographicCamera = true;
  9428. this.type = 'OrthographicCamera';
  9429. this.zoom = 1;
  9430. this.view = null;
  9431. this.left = left;
  9432. this.right = right;
  9433. this.top = top;
  9434. this.bottom = bottom;
  9435. this.near = near;
  9436. this.far = far;
  9437. this.updateProjectionMatrix();
  9438. }
  9439. copy( source, recursive ) {
  9440. super.copy( source, recursive );
  9441. this.left = source.left;
  9442. this.right = source.right;
  9443. this.top = source.top;
  9444. this.bottom = source.bottom;
  9445. this.near = source.near;
  9446. this.far = source.far;
  9447. this.zoom = source.zoom;
  9448. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9449. return this;
  9450. }
  9451. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9452. if ( this.view === null ) {
  9453. this.view = {
  9454. enabled: true,
  9455. fullWidth: 1,
  9456. fullHeight: 1,
  9457. offsetX: 0,
  9458. offsetY: 0,
  9459. width: 1,
  9460. height: 1
  9461. };
  9462. }
  9463. this.view.enabled = true;
  9464. this.view.fullWidth = fullWidth;
  9465. this.view.fullHeight = fullHeight;
  9466. this.view.offsetX = x;
  9467. this.view.offsetY = y;
  9468. this.view.width = width;
  9469. this.view.height = height;
  9470. this.updateProjectionMatrix();
  9471. }
  9472. clearViewOffset() {
  9473. if ( this.view !== null ) {
  9474. this.view.enabled = false;
  9475. }
  9476. this.updateProjectionMatrix();
  9477. }
  9478. updateProjectionMatrix() {
  9479. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9480. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9481. const cx = ( this.right + this.left ) / 2;
  9482. const cy = ( this.top + this.bottom ) / 2;
  9483. let left = cx - dx;
  9484. let right = cx + dx;
  9485. let top = cy + dy;
  9486. let bottom = cy - dy;
  9487. if ( this.view !== null && this.view.enabled ) {
  9488. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9489. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9490. left += scaleW * this.view.offsetX;
  9491. right = left + scaleW * this.view.width;
  9492. top -= scaleH * this.view.offsetY;
  9493. bottom = top - scaleH * this.view.height;
  9494. }
  9495. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9496. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9497. }
  9498. toJSON( meta ) {
  9499. const data = super.toJSON( meta );
  9500. data.object.zoom = this.zoom;
  9501. data.object.left = this.left;
  9502. data.object.right = this.right;
  9503. data.object.top = this.top;
  9504. data.object.bottom = this.bottom;
  9505. data.object.near = this.near;
  9506. data.object.far = this.far;
  9507. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9508. return data;
  9509. }
  9510. }
  9511. const LOD_MIN = 4;
  9512. // The standard deviations (radians) associated with the extra mips. These are
  9513. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9514. // geometric shadowing function. These sigma values squared must match the
  9515. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9516. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9517. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9518. // samples and exit early, but not recompile the shader.
  9519. const MAX_SAMPLES = 20;
  9520. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9521. const _clearColor = /*@__PURE__*/ new Color();
  9522. let _oldTarget = null;
  9523. // Golden Ratio
  9524. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9525. const INV_PHI = 1 / PHI;
  9526. // Vertices of a dodecahedron (except the opposites, which represent the
  9527. // same axis), used as axis directions evenly spread on a sphere.
  9528. const _axisDirections = [
  9529. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9530. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9531. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9532. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9533. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9534. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9535. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9536. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9537. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9538. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9539. /**
  9540. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9541. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9542. * blur to be quickly accessed based on material roughness. It is packed into a
  9543. * special CubeUV format that allows us to perform custom interpolation so that
  9544. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9545. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9546. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9547. * higher roughness levels. In this way we maintain resolution to smoothly
  9548. * interpolate diffuse lighting while limiting sampling computation.
  9549. *
  9550. * Paper: Fast, Accurate Image-Based Lighting
  9551. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9552. */
  9553. class PMREMGenerator {
  9554. constructor( renderer ) {
  9555. this._renderer = renderer;
  9556. this._pingPongRenderTarget = null;
  9557. this._lodMax = 0;
  9558. this._cubeSize = 0;
  9559. this._lodPlanes = [];
  9560. this._sizeLods = [];
  9561. this._sigmas = [];
  9562. this._blurMaterial = null;
  9563. this._cubemapMaterial = null;
  9564. this._equirectMaterial = null;
  9565. this._compileMaterial( this._blurMaterial );
  9566. }
  9567. /**
  9568. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9569. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9570. * in radians to be applied to the scene before PMREM generation. Optional near
  9571. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9572. * is placed at the origin).
  9573. */
  9574. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9575. _oldTarget = this._renderer.getRenderTarget();
  9576. this._setSize( 256 );
  9577. const cubeUVRenderTarget = this._allocateTargets();
  9578. cubeUVRenderTarget.depthBuffer = true;
  9579. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9580. if ( sigma > 0 ) {
  9581. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9582. }
  9583. this._applyPMREM( cubeUVRenderTarget );
  9584. this._cleanup( cubeUVRenderTarget );
  9585. return cubeUVRenderTarget;
  9586. }
  9587. /**
  9588. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9589. * or HDR. The ideal input image size is 1k (1024 x 512),
  9590. * as this matches best with the 256 x 256 cubemap output.
  9591. */
  9592. fromEquirectangular( equirectangular, renderTarget = null ) {
  9593. return this._fromTexture( equirectangular, renderTarget );
  9594. }
  9595. /**
  9596. * Generates a PMREM from an cubemap texture, which can be either LDR
  9597. * or HDR. The ideal input cube size is 256 x 256,
  9598. * as this matches best with the 256 x 256 cubemap output.
  9599. */
  9600. fromCubemap( cubemap, renderTarget = null ) {
  9601. return this._fromTexture( cubemap, renderTarget );
  9602. }
  9603. /**
  9604. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9605. * your texture's network fetch for increased concurrency.
  9606. */
  9607. compileCubemapShader() {
  9608. if ( this._cubemapMaterial === null ) {
  9609. this._cubemapMaterial = _getCubemapMaterial();
  9610. this._compileMaterial( this._cubemapMaterial );
  9611. }
  9612. }
  9613. /**
  9614. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9615. * your texture's network fetch for increased concurrency.
  9616. */
  9617. compileEquirectangularShader() {
  9618. if ( this._equirectMaterial === null ) {
  9619. this._equirectMaterial = _getEquirectMaterial();
  9620. this._compileMaterial( this._equirectMaterial );
  9621. }
  9622. }
  9623. /**
  9624. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9625. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9626. * one of them will cause any others to also become unusable.
  9627. */
  9628. dispose() {
  9629. this._dispose();
  9630. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9631. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9632. }
  9633. // private interface
  9634. _setSize( cubeSize ) {
  9635. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9636. this._cubeSize = Math.pow( 2, this._lodMax );
  9637. }
  9638. _dispose() {
  9639. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9640. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9641. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9642. this._lodPlanes[ i ].dispose();
  9643. }
  9644. }
  9645. _cleanup( outputTarget ) {
  9646. this._renderer.setRenderTarget( _oldTarget );
  9647. outputTarget.scissorTest = false;
  9648. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9649. }
  9650. _fromTexture( texture, renderTarget ) {
  9651. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9652. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9653. } else { // Equirectangular
  9654. this._setSize( texture.image.width / 4 );
  9655. }
  9656. _oldTarget = this._renderer.getRenderTarget();
  9657. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9658. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9659. this._applyPMREM( cubeUVRenderTarget );
  9660. this._cleanup( cubeUVRenderTarget );
  9661. return cubeUVRenderTarget;
  9662. }
  9663. _allocateTargets() {
  9664. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9665. const height = 4 * this._cubeSize;
  9666. const params = {
  9667. magFilter: LinearFilter,
  9668. minFilter: LinearFilter,
  9669. generateMipmaps: false,
  9670. type: HalfFloatType,
  9671. format: RGBAFormat,
  9672. colorSpace: LinearSRGBColorSpace,
  9673. depthBuffer: false
  9674. };
  9675. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9676. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9677. if ( this._pingPongRenderTarget !== null ) {
  9678. this._dispose();
  9679. }
  9680. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9681. const { _lodMax } = this;
  9682. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9683. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9684. }
  9685. return cubeUVRenderTarget;
  9686. }
  9687. _compileMaterial( material ) {
  9688. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9689. this._renderer.compile( tmpMesh, _flatCamera );
  9690. }
  9691. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9692. const fov = 90;
  9693. const aspect = 1;
  9694. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9695. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9696. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9697. const renderer = this._renderer;
  9698. const originalAutoClear = renderer.autoClear;
  9699. const toneMapping = renderer.toneMapping;
  9700. renderer.getClearColor( _clearColor );
  9701. renderer.toneMapping = NoToneMapping;
  9702. renderer.autoClear = false;
  9703. const backgroundMaterial = new MeshBasicMaterial( {
  9704. name: 'PMREM.Background',
  9705. side: BackSide,
  9706. depthWrite: false,
  9707. depthTest: false,
  9708. } );
  9709. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9710. let useSolidColor = false;
  9711. const background = scene.background;
  9712. if ( background ) {
  9713. if ( background.isColor ) {
  9714. backgroundMaterial.color.copy( background );
  9715. scene.background = null;
  9716. useSolidColor = true;
  9717. }
  9718. } else {
  9719. backgroundMaterial.color.copy( _clearColor );
  9720. useSolidColor = true;
  9721. }
  9722. for ( let i = 0; i < 6; i ++ ) {
  9723. const col = i % 3;
  9724. if ( col === 0 ) {
  9725. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9726. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9727. } else if ( col === 1 ) {
  9728. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9729. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9730. } else {
  9731. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9732. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9733. }
  9734. const size = this._cubeSize;
  9735. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9736. renderer.setRenderTarget( cubeUVRenderTarget );
  9737. if ( useSolidColor ) {
  9738. renderer.render( backgroundBox, cubeCamera );
  9739. }
  9740. renderer.render( scene, cubeCamera );
  9741. }
  9742. backgroundBox.geometry.dispose();
  9743. backgroundBox.material.dispose();
  9744. renderer.toneMapping = toneMapping;
  9745. renderer.autoClear = originalAutoClear;
  9746. scene.background = background;
  9747. }
  9748. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9749. const renderer = this._renderer;
  9750. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9751. if ( isCubeTexture ) {
  9752. if ( this._cubemapMaterial === null ) {
  9753. this._cubemapMaterial = _getCubemapMaterial();
  9754. }
  9755. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9756. } else {
  9757. if ( this._equirectMaterial === null ) {
  9758. this._equirectMaterial = _getEquirectMaterial();
  9759. }
  9760. }
  9761. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9762. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9763. const uniforms = material.uniforms;
  9764. uniforms[ 'envMap' ].value = texture;
  9765. const size = this._cubeSize;
  9766. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9767. renderer.setRenderTarget( cubeUVRenderTarget );
  9768. renderer.render( mesh, _flatCamera );
  9769. }
  9770. _applyPMREM( cubeUVRenderTarget ) {
  9771. const renderer = this._renderer;
  9772. const autoClear = renderer.autoClear;
  9773. renderer.autoClear = false;
  9774. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9775. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9776. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9777. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9778. }
  9779. renderer.autoClear = autoClear;
  9780. }
  9781. /**
  9782. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9783. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9784. * the blur latitudinally (around the poles), and then longitudinally (towards
  9785. * the poles) to approximate the orthogonally-separable blur. It is least
  9786. * accurate at the poles, but still does a decent job.
  9787. */
  9788. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9789. const pingPongRenderTarget = this._pingPongRenderTarget;
  9790. this._halfBlur(
  9791. cubeUVRenderTarget,
  9792. pingPongRenderTarget,
  9793. lodIn,
  9794. lodOut,
  9795. sigma,
  9796. 'latitudinal',
  9797. poleAxis );
  9798. this._halfBlur(
  9799. pingPongRenderTarget,
  9800. cubeUVRenderTarget,
  9801. lodOut,
  9802. lodOut,
  9803. sigma,
  9804. 'longitudinal',
  9805. poleAxis );
  9806. }
  9807. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9808. const renderer = this._renderer;
  9809. const blurMaterial = this._blurMaterial;
  9810. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9811. console.error(
  9812. 'blur direction must be either latitudinal or longitudinal!' );
  9813. }
  9814. // Number of standard deviations at which to cut off the discrete approximation.
  9815. const STANDARD_DEVIATIONS = 3;
  9816. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9817. const blurUniforms = blurMaterial.uniforms;
  9818. const pixels = this._sizeLods[ lodIn ] - 1;
  9819. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9820. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9821. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9822. if ( samples > MAX_SAMPLES ) {
  9823. console.warn( `sigmaRadians, ${
  9824. sigmaRadians}, is too large and will clip, as it requested ${
  9825. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9826. }
  9827. const weights = [];
  9828. let sum = 0;
  9829. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9830. const x = i / sigmaPixels;
  9831. const weight = Math.exp( - x * x / 2 );
  9832. weights.push( weight );
  9833. if ( i === 0 ) {
  9834. sum += weight;
  9835. } else if ( i < samples ) {
  9836. sum += 2 * weight;
  9837. }
  9838. }
  9839. for ( let i = 0; i < weights.length; i ++ ) {
  9840. weights[ i ] = weights[ i ] / sum;
  9841. }
  9842. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9843. blurUniforms[ 'samples' ].value = samples;
  9844. blurUniforms[ 'weights' ].value = weights;
  9845. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9846. if ( poleAxis ) {
  9847. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9848. }
  9849. const { _lodMax } = this;
  9850. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9851. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9852. const outputSize = this._sizeLods[ lodOut ];
  9853. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9854. const y = 4 * ( this._cubeSize - outputSize );
  9855. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9856. renderer.setRenderTarget( targetOut );
  9857. renderer.render( blurMesh, _flatCamera );
  9858. }
  9859. }
  9860. function _createPlanes( lodMax ) {
  9861. const lodPlanes = [];
  9862. const sizeLods = [];
  9863. const sigmas = [];
  9864. let lod = lodMax;
  9865. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9866. for ( let i = 0; i < totalLods; i ++ ) {
  9867. const sizeLod = Math.pow( 2, lod );
  9868. sizeLods.push( sizeLod );
  9869. let sigma = 1.0 / sizeLod;
  9870. if ( i > lodMax - LOD_MIN ) {
  9871. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9872. } else if ( i === 0 ) {
  9873. sigma = 0;
  9874. }
  9875. sigmas.push( sigma );
  9876. const texelSize = 1.0 / ( sizeLod - 2 );
  9877. const min = - texelSize;
  9878. const max = 1 + texelSize;
  9879. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9880. const cubeFaces = 6;
  9881. const vertices = 6;
  9882. const positionSize = 3;
  9883. const uvSize = 2;
  9884. const faceIndexSize = 1;
  9885. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9886. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9887. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9888. for ( let face = 0; face < cubeFaces; face ++ ) {
  9889. const x = ( face % 3 ) * 2 / 3 - 1;
  9890. const y = face > 2 ? 0 : - 1;
  9891. const coordinates = [
  9892. x, y, 0,
  9893. x + 2 / 3, y, 0,
  9894. x + 2 / 3, y + 1, 0,
  9895. x, y, 0,
  9896. x + 2 / 3, y + 1, 0,
  9897. x, y + 1, 0
  9898. ];
  9899. position.set( coordinates, positionSize * vertices * face );
  9900. uv.set( uv1, uvSize * vertices * face );
  9901. const fill = [ face, face, face, face, face, face ];
  9902. faceIndex.set( fill, faceIndexSize * vertices * face );
  9903. }
  9904. const planes = new BufferGeometry();
  9905. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9906. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9907. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9908. lodPlanes.push( planes );
  9909. if ( lod > LOD_MIN ) {
  9910. lod --;
  9911. }
  9912. }
  9913. return { lodPlanes, sizeLods, sigmas };
  9914. }
  9915. function _createRenderTarget( width, height, params ) {
  9916. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9917. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9918. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9919. cubeUVRenderTarget.scissorTest = true;
  9920. return cubeUVRenderTarget;
  9921. }
  9922. function _setViewport( target, x, y, width, height ) {
  9923. target.viewport.set( x, y, width, height );
  9924. target.scissor.set( x, y, width, height );
  9925. }
  9926. function _getBlurShader( lodMax, width, height ) {
  9927. const weights = new Float32Array( MAX_SAMPLES );
  9928. const poleAxis = new Vector3( 0, 1, 0 );
  9929. const shaderMaterial = new ShaderMaterial( {
  9930. name: 'SphericalGaussianBlur',
  9931. defines: {
  9932. 'n': MAX_SAMPLES,
  9933. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9934. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9935. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9936. },
  9937. uniforms: {
  9938. 'envMap': { value: null },
  9939. 'samples': { value: 1 },
  9940. 'weights': { value: weights },
  9941. 'latitudinal': { value: false },
  9942. 'dTheta': { value: 0 },
  9943. 'mipInt': { value: 0 },
  9944. 'poleAxis': { value: poleAxis }
  9945. },
  9946. vertexShader: _getCommonVertexShader(),
  9947. fragmentShader: /* glsl */`
  9948. precision mediump float;
  9949. precision mediump int;
  9950. varying vec3 vOutputDirection;
  9951. uniform sampler2D envMap;
  9952. uniform int samples;
  9953. uniform float weights[ n ];
  9954. uniform bool latitudinal;
  9955. uniform float dTheta;
  9956. uniform float mipInt;
  9957. uniform vec3 poleAxis;
  9958. #define ENVMAP_TYPE_CUBE_UV
  9959. #include <cube_uv_reflection_fragment>
  9960. vec3 getSample( float theta, vec3 axis ) {
  9961. float cosTheta = cos( theta );
  9962. // Rodrigues' axis-angle rotation
  9963. vec3 sampleDirection = vOutputDirection * cosTheta
  9964. + cross( axis, vOutputDirection ) * sin( theta )
  9965. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9966. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9967. }
  9968. void main() {
  9969. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9970. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9971. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9972. }
  9973. axis = normalize( axis );
  9974. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9975. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9976. for ( int i = 1; i < n; i++ ) {
  9977. if ( i >= samples ) {
  9978. break;
  9979. }
  9980. float theta = dTheta * float( i );
  9981. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9982. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9983. }
  9984. }
  9985. `,
  9986. blending: NoBlending,
  9987. depthTest: false,
  9988. depthWrite: false
  9989. } );
  9990. return shaderMaterial;
  9991. }
  9992. function _getEquirectMaterial() {
  9993. return new ShaderMaterial( {
  9994. name: 'EquirectangularToCubeUV',
  9995. uniforms: {
  9996. 'envMap': { value: null }
  9997. },
  9998. vertexShader: _getCommonVertexShader(),
  9999. fragmentShader: /* glsl */`
  10000. precision mediump float;
  10001. precision mediump int;
  10002. varying vec3 vOutputDirection;
  10003. uniform sampler2D envMap;
  10004. #include <common>
  10005. void main() {
  10006. vec3 outputDirection = normalize( vOutputDirection );
  10007. vec2 uv = equirectUv( outputDirection );
  10008. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10009. }
  10010. `,
  10011. blending: NoBlending,
  10012. depthTest: false,
  10013. depthWrite: false
  10014. } );
  10015. }
  10016. function _getCubemapMaterial() {
  10017. return new ShaderMaterial( {
  10018. name: 'CubemapToCubeUV',
  10019. uniforms: {
  10020. 'envMap': { value: null },
  10021. 'flipEnvMap': { value: - 1 }
  10022. },
  10023. vertexShader: _getCommonVertexShader(),
  10024. fragmentShader: /* glsl */`
  10025. precision mediump float;
  10026. precision mediump int;
  10027. uniform float flipEnvMap;
  10028. varying vec3 vOutputDirection;
  10029. uniform samplerCube envMap;
  10030. void main() {
  10031. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10032. }
  10033. `,
  10034. blending: NoBlending,
  10035. depthTest: false,
  10036. depthWrite: false
  10037. } );
  10038. }
  10039. function _getCommonVertexShader() {
  10040. return /* glsl */`
  10041. precision mediump float;
  10042. precision mediump int;
  10043. attribute float faceIndex;
  10044. varying vec3 vOutputDirection;
  10045. // RH coordinate system; PMREM face-indexing convention
  10046. vec3 getDirection( vec2 uv, float face ) {
  10047. uv = 2.0 * uv - 1.0;
  10048. vec3 direction = vec3( uv, 1.0 );
  10049. if ( face == 0.0 ) {
  10050. direction = direction.zyx; // ( 1, v, u ) pos x
  10051. } else if ( face == 1.0 ) {
  10052. direction = direction.xzy;
  10053. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10054. } else if ( face == 2.0 ) {
  10055. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10056. } else if ( face == 3.0 ) {
  10057. direction = direction.zyx;
  10058. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10059. } else if ( face == 4.0 ) {
  10060. direction = direction.xzy;
  10061. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10062. } else if ( face == 5.0 ) {
  10063. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10064. }
  10065. return direction;
  10066. }
  10067. void main() {
  10068. vOutputDirection = getDirection( uv, faceIndex );
  10069. gl_Position = vec4( position, 1.0 );
  10070. }
  10071. `;
  10072. }
  10073. function WebGLCubeUVMaps( renderer ) {
  10074. let cubeUVmaps = new WeakMap();
  10075. let pmremGenerator = null;
  10076. function get( texture ) {
  10077. if ( texture && texture.isTexture ) {
  10078. const mapping = texture.mapping;
  10079. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10080. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10081. // equirect/cube map to cubeUV conversion
  10082. if ( isEquirectMap || isCubeMap ) {
  10083. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10084. texture.needsPMREMUpdate = false;
  10085. let renderTarget = cubeUVmaps.get( texture );
  10086. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10087. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10088. cubeUVmaps.set( texture, renderTarget );
  10089. return renderTarget.texture;
  10090. } else {
  10091. if ( cubeUVmaps.has( texture ) ) {
  10092. return cubeUVmaps.get( texture ).texture;
  10093. } else {
  10094. const image = texture.image;
  10095. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10096. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10097. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10098. cubeUVmaps.set( texture, renderTarget );
  10099. texture.addEventListener( 'dispose', onTextureDispose );
  10100. return renderTarget.texture;
  10101. } else {
  10102. // image not yet ready. try the conversion next frame
  10103. return null;
  10104. }
  10105. }
  10106. }
  10107. }
  10108. }
  10109. return texture;
  10110. }
  10111. function isCubeTextureComplete( image ) {
  10112. let count = 0;
  10113. const length = 6;
  10114. for ( let i = 0; i < length; i ++ ) {
  10115. if ( image[ i ] !== undefined ) count ++;
  10116. }
  10117. return count === length;
  10118. }
  10119. function onTextureDispose( event ) {
  10120. const texture = event.target;
  10121. texture.removeEventListener( 'dispose', onTextureDispose );
  10122. const cubemapUV = cubeUVmaps.get( texture );
  10123. if ( cubemapUV !== undefined ) {
  10124. cubeUVmaps.delete( texture );
  10125. cubemapUV.dispose();
  10126. }
  10127. }
  10128. function dispose() {
  10129. cubeUVmaps = new WeakMap();
  10130. if ( pmremGenerator !== null ) {
  10131. pmremGenerator.dispose();
  10132. pmremGenerator = null;
  10133. }
  10134. }
  10135. return {
  10136. get: get,
  10137. dispose: dispose
  10138. };
  10139. }
  10140. function WebGLExtensions( gl ) {
  10141. const extensions = {};
  10142. function getExtension( name ) {
  10143. if ( extensions[ name ] !== undefined ) {
  10144. return extensions[ name ];
  10145. }
  10146. let extension;
  10147. switch ( name ) {
  10148. case 'WEBGL_depth_texture':
  10149. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10150. break;
  10151. case 'EXT_texture_filter_anisotropic':
  10152. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10153. break;
  10154. case 'WEBGL_compressed_texture_s3tc':
  10155. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10156. break;
  10157. case 'WEBGL_compressed_texture_pvrtc':
  10158. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10159. break;
  10160. default:
  10161. extension = gl.getExtension( name );
  10162. }
  10163. extensions[ name ] = extension;
  10164. return extension;
  10165. }
  10166. return {
  10167. has: function ( name ) {
  10168. return getExtension( name ) !== null;
  10169. },
  10170. init: function ( capabilities ) {
  10171. if ( capabilities.isWebGL2 ) {
  10172. getExtension( 'EXT_color_buffer_float' );
  10173. } else {
  10174. getExtension( 'WEBGL_depth_texture' );
  10175. getExtension( 'OES_texture_float' );
  10176. getExtension( 'OES_texture_half_float' );
  10177. getExtension( 'OES_texture_half_float_linear' );
  10178. getExtension( 'OES_standard_derivatives' );
  10179. getExtension( 'OES_element_index_uint' );
  10180. getExtension( 'OES_vertex_array_object' );
  10181. getExtension( 'ANGLE_instanced_arrays' );
  10182. }
  10183. getExtension( 'OES_texture_float_linear' );
  10184. getExtension( 'EXT_color_buffer_half_float' );
  10185. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10186. },
  10187. get: function ( name ) {
  10188. const extension = getExtension( name );
  10189. if ( extension === null ) {
  10190. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10191. }
  10192. return extension;
  10193. }
  10194. };
  10195. }
  10196. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10197. const geometries = {};
  10198. const wireframeAttributes = new WeakMap();
  10199. function onGeometryDispose( event ) {
  10200. const geometry = event.target;
  10201. if ( geometry.index !== null ) {
  10202. attributes.remove( geometry.index );
  10203. }
  10204. for ( const name in geometry.attributes ) {
  10205. attributes.remove( geometry.attributes[ name ] );
  10206. }
  10207. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10208. delete geometries[ geometry.id ];
  10209. const attribute = wireframeAttributes.get( geometry );
  10210. if ( attribute ) {
  10211. attributes.remove( attribute );
  10212. wireframeAttributes.delete( geometry );
  10213. }
  10214. bindingStates.releaseStatesOfGeometry( geometry );
  10215. if ( geometry.isInstancedBufferGeometry === true ) {
  10216. delete geometry._maxInstanceCount;
  10217. }
  10218. //
  10219. info.memory.geometries --;
  10220. }
  10221. function get( object, geometry ) {
  10222. if ( geometries[ geometry.id ] === true ) return geometry;
  10223. geometry.addEventListener( 'dispose', onGeometryDispose );
  10224. geometries[ geometry.id ] = true;
  10225. info.memory.geometries ++;
  10226. return geometry;
  10227. }
  10228. function update( geometry ) {
  10229. const geometryAttributes = geometry.attributes;
  10230. // Updating index buffer in VAO now. See WebGLBindingStates.
  10231. for ( const name in geometryAttributes ) {
  10232. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10233. }
  10234. // morph targets
  10235. const morphAttributes = geometry.morphAttributes;
  10236. for ( const name in morphAttributes ) {
  10237. const array = morphAttributes[ name ];
  10238. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10239. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10240. }
  10241. }
  10242. }
  10243. function updateWireframeAttribute( geometry ) {
  10244. const indices = [];
  10245. const geometryIndex = geometry.index;
  10246. const geometryPosition = geometry.attributes.position;
  10247. let version = 0;
  10248. if ( geometryIndex !== null ) {
  10249. const array = geometryIndex.array;
  10250. version = geometryIndex.version;
  10251. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10252. const a = array[ i + 0 ];
  10253. const b = array[ i + 1 ];
  10254. const c = array[ i + 2 ];
  10255. indices.push( a, b, b, c, c, a );
  10256. }
  10257. } else {
  10258. const array = geometryPosition.array;
  10259. version = geometryPosition.version;
  10260. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10261. const a = i + 0;
  10262. const b = i + 1;
  10263. const c = i + 2;
  10264. indices.push( a, b, b, c, c, a );
  10265. }
  10266. }
  10267. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10268. attribute.version = version;
  10269. // Updating index buffer in VAO now. See WebGLBindingStates
  10270. //
  10271. const previousAttribute = wireframeAttributes.get( geometry );
  10272. if ( previousAttribute ) attributes.remove( previousAttribute );
  10273. //
  10274. wireframeAttributes.set( geometry, attribute );
  10275. }
  10276. function getWireframeAttribute( geometry ) {
  10277. const currentAttribute = wireframeAttributes.get( geometry );
  10278. if ( currentAttribute ) {
  10279. const geometryIndex = geometry.index;
  10280. if ( geometryIndex !== null ) {
  10281. // if the attribute is obsolete, create a new one
  10282. if ( currentAttribute.version < geometryIndex.version ) {
  10283. updateWireframeAttribute( geometry );
  10284. }
  10285. }
  10286. } else {
  10287. updateWireframeAttribute( geometry );
  10288. }
  10289. return wireframeAttributes.get( geometry );
  10290. }
  10291. return {
  10292. get: get,
  10293. update: update,
  10294. getWireframeAttribute: getWireframeAttribute
  10295. };
  10296. }
  10297. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10298. const isWebGL2 = capabilities.isWebGL2;
  10299. let mode;
  10300. function setMode( value ) {
  10301. mode = value;
  10302. }
  10303. let type, bytesPerElement;
  10304. function setIndex( value ) {
  10305. type = value.type;
  10306. bytesPerElement = value.bytesPerElement;
  10307. }
  10308. function render( start, count ) {
  10309. gl.drawElements( mode, count, type, start * bytesPerElement );
  10310. info.update( count, mode, 1 );
  10311. }
  10312. function renderInstances( start, count, primcount ) {
  10313. if ( primcount === 0 ) return;
  10314. let extension, methodName;
  10315. if ( isWebGL2 ) {
  10316. extension = gl;
  10317. methodName = 'drawElementsInstanced';
  10318. } else {
  10319. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10320. methodName = 'drawElementsInstancedANGLE';
  10321. if ( extension === null ) {
  10322. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10323. return;
  10324. }
  10325. }
  10326. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10327. info.update( count, mode, primcount );
  10328. }
  10329. //
  10330. this.setMode = setMode;
  10331. this.setIndex = setIndex;
  10332. this.render = render;
  10333. this.renderInstances = renderInstances;
  10334. }
  10335. function WebGLInfo( gl ) {
  10336. const memory = {
  10337. geometries: 0,
  10338. textures: 0
  10339. };
  10340. const render = {
  10341. frame: 0,
  10342. calls: 0,
  10343. triangles: 0,
  10344. points: 0,
  10345. lines: 0
  10346. };
  10347. function update( count, mode, instanceCount ) {
  10348. render.calls ++;
  10349. switch ( mode ) {
  10350. case gl.TRIANGLES:
  10351. render.triangles += instanceCount * ( count / 3 );
  10352. break;
  10353. case gl.LINES:
  10354. render.lines += instanceCount * ( count / 2 );
  10355. break;
  10356. case gl.LINE_STRIP:
  10357. render.lines += instanceCount * ( count - 1 );
  10358. break;
  10359. case gl.LINE_LOOP:
  10360. render.lines += instanceCount * count;
  10361. break;
  10362. case gl.POINTS:
  10363. render.points += instanceCount * count;
  10364. break;
  10365. default:
  10366. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10367. break;
  10368. }
  10369. }
  10370. function reset() {
  10371. render.frame ++;
  10372. render.calls = 0;
  10373. render.triangles = 0;
  10374. render.points = 0;
  10375. render.lines = 0;
  10376. }
  10377. return {
  10378. memory: memory,
  10379. render: render,
  10380. programs: null,
  10381. autoReset: true,
  10382. reset: reset,
  10383. update: update
  10384. };
  10385. }
  10386. function numericalSort( a, b ) {
  10387. return a[ 0 ] - b[ 0 ];
  10388. }
  10389. function absNumericalSort( a, b ) {
  10390. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10391. }
  10392. function WebGLMorphtargets( gl, capabilities, textures ) {
  10393. const influencesList = {};
  10394. const morphInfluences = new Float32Array( 8 );
  10395. const morphTextures = new WeakMap();
  10396. const morph = new Vector4();
  10397. const workInfluences = [];
  10398. for ( let i = 0; i < 8; i ++ ) {
  10399. workInfluences[ i ] = [ i, 0 ];
  10400. }
  10401. function update( object, geometry, program ) {
  10402. const objectInfluences = object.morphTargetInfluences;
  10403. if ( capabilities.isWebGL2 === true ) {
  10404. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10405. // into an array of data textures. Each layer represents a single morph target.
  10406. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10407. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10408. let entry = morphTextures.get( geometry );
  10409. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10410. if ( entry !== undefined ) entry.texture.dispose();
  10411. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10412. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10413. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10414. const morphTargets = geometry.morphAttributes.position || [];
  10415. const morphNormals = geometry.morphAttributes.normal || [];
  10416. const morphColors = geometry.morphAttributes.color || [];
  10417. let vertexDataCount = 0;
  10418. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10419. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10420. if ( hasMorphColors === true ) vertexDataCount = 3;
  10421. let width = geometry.attributes.position.count * vertexDataCount;
  10422. let height = 1;
  10423. if ( width > capabilities.maxTextureSize ) {
  10424. height = Math.ceil( width / capabilities.maxTextureSize );
  10425. width = capabilities.maxTextureSize;
  10426. }
  10427. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10428. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10429. texture.type = FloatType;
  10430. texture.needsUpdate = true;
  10431. // fill buffer
  10432. const vertexDataStride = vertexDataCount * 4;
  10433. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10434. const morphTarget = morphTargets[ i ];
  10435. const morphNormal = morphNormals[ i ];
  10436. const morphColor = morphColors[ i ];
  10437. const offset = width * height * 4 * i;
  10438. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10439. const stride = j * vertexDataStride;
  10440. if ( hasMorphPosition === true ) {
  10441. morph.fromBufferAttribute( morphTarget, j );
  10442. buffer[ offset + stride + 0 ] = morph.x;
  10443. buffer[ offset + stride + 1 ] = morph.y;
  10444. buffer[ offset + stride + 2 ] = morph.z;
  10445. buffer[ offset + stride + 3 ] = 0;
  10446. }
  10447. if ( hasMorphNormals === true ) {
  10448. morph.fromBufferAttribute( morphNormal, j );
  10449. buffer[ offset + stride + 4 ] = morph.x;
  10450. buffer[ offset + stride + 5 ] = morph.y;
  10451. buffer[ offset + stride + 6 ] = morph.z;
  10452. buffer[ offset + stride + 7 ] = 0;
  10453. }
  10454. if ( hasMorphColors === true ) {
  10455. morph.fromBufferAttribute( morphColor, j );
  10456. buffer[ offset + stride + 8 ] = morph.x;
  10457. buffer[ offset + stride + 9 ] = morph.y;
  10458. buffer[ offset + stride + 10 ] = morph.z;
  10459. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10460. }
  10461. }
  10462. }
  10463. entry = {
  10464. count: morphTargetsCount,
  10465. texture: texture,
  10466. size: new Vector2( width, height )
  10467. };
  10468. morphTextures.set( geometry, entry );
  10469. function disposeTexture() {
  10470. texture.dispose();
  10471. morphTextures.delete( geometry );
  10472. geometry.removeEventListener( 'dispose', disposeTexture );
  10473. }
  10474. geometry.addEventListener( 'dispose', disposeTexture );
  10475. }
  10476. //
  10477. let morphInfluencesSum = 0;
  10478. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10479. morphInfluencesSum += objectInfluences[ i ];
  10480. }
  10481. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10482. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10483. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10484. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10485. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10486. } else {
  10487. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10488. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10489. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10490. let influences = influencesList[ geometry.id ];
  10491. if ( influences === undefined || influences.length !== length ) {
  10492. // initialise list
  10493. influences = [];
  10494. for ( let i = 0; i < length; i ++ ) {
  10495. influences[ i ] = [ i, 0 ];
  10496. }
  10497. influencesList[ geometry.id ] = influences;
  10498. }
  10499. // Collect influences
  10500. for ( let i = 0; i < length; i ++ ) {
  10501. const influence = influences[ i ];
  10502. influence[ 0 ] = i;
  10503. influence[ 1 ] = objectInfluences[ i ];
  10504. }
  10505. influences.sort( absNumericalSort );
  10506. for ( let i = 0; i < 8; i ++ ) {
  10507. if ( i < length && influences[ i ][ 1 ] ) {
  10508. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10509. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10510. } else {
  10511. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10512. workInfluences[ i ][ 1 ] = 0;
  10513. }
  10514. }
  10515. workInfluences.sort( numericalSort );
  10516. const morphTargets = geometry.morphAttributes.position;
  10517. const morphNormals = geometry.morphAttributes.normal;
  10518. let morphInfluencesSum = 0;
  10519. for ( let i = 0; i < 8; i ++ ) {
  10520. const influence = workInfluences[ i ];
  10521. const index = influence[ 0 ];
  10522. const value = influence[ 1 ];
  10523. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10524. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10525. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10526. }
  10527. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10528. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10529. }
  10530. morphInfluences[ i ] = value;
  10531. morphInfluencesSum += value;
  10532. } else {
  10533. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10534. geometry.deleteAttribute( 'morphTarget' + i );
  10535. }
  10536. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10537. geometry.deleteAttribute( 'morphNormal' + i );
  10538. }
  10539. morphInfluences[ i ] = 0;
  10540. }
  10541. }
  10542. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10543. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10544. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10545. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10546. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10547. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10548. }
  10549. }
  10550. return {
  10551. update: update
  10552. };
  10553. }
  10554. function WebGLObjects( gl, geometries, attributes, info ) {
  10555. let updateMap = new WeakMap();
  10556. function update( object ) {
  10557. const frame = info.render.frame;
  10558. const geometry = object.geometry;
  10559. const buffergeometry = geometries.get( object, geometry );
  10560. // Update once per frame
  10561. if ( updateMap.get( buffergeometry ) !== frame ) {
  10562. geometries.update( buffergeometry );
  10563. updateMap.set( buffergeometry, frame );
  10564. }
  10565. if ( object.isInstancedMesh ) {
  10566. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10567. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10568. }
  10569. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10570. if ( object.instanceColor !== null ) {
  10571. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10572. }
  10573. }
  10574. return buffergeometry;
  10575. }
  10576. function dispose() {
  10577. updateMap = new WeakMap();
  10578. }
  10579. function onInstancedMeshDispose( event ) {
  10580. const instancedMesh = event.target;
  10581. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10582. attributes.remove( instancedMesh.instanceMatrix );
  10583. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10584. }
  10585. return {
  10586. update: update,
  10587. dispose: dispose
  10588. };
  10589. }
  10590. /**
  10591. * Uniforms of a program.
  10592. * Those form a tree structure with a special top-level container for the root,
  10593. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10594. *
  10595. *
  10596. * Properties of inner nodes including the top-level container:
  10597. *
  10598. * .seq - array of nested uniforms
  10599. * .map - nested uniforms by name
  10600. *
  10601. *
  10602. * Methods of all nodes except the top-level container:
  10603. *
  10604. * .setValue( gl, value, [textures] )
  10605. *
  10606. * uploads a uniform value(s)
  10607. * the 'textures' parameter is needed for sampler uniforms
  10608. *
  10609. *
  10610. * Static methods of the top-level container (textures factorizations):
  10611. *
  10612. * .upload( gl, seq, values, textures )
  10613. *
  10614. * sets uniforms in 'seq' to 'values[id].value'
  10615. *
  10616. * .seqWithValue( seq, values ) : filteredSeq
  10617. *
  10618. * filters 'seq' entries with corresponding entry in values
  10619. *
  10620. *
  10621. * Methods of the top-level container (textures factorizations):
  10622. *
  10623. * .setValue( gl, name, value, textures )
  10624. *
  10625. * sets uniform with name 'name' to 'value'
  10626. *
  10627. * .setOptional( gl, obj, prop )
  10628. *
  10629. * like .set for an optional property of the object
  10630. *
  10631. */
  10632. const emptyTexture = /*@__PURE__*/ new Texture();
  10633. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10634. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10635. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10636. // --- Utilities ---
  10637. // Array Caches (provide typed arrays for temporary by size)
  10638. const arrayCacheF32 = [];
  10639. const arrayCacheI32 = [];
  10640. // Float32Array caches used for uploading Matrix uniforms
  10641. const mat4array = new Float32Array( 16 );
  10642. const mat3array = new Float32Array( 9 );
  10643. const mat2array = new Float32Array( 4 );
  10644. // Flattening for arrays of vectors and matrices
  10645. function flatten( array, nBlocks, blockSize ) {
  10646. const firstElem = array[ 0 ];
  10647. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10648. // unoptimized: ! isNaN( firstElem )
  10649. // see http://jacksondunstan.com/articles/983
  10650. const n = nBlocks * blockSize;
  10651. let r = arrayCacheF32[ n ];
  10652. if ( r === undefined ) {
  10653. r = new Float32Array( n );
  10654. arrayCacheF32[ n ] = r;
  10655. }
  10656. if ( nBlocks !== 0 ) {
  10657. firstElem.toArray( r, 0 );
  10658. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10659. offset += blockSize;
  10660. array[ i ].toArray( r, offset );
  10661. }
  10662. }
  10663. return r;
  10664. }
  10665. function arraysEqual( a, b ) {
  10666. if ( a.length !== b.length ) return false;
  10667. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10668. if ( a[ i ] !== b[ i ] ) return false;
  10669. }
  10670. return true;
  10671. }
  10672. function copyArray( a, b ) {
  10673. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10674. a[ i ] = b[ i ];
  10675. }
  10676. }
  10677. // Texture unit allocation
  10678. function allocTexUnits( textures, n ) {
  10679. let r = arrayCacheI32[ n ];
  10680. if ( r === undefined ) {
  10681. r = new Int32Array( n );
  10682. arrayCacheI32[ n ] = r;
  10683. }
  10684. for ( let i = 0; i !== n; ++ i ) {
  10685. r[ i ] = textures.allocateTextureUnit();
  10686. }
  10687. return r;
  10688. }
  10689. // --- Setters ---
  10690. // Note: Defining these methods externally, because they come in a bunch
  10691. // and this way their names minify.
  10692. // Single scalar
  10693. function setValueV1f( gl, v ) {
  10694. const cache = this.cache;
  10695. if ( cache[ 0 ] === v ) return;
  10696. gl.uniform1f( this.addr, v );
  10697. cache[ 0 ] = v;
  10698. }
  10699. // Single float vector (from flat array or THREE.VectorN)
  10700. function setValueV2f( gl, v ) {
  10701. const cache = this.cache;
  10702. if ( v.x !== undefined ) {
  10703. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10704. gl.uniform2f( this.addr, v.x, v.y );
  10705. cache[ 0 ] = v.x;
  10706. cache[ 1 ] = v.y;
  10707. }
  10708. } else {
  10709. if ( arraysEqual( cache, v ) ) return;
  10710. gl.uniform2fv( this.addr, v );
  10711. copyArray( cache, v );
  10712. }
  10713. }
  10714. function setValueV3f( gl, v ) {
  10715. const cache = this.cache;
  10716. if ( v.x !== undefined ) {
  10717. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10718. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10719. cache[ 0 ] = v.x;
  10720. cache[ 1 ] = v.y;
  10721. cache[ 2 ] = v.z;
  10722. }
  10723. } else if ( v.r !== undefined ) {
  10724. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10725. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10726. cache[ 0 ] = v.r;
  10727. cache[ 1 ] = v.g;
  10728. cache[ 2 ] = v.b;
  10729. }
  10730. } else {
  10731. if ( arraysEqual( cache, v ) ) return;
  10732. gl.uniform3fv( this.addr, v );
  10733. copyArray( cache, v );
  10734. }
  10735. }
  10736. function setValueV4f( gl, v ) {
  10737. const cache = this.cache;
  10738. if ( v.x !== undefined ) {
  10739. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10740. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10741. cache[ 0 ] = v.x;
  10742. cache[ 1 ] = v.y;
  10743. cache[ 2 ] = v.z;
  10744. cache[ 3 ] = v.w;
  10745. }
  10746. } else {
  10747. if ( arraysEqual( cache, v ) ) return;
  10748. gl.uniform4fv( this.addr, v );
  10749. copyArray( cache, v );
  10750. }
  10751. }
  10752. // Single matrix (from flat array or THREE.MatrixN)
  10753. function setValueM2( gl, v ) {
  10754. const cache = this.cache;
  10755. const elements = v.elements;
  10756. if ( elements === undefined ) {
  10757. if ( arraysEqual( cache, v ) ) return;
  10758. gl.uniformMatrix2fv( this.addr, false, v );
  10759. copyArray( cache, v );
  10760. } else {
  10761. if ( arraysEqual( cache, elements ) ) return;
  10762. mat2array.set( elements );
  10763. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10764. copyArray( cache, elements );
  10765. }
  10766. }
  10767. function setValueM3( gl, v ) {
  10768. const cache = this.cache;
  10769. const elements = v.elements;
  10770. if ( elements === undefined ) {
  10771. if ( arraysEqual( cache, v ) ) return;
  10772. gl.uniformMatrix3fv( this.addr, false, v );
  10773. copyArray( cache, v );
  10774. } else {
  10775. if ( arraysEqual( cache, elements ) ) return;
  10776. mat3array.set( elements );
  10777. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10778. copyArray( cache, elements );
  10779. }
  10780. }
  10781. function setValueM4( gl, v ) {
  10782. const cache = this.cache;
  10783. const elements = v.elements;
  10784. if ( elements === undefined ) {
  10785. if ( arraysEqual( cache, v ) ) return;
  10786. gl.uniformMatrix4fv( this.addr, false, v );
  10787. copyArray( cache, v );
  10788. } else {
  10789. if ( arraysEqual( cache, elements ) ) return;
  10790. mat4array.set( elements );
  10791. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10792. copyArray( cache, elements );
  10793. }
  10794. }
  10795. // Single integer / boolean
  10796. function setValueV1i( gl, v ) {
  10797. const cache = this.cache;
  10798. if ( cache[ 0 ] === v ) return;
  10799. gl.uniform1i( this.addr, v );
  10800. cache[ 0 ] = v;
  10801. }
  10802. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10803. function setValueV2i( gl, v ) {
  10804. const cache = this.cache;
  10805. if ( v.x !== undefined ) {
  10806. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10807. gl.uniform2i( this.addr, v.x, v.y );
  10808. cache[ 0 ] = v.x;
  10809. cache[ 1 ] = v.y;
  10810. }
  10811. } else {
  10812. if ( arraysEqual( cache, v ) ) return;
  10813. gl.uniform2iv( this.addr, v );
  10814. copyArray( cache, v );
  10815. }
  10816. }
  10817. function setValueV3i( gl, v ) {
  10818. const cache = this.cache;
  10819. if ( v.x !== undefined ) {
  10820. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10821. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10822. cache[ 0 ] = v.x;
  10823. cache[ 1 ] = v.y;
  10824. cache[ 2 ] = v.z;
  10825. }
  10826. } else {
  10827. if ( arraysEqual( cache, v ) ) return;
  10828. gl.uniform3iv( this.addr, v );
  10829. copyArray( cache, v );
  10830. }
  10831. }
  10832. function setValueV4i( gl, v ) {
  10833. const cache = this.cache;
  10834. if ( v.x !== undefined ) {
  10835. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10836. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10837. cache[ 0 ] = v.x;
  10838. cache[ 1 ] = v.y;
  10839. cache[ 2 ] = v.z;
  10840. cache[ 3 ] = v.w;
  10841. }
  10842. } else {
  10843. if ( arraysEqual( cache, v ) ) return;
  10844. gl.uniform4iv( this.addr, v );
  10845. copyArray( cache, v );
  10846. }
  10847. }
  10848. // Single unsigned integer
  10849. function setValueV1ui( gl, v ) {
  10850. const cache = this.cache;
  10851. if ( cache[ 0 ] === v ) return;
  10852. gl.uniform1ui( this.addr, v );
  10853. cache[ 0 ] = v;
  10854. }
  10855. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10856. function setValueV2ui( gl, v ) {
  10857. const cache = this.cache;
  10858. if ( v.x !== undefined ) {
  10859. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10860. gl.uniform2ui( this.addr, v.x, v.y );
  10861. cache[ 0 ] = v.x;
  10862. cache[ 1 ] = v.y;
  10863. }
  10864. } else {
  10865. if ( arraysEqual( cache, v ) ) return;
  10866. gl.uniform2uiv( this.addr, v );
  10867. copyArray( cache, v );
  10868. }
  10869. }
  10870. function setValueV3ui( gl, v ) {
  10871. const cache = this.cache;
  10872. if ( v.x !== undefined ) {
  10873. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10874. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10875. cache[ 0 ] = v.x;
  10876. cache[ 1 ] = v.y;
  10877. cache[ 2 ] = v.z;
  10878. }
  10879. } else {
  10880. if ( arraysEqual( cache, v ) ) return;
  10881. gl.uniform3uiv( this.addr, v );
  10882. copyArray( cache, v );
  10883. }
  10884. }
  10885. function setValueV4ui( gl, v ) {
  10886. const cache = this.cache;
  10887. if ( v.x !== undefined ) {
  10888. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10889. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10890. cache[ 0 ] = v.x;
  10891. cache[ 1 ] = v.y;
  10892. cache[ 2 ] = v.z;
  10893. cache[ 3 ] = v.w;
  10894. }
  10895. } else {
  10896. if ( arraysEqual( cache, v ) ) return;
  10897. gl.uniform4uiv( this.addr, v );
  10898. copyArray( cache, v );
  10899. }
  10900. }
  10901. // Single texture (2D / Cube)
  10902. function setValueT1( gl, v, textures ) {
  10903. const cache = this.cache;
  10904. const unit = textures.allocateTextureUnit();
  10905. if ( cache[ 0 ] !== unit ) {
  10906. gl.uniform1i( this.addr, unit );
  10907. cache[ 0 ] = unit;
  10908. }
  10909. textures.setTexture2D( v || emptyTexture, unit );
  10910. }
  10911. function setValueT3D1( gl, v, textures ) {
  10912. const cache = this.cache;
  10913. const unit = textures.allocateTextureUnit();
  10914. if ( cache[ 0 ] !== unit ) {
  10915. gl.uniform1i( this.addr, unit );
  10916. cache[ 0 ] = unit;
  10917. }
  10918. textures.setTexture3D( v || empty3dTexture, unit );
  10919. }
  10920. function setValueT6( gl, v, textures ) {
  10921. const cache = this.cache;
  10922. const unit = textures.allocateTextureUnit();
  10923. if ( cache[ 0 ] !== unit ) {
  10924. gl.uniform1i( this.addr, unit );
  10925. cache[ 0 ] = unit;
  10926. }
  10927. textures.setTextureCube( v || emptyCubeTexture, unit );
  10928. }
  10929. function setValueT2DArray1( gl, v, textures ) {
  10930. const cache = this.cache;
  10931. const unit = textures.allocateTextureUnit();
  10932. if ( cache[ 0 ] !== unit ) {
  10933. gl.uniform1i( this.addr, unit );
  10934. cache[ 0 ] = unit;
  10935. }
  10936. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10937. }
  10938. // Helper to pick the right setter for the singular case
  10939. function getSingularSetter( type ) {
  10940. switch ( type ) {
  10941. case 0x1406: return setValueV1f; // FLOAT
  10942. case 0x8b50: return setValueV2f; // _VEC2
  10943. case 0x8b51: return setValueV3f; // _VEC3
  10944. case 0x8b52: return setValueV4f; // _VEC4
  10945. case 0x8b5a: return setValueM2; // _MAT2
  10946. case 0x8b5b: return setValueM3; // _MAT3
  10947. case 0x8b5c: return setValueM4; // _MAT4
  10948. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10949. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10950. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10951. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10952. case 0x1405: return setValueV1ui; // UINT
  10953. case 0x8dc6: return setValueV2ui; // _VEC2
  10954. case 0x8dc7: return setValueV3ui; // _VEC3
  10955. case 0x8dc8: return setValueV4ui; // _VEC4
  10956. case 0x8b5e: // SAMPLER_2D
  10957. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10958. case 0x8dca: // INT_SAMPLER_2D
  10959. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10960. case 0x8b62: // SAMPLER_2D_SHADOW
  10961. return setValueT1;
  10962. case 0x8b5f: // SAMPLER_3D
  10963. case 0x8dcb: // INT_SAMPLER_3D
  10964. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10965. return setValueT3D1;
  10966. case 0x8b60: // SAMPLER_CUBE
  10967. case 0x8dcc: // INT_SAMPLER_CUBE
  10968. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10969. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10970. return setValueT6;
  10971. case 0x8dc1: // SAMPLER_2D_ARRAY
  10972. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10973. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10974. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10975. return setValueT2DArray1;
  10976. }
  10977. }
  10978. // Array of scalars
  10979. function setValueV1fArray( gl, v ) {
  10980. gl.uniform1fv( this.addr, v );
  10981. }
  10982. // Array of vectors (from flat array or array of THREE.VectorN)
  10983. function setValueV2fArray( gl, v ) {
  10984. const data = flatten( v, this.size, 2 );
  10985. gl.uniform2fv( this.addr, data );
  10986. }
  10987. function setValueV3fArray( gl, v ) {
  10988. const data = flatten( v, this.size, 3 );
  10989. gl.uniform3fv( this.addr, data );
  10990. }
  10991. function setValueV4fArray( gl, v ) {
  10992. const data = flatten( v, this.size, 4 );
  10993. gl.uniform4fv( this.addr, data );
  10994. }
  10995. // Array of matrices (from flat array or array of THREE.MatrixN)
  10996. function setValueM2Array( gl, v ) {
  10997. const data = flatten( v, this.size, 4 );
  10998. gl.uniformMatrix2fv( this.addr, false, data );
  10999. }
  11000. function setValueM3Array( gl, v ) {
  11001. const data = flatten( v, this.size, 9 );
  11002. gl.uniformMatrix3fv( this.addr, false, data );
  11003. }
  11004. function setValueM4Array( gl, v ) {
  11005. const data = flatten( v, this.size, 16 );
  11006. gl.uniformMatrix4fv( this.addr, false, data );
  11007. }
  11008. // Array of integer / boolean
  11009. function setValueV1iArray( gl, v ) {
  11010. gl.uniform1iv( this.addr, v );
  11011. }
  11012. // Array of integer / boolean vectors (from flat array)
  11013. function setValueV2iArray( gl, v ) {
  11014. gl.uniform2iv( this.addr, v );
  11015. }
  11016. function setValueV3iArray( gl, v ) {
  11017. gl.uniform3iv( this.addr, v );
  11018. }
  11019. function setValueV4iArray( gl, v ) {
  11020. gl.uniform4iv( this.addr, v );
  11021. }
  11022. // Array of unsigned integer
  11023. function setValueV1uiArray( gl, v ) {
  11024. gl.uniform1uiv( this.addr, v );
  11025. }
  11026. // Array of unsigned integer vectors (from flat array)
  11027. function setValueV2uiArray( gl, v ) {
  11028. gl.uniform2uiv( this.addr, v );
  11029. }
  11030. function setValueV3uiArray( gl, v ) {
  11031. gl.uniform3uiv( this.addr, v );
  11032. }
  11033. function setValueV4uiArray( gl, v ) {
  11034. gl.uniform4uiv( this.addr, v );
  11035. }
  11036. // Array of textures (2D / 3D / Cube / 2DArray)
  11037. function setValueT1Array( gl, v, textures ) {
  11038. const cache = this.cache;
  11039. const n = v.length;
  11040. const units = allocTexUnits( textures, n );
  11041. if ( ! arraysEqual( cache, units ) ) {
  11042. gl.uniform1iv( this.addr, units );
  11043. copyArray( cache, units );
  11044. }
  11045. for ( let i = 0; i !== n; ++ i ) {
  11046. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11047. }
  11048. }
  11049. function setValueT3DArray( gl, v, textures ) {
  11050. const cache = this.cache;
  11051. const n = v.length;
  11052. const units = allocTexUnits( textures, n );
  11053. if ( ! arraysEqual( cache, units ) ) {
  11054. gl.uniform1iv( this.addr, units );
  11055. copyArray( cache, units );
  11056. }
  11057. for ( let i = 0; i !== n; ++ i ) {
  11058. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11059. }
  11060. }
  11061. function setValueT6Array( gl, v, textures ) {
  11062. const cache = this.cache;
  11063. const n = v.length;
  11064. const units = allocTexUnits( textures, n );
  11065. if ( ! arraysEqual( cache, units ) ) {
  11066. gl.uniform1iv( this.addr, units );
  11067. copyArray( cache, units );
  11068. }
  11069. for ( let i = 0; i !== n; ++ i ) {
  11070. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11071. }
  11072. }
  11073. function setValueT2DArrayArray( gl, v, textures ) {
  11074. const cache = this.cache;
  11075. const n = v.length;
  11076. const units = allocTexUnits( textures, n );
  11077. if ( ! arraysEqual( cache, units ) ) {
  11078. gl.uniform1iv( this.addr, units );
  11079. copyArray( cache, units );
  11080. }
  11081. for ( let i = 0; i !== n; ++ i ) {
  11082. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11083. }
  11084. }
  11085. // Helper to pick the right setter for a pure (bottom-level) array
  11086. function getPureArraySetter( type ) {
  11087. switch ( type ) {
  11088. case 0x1406: return setValueV1fArray; // FLOAT
  11089. case 0x8b50: return setValueV2fArray; // _VEC2
  11090. case 0x8b51: return setValueV3fArray; // _VEC3
  11091. case 0x8b52: return setValueV4fArray; // _VEC4
  11092. case 0x8b5a: return setValueM2Array; // _MAT2
  11093. case 0x8b5b: return setValueM3Array; // _MAT3
  11094. case 0x8b5c: return setValueM4Array; // _MAT4
  11095. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11096. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11097. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11098. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11099. case 0x1405: return setValueV1uiArray; // UINT
  11100. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11101. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11102. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11103. case 0x8b5e: // SAMPLER_2D
  11104. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11105. case 0x8dca: // INT_SAMPLER_2D
  11106. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11107. case 0x8b62: // SAMPLER_2D_SHADOW
  11108. return setValueT1Array;
  11109. case 0x8b5f: // SAMPLER_3D
  11110. case 0x8dcb: // INT_SAMPLER_3D
  11111. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11112. return setValueT3DArray;
  11113. case 0x8b60: // SAMPLER_CUBE
  11114. case 0x8dcc: // INT_SAMPLER_CUBE
  11115. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11116. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11117. return setValueT6Array;
  11118. case 0x8dc1: // SAMPLER_2D_ARRAY
  11119. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11120. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11121. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11122. return setValueT2DArrayArray;
  11123. }
  11124. }
  11125. // --- Uniform Classes ---
  11126. class SingleUniform {
  11127. constructor( id, activeInfo, addr ) {
  11128. this.id = id;
  11129. this.addr = addr;
  11130. this.cache = [];
  11131. this.setValue = getSingularSetter( activeInfo.type );
  11132. // this.path = activeInfo.name; // DEBUG
  11133. }
  11134. }
  11135. class PureArrayUniform {
  11136. constructor( id, activeInfo, addr ) {
  11137. this.id = id;
  11138. this.addr = addr;
  11139. this.cache = [];
  11140. this.size = activeInfo.size;
  11141. this.setValue = getPureArraySetter( activeInfo.type );
  11142. // this.path = activeInfo.name; // DEBUG
  11143. }
  11144. }
  11145. class StructuredUniform {
  11146. constructor( id ) {
  11147. this.id = id;
  11148. this.seq = [];
  11149. this.map = {};
  11150. }
  11151. setValue( gl, value, textures ) {
  11152. const seq = this.seq;
  11153. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11154. const u = seq[ i ];
  11155. u.setValue( gl, value[ u.id ], textures );
  11156. }
  11157. }
  11158. }
  11159. // --- Top-level ---
  11160. // Parser - builds up the property tree from the path strings
  11161. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11162. // extracts
  11163. // - the identifier (member name or array index)
  11164. // - followed by an optional right bracket (found when array index)
  11165. // - followed by an optional left bracket or dot (type of subscript)
  11166. //
  11167. // Note: These portions can be read in a non-overlapping fashion and
  11168. // allow straightforward parsing of the hierarchy that WebGL encodes
  11169. // in the uniform names.
  11170. function addUniform( container, uniformObject ) {
  11171. container.seq.push( uniformObject );
  11172. container.map[ uniformObject.id ] = uniformObject;
  11173. }
  11174. function parseUniform( activeInfo, addr, container ) {
  11175. const path = activeInfo.name,
  11176. pathLength = path.length;
  11177. // reset RegExp object, because of the early exit of a previous run
  11178. RePathPart.lastIndex = 0;
  11179. while ( true ) {
  11180. const match = RePathPart.exec( path ),
  11181. matchEnd = RePathPart.lastIndex;
  11182. let id = match[ 1 ];
  11183. const idIsIndex = match[ 2 ] === ']',
  11184. subscript = match[ 3 ];
  11185. if ( idIsIndex ) id = id | 0; // convert to integer
  11186. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11187. // bare name or "pure" bottom-level array "[0]" suffix
  11188. addUniform( container, subscript === undefined ?
  11189. new SingleUniform( id, activeInfo, addr ) :
  11190. new PureArrayUniform( id, activeInfo, addr ) );
  11191. break;
  11192. } else {
  11193. // step into inner node / create it in case it doesn't exist
  11194. const map = container.map;
  11195. let next = map[ id ];
  11196. if ( next === undefined ) {
  11197. next = new StructuredUniform( id );
  11198. addUniform( container, next );
  11199. }
  11200. container = next;
  11201. }
  11202. }
  11203. }
  11204. // Root Container
  11205. class WebGLUniforms {
  11206. constructor( gl, program ) {
  11207. this.seq = [];
  11208. this.map = {};
  11209. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11210. for ( let i = 0; i < n; ++ i ) {
  11211. const info = gl.getActiveUniform( program, i ),
  11212. addr = gl.getUniformLocation( program, info.name );
  11213. parseUniform( info, addr, this );
  11214. }
  11215. }
  11216. setValue( gl, name, value, textures ) {
  11217. const u = this.map[ name ];
  11218. if ( u !== undefined ) u.setValue( gl, value, textures );
  11219. }
  11220. setOptional( gl, object, name ) {
  11221. const v = object[ name ];
  11222. if ( v !== undefined ) this.setValue( gl, name, v );
  11223. }
  11224. static upload( gl, seq, values, textures ) {
  11225. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11226. const u = seq[ i ],
  11227. v = values[ u.id ];
  11228. if ( v.needsUpdate !== false ) {
  11229. // note: always updating when .needsUpdate is undefined
  11230. u.setValue( gl, v.value, textures );
  11231. }
  11232. }
  11233. }
  11234. static seqWithValue( seq, values ) {
  11235. const r = [];
  11236. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11237. const u = seq[ i ];
  11238. if ( u.id in values ) r.push( u );
  11239. }
  11240. return r;
  11241. }
  11242. }
  11243. function WebGLShader( gl, type, string ) {
  11244. const shader = gl.createShader( type );
  11245. gl.shaderSource( shader, string );
  11246. gl.compileShader( shader );
  11247. return shader;
  11248. }
  11249. let programIdCount = 0;
  11250. function handleSource( string, errorLine ) {
  11251. const lines = string.split( '\n' );
  11252. const lines2 = [];
  11253. const from = Math.max( errorLine - 6, 0 );
  11254. const to = Math.min( errorLine + 6, lines.length );
  11255. for ( let i = from; i < to; i ++ ) {
  11256. const line = i + 1;
  11257. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11258. }
  11259. return lines2.join( '\n' );
  11260. }
  11261. function getEncodingComponents( colorSpace ) {
  11262. switch ( colorSpace ) {
  11263. case LinearSRGBColorSpace:
  11264. return [ 'Linear', '( value )' ];
  11265. case SRGBColorSpace:
  11266. return [ 'sRGB', '( value )' ];
  11267. default:
  11268. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11269. return [ 'Linear', '( value )' ];
  11270. }
  11271. }
  11272. function getShaderErrors( gl, shader, type ) {
  11273. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11274. const errors = gl.getShaderInfoLog( shader ).trim();
  11275. if ( status && errors === '' ) return '';
  11276. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11277. if ( errorMatches ) {
  11278. // --enable-privileged-webgl-extension
  11279. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11280. const errorLine = parseInt( errorMatches[ 1 ] );
  11281. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11282. } else {
  11283. return errors;
  11284. }
  11285. }
  11286. function getTexelEncodingFunction( functionName, colorSpace ) {
  11287. const components = getEncodingComponents( colorSpace );
  11288. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11289. }
  11290. function getToneMappingFunction( functionName, toneMapping ) {
  11291. let toneMappingName;
  11292. switch ( toneMapping ) {
  11293. case LinearToneMapping:
  11294. toneMappingName = 'Linear';
  11295. break;
  11296. case ReinhardToneMapping:
  11297. toneMappingName = 'Reinhard';
  11298. break;
  11299. case CineonToneMapping:
  11300. toneMappingName = 'OptimizedCineon';
  11301. break;
  11302. case ACESFilmicToneMapping:
  11303. toneMappingName = 'ACESFilmic';
  11304. break;
  11305. case CustomToneMapping:
  11306. toneMappingName = 'Custom';
  11307. break;
  11308. default:
  11309. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11310. toneMappingName = 'Linear';
  11311. }
  11312. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11313. }
  11314. function generateExtensions( parameters ) {
  11315. const chunks = [
  11316. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11317. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11318. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11319. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11320. ];
  11321. return chunks.filter( filterEmptyLine ).join( '\n' );
  11322. }
  11323. function generateDefines( defines ) {
  11324. const chunks = [];
  11325. for ( const name in defines ) {
  11326. const value = defines[ name ];
  11327. if ( value === false ) continue;
  11328. chunks.push( '#define ' + name + ' ' + value );
  11329. }
  11330. return chunks.join( '\n' );
  11331. }
  11332. function fetchAttributeLocations( gl, program ) {
  11333. const attributes = {};
  11334. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11335. for ( let i = 0; i < n; i ++ ) {
  11336. const info = gl.getActiveAttrib( program, i );
  11337. const name = info.name;
  11338. let locationSize = 1;
  11339. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11340. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11341. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11342. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11343. attributes[ name ] = {
  11344. type: info.type,
  11345. location: gl.getAttribLocation( program, name ),
  11346. locationSize: locationSize
  11347. };
  11348. }
  11349. return attributes;
  11350. }
  11351. function filterEmptyLine( string ) {
  11352. return string !== '';
  11353. }
  11354. function replaceLightNums( string, parameters ) {
  11355. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11356. return string
  11357. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11358. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11359. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11360. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11361. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11362. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11363. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11364. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11365. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11366. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11367. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11368. }
  11369. function replaceClippingPlaneNums( string, parameters ) {
  11370. return string
  11371. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11372. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11373. }
  11374. // Resolve Includes
  11375. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11376. function resolveIncludes( string ) {
  11377. return string.replace( includePattern, includeReplacer );
  11378. }
  11379. function includeReplacer( match, include ) {
  11380. const string = ShaderChunk[ include ];
  11381. if ( string === undefined ) {
  11382. throw new Error( 'Can not resolve #include <' + include + '>' );
  11383. }
  11384. return resolveIncludes( string );
  11385. }
  11386. // Unroll Loops
  11387. 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;
  11388. function unrollLoops( string ) {
  11389. return string.replace( unrollLoopPattern, loopReplacer );
  11390. }
  11391. function loopReplacer( match, start, end, snippet ) {
  11392. let string = '';
  11393. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11394. string += snippet
  11395. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11396. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11397. }
  11398. return string;
  11399. }
  11400. //
  11401. function generatePrecision( parameters ) {
  11402. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11403. if ( parameters.precision === 'highp' ) {
  11404. precisionstring += '\n#define HIGH_PRECISION';
  11405. } else if ( parameters.precision === 'mediump' ) {
  11406. precisionstring += '\n#define MEDIUM_PRECISION';
  11407. } else if ( parameters.precision === 'lowp' ) {
  11408. precisionstring += '\n#define LOW_PRECISION';
  11409. }
  11410. return precisionstring;
  11411. }
  11412. function generateShadowMapTypeDefine( parameters ) {
  11413. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11414. if ( parameters.shadowMapType === PCFShadowMap ) {
  11415. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11416. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11417. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11418. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11419. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11420. }
  11421. return shadowMapTypeDefine;
  11422. }
  11423. function generateEnvMapTypeDefine( parameters ) {
  11424. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11425. if ( parameters.envMap ) {
  11426. switch ( parameters.envMapMode ) {
  11427. case CubeReflectionMapping:
  11428. case CubeRefractionMapping:
  11429. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11430. break;
  11431. case CubeUVReflectionMapping:
  11432. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11433. break;
  11434. }
  11435. }
  11436. return envMapTypeDefine;
  11437. }
  11438. function generateEnvMapModeDefine( parameters ) {
  11439. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11440. if ( parameters.envMap ) {
  11441. switch ( parameters.envMapMode ) {
  11442. case CubeRefractionMapping:
  11443. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11444. break;
  11445. }
  11446. }
  11447. return envMapModeDefine;
  11448. }
  11449. function generateEnvMapBlendingDefine( parameters ) {
  11450. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11451. if ( parameters.envMap ) {
  11452. switch ( parameters.combine ) {
  11453. case MultiplyOperation:
  11454. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11455. break;
  11456. case MixOperation:
  11457. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11458. break;
  11459. case AddOperation:
  11460. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11461. break;
  11462. }
  11463. }
  11464. return envMapBlendingDefine;
  11465. }
  11466. function generateCubeUVSize( parameters ) {
  11467. const imageHeight = parameters.envMapCubeUVHeight;
  11468. if ( imageHeight === null ) return null;
  11469. const maxMip = Math.log2( imageHeight ) - 2;
  11470. const texelHeight = 1.0 / imageHeight;
  11471. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11472. return { texelWidth, texelHeight, maxMip };
  11473. }
  11474. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11475. // TODO Send this event to Three.js DevTools
  11476. // console.log( 'WebGLProgram', cacheKey );
  11477. const gl = renderer.getContext();
  11478. const defines = parameters.defines;
  11479. let vertexShader = parameters.vertexShader;
  11480. let fragmentShader = parameters.fragmentShader;
  11481. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11482. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11483. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11484. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11485. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11486. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11487. const customDefines = generateDefines( defines );
  11488. const program = gl.createProgram();
  11489. let prefixVertex, prefixFragment;
  11490. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11491. if ( parameters.isRawShaderMaterial ) {
  11492. prefixVertex = [
  11493. customDefines
  11494. ].filter( filterEmptyLine ).join( '\n' );
  11495. if ( prefixVertex.length > 0 ) {
  11496. prefixVertex += '\n';
  11497. }
  11498. prefixFragment = [
  11499. customExtensions,
  11500. customDefines
  11501. ].filter( filterEmptyLine ).join( '\n' );
  11502. if ( prefixFragment.length > 0 ) {
  11503. prefixFragment += '\n';
  11504. }
  11505. } else {
  11506. prefixVertex = [
  11507. generatePrecision( parameters ),
  11508. '#define SHADER_NAME ' + parameters.shaderName,
  11509. customDefines,
  11510. parameters.instancing ? '#define USE_INSTANCING' : '',
  11511. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11512. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11513. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11514. parameters.map ? '#define USE_MAP' : '',
  11515. parameters.envMap ? '#define USE_ENVMAP' : '',
  11516. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11517. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11518. parameters.aoMap ? '#define USE_AOMAP' : '',
  11519. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11520. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11521. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11522. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11523. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11524. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11525. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11526. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11527. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11528. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11529. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11530. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11531. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11532. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11533. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11534. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11535. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11536. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11537. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11538. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11539. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11540. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11541. //
  11542. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11543. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11544. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11545. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11546. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11547. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11548. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11549. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11550. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11551. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11552. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11553. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11554. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11555. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11556. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11557. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11558. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11559. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11560. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11561. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11562. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11563. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11564. //
  11565. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11566. parameters.vertexColors ? '#define USE_COLOR' : '',
  11567. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11568. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11569. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11570. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11571. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11572. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11573. parameters.skinning ? '#define USE_SKINNING' : '',
  11574. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11575. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11576. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11577. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11578. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11579. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11580. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11581. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11582. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11583. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11584. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11585. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11586. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11587. 'uniform mat4 modelMatrix;',
  11588. 'uniform mat4 modelViewMatrix;',
  11589. 'uniform mat4 projectionMatrix;',
  11590. 'uniform mat4 viewMatrix;',
  11591. 'uniform mat3 normalMatrix;',
  11592. 'uniform vec3 cameraPosition;',
  11593. 'uniform bool isOrthographic;',
  11594. '#ifdef USE_INSTANCING',
  11595. ' attribute mat4 instanceMatrix;',
  11596. '#endif',
  11597. '#ifdef USE_INSTANCING_COLOR',
  11598. ' attribute vec3 instanceColor;',
  11599. '#endif',
  11600. 'attribute vec3 position;',
  11601. 'attribute vec3 normal;',
  11602. 'attribute vec2 uv;',
  11603. '#ifdef USE_UV1',
  11604. ' attribute vec2 uv1;',
  11605. '#endif',
  11606. '#ifdef USE_UV2',
  11607. ' attribute vec2 uv2;',
  11608. '#endif',
  11609. '#ifdef USE_UV3',
  11610. ' attribute vec2 uv3;',
  11611. '#endif',
  11612. '#ifdef USE_TANGENT',
  11613. ' attribute vec4 tangent;',
  11614. '#endif',
  11615. '#if defined( USE_COLOR_ALPHA )',
  11616. ' attribute vec4 color;',
  11617. '#elif defined( USE_COLOR )',
  11618. ' attribute vec3 color;',
  11619. '#endif',
  11620. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11621. ' attribute vec3 morphTarget0;',
  11622. ' attribute vec3 morphTarget1;',
  11623. ' attribute vec3 morphTarget2;',
  11624. ' attribute vec3 morphTarget3;',
  11625. ' #ifdef USE_MORPHNORMALS',
  11626. ' attribute vec3 morphNormal0;',
  11627. ' attribute vec3 morphNormal1;',
  11628. ' attribute vec3 morphNormal2;',
  11629. ' attribute vec3 morphNormal3;',
  11630. ' #else',
  11631. ' attribute vec3 morphTarget4;',
  11632. ' attribute vec3 morphTarget5;',
  11633. ' attribute vec3 morphTarget6;',
  11634. ' attribute vec3 morphTarget7;',
  11635. ' #endif',
  11636. '#endif',
  11637. '#ifdef USE_SKINNING',
  11638. ' attribute vec4 skinIndex;',
  11639. ' attribute vec4 skinWeight;',
  11640. '#endif',
  11641. '\n'
  11642. ].filter( filterEmptyLine ).join( '\n' );
  11643. prefixFragment = [
  11644. customExtensions,
  11645. generatePrecision( parameters ),
  11646. '#define SHADER_NAME ' + parameters.shaderName,
  11647. customDefines,
  11648. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11649. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11650. parameters.map ? '#define USE_MAP' : '',
  11651. parameters.matcap ? '#define USE_MATCAP' : '',
  11652. parameters.envMap ? '#define USE_ENVMAP' : '',
  11653. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11654. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11655. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11656. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11657. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11658. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11659. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11660. parameters.aoMap ? '#define USE_AOMAP' : '',
  11661. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11662. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11663. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11664. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11665. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11666. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11667. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11668. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11669. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11670. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11671. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11672. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11673. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11674. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11675. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11676. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11677. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11678. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11679. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11680. parameters.sheen ? '#define USE_SHEEN' : '',
  11681. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11682. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11683. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11684. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11685. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11686. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11687. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11688. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11689. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11690. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11691. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11692. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11693. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11694. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11695. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11696. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11697. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11698. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11699. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11700. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11701. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11702. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11703. 'uniform mat4 viewMatrix;',
  11704. 'uniform vec3 cameraPosition;',
  11705. 'uniform bool isOrthographic;',
  11706. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11707. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11708. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11709. parameters.dithering ? '#define DITHERING' : '',
  11710. parameters.opaque ? '#define OPAQUE' : '',
  11711. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11712. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  11713. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11714. '\n'
  11715. ].filter( filterEmptyLine ).join( '\n' );
  11716. }
  11717. vertexShader = resolveIncludes( vertexShader );
  11718. vertexShader = replaceLightNums( vertexShader, parameters );
  11719. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11720. fragmentShader = resolveIncludes( fragmentShader );
  11721. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11722. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11723. vertexShader = unrollLoops( vertexShader );
  11724. fragmentShader = unrollLoops( fragmentShader );
  11725. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11726. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11727. versionString = '#version 300 es\n';
  11728. prefixVertex = [
  11729. 'precision mediump sampler2DArray;',
  11730. '#define attribute in',
  11731. '#define varying out',
  11732. '#define texture2D texture'
  11733. ].join( '\n' ) + '\n' + prefixVertex;
  11734. prefixFragment = [
  11735. '#define varying in',
  11736. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11737. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11738. '#define gl_FragDepthEXT gl_FragDepth',
  11739. '#define texture2D texture',
  11740. '#define textureCube texture',
  11741. '#define texture2DProj textureProj',
  11742. '#define texture2DLodEXT textureLod',
  11743. '#define texture2DProjLodEXT textureProjLod',
  11744. '#define textureCubeLodEXT textureLod',
  11745. '#define texture2DGradEXT textureGrad',
  11746. '#define texture2DProjGradEXT textureProjGrad',
  11747. '#define textureCubeGradEXT textureGrad'
  11748. ].join( '\n' ) + '\n' + prefixFragment;
  11749. }
  11750. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11751. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11752. // console.log( '*VERTEX*', vertexGlsl );
  11753. // console.log( '*FRAGMENT*', fragmentGlsl );
  11754. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11755. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11756. gl.attachShader( program, glVertexShader );
  11757. gl.attachShader( program, glFragmentShader );
  11758. // Force a particular attribute to index 0.
  11759. if ( parameters.index0AttributeName !== undefined ) {
  11760. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11761. } else if ( parameters.morphTargets === true ) {
  11762. // programs with morphTargets displace position out of attribute 0
  11763. gl.bindAttribLocation( program, 0, 'position' );
  11764. }
  11765. gl.linkProgram( program );
  11766. // check for link errors
  11767. if ( renderer.debug.checkShaderErrors ) {
  11768. const programLog = gl.getProgramInfoLog( program ).trim();
  11769. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11770. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11771. let runnable = true;
  11772. let haveDiagnostics = true;
  11773. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11774. runnable = false;
  11775. if ( typeof renderer.debug.onShaderError === 'function' ) {
  11776. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  11777. } else {
  11778. // default error reporting
  11779. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11780. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11781. console.error(
  11782. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11783. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11784. 'Program Info Log: ' + programLog + '\n' +
  11785. vertexErrors + '\n' +
  11786. fragmentErrors
  11787. );
  11788. }
  11789. } else if ( programLog !== '' ) {
  11790. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11791. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11792. haveDiagnostics = false;
  11793. }
  11794. if ( haveDiagnostics ) {
  11795. this.diagnostics = {
  11796. runnable: runnable,
  11797. programLog: programLog,
  11798. vertexShader: {
  11799. log: vertexLog,
  11800. prefix: prefixVertex
  11801. },
  11802. fragmentShader: {
  11803. log: fragmentLog,
  11804. prefix: prefixFragment
  11805. }
  11806. };
  11807. }
  11808. }
  11809. // Clean up
  11810. // Crashes in iOS9 and iOS10. #18402
  11811. // gl.detachShader( program, glVertexShader );
  11812. // gl.detachShader( program, glFragmentShader );
  11813. gl.deleteShader( glVertexShader );
  11814. gl.deleteShader( glFragmentShader );
  11815. // set up caching for uniform locations
  11816. let cachedUniforms;
  11817. this.getUniforms = function () {
  11818. if ( cachedUniforms === undefined ) {
  11819. cachedUniforms = new WebGLUniforms( gl, program );
  11820. }
  11821. return cachedUniforms;
  11822. };
  11823. // set up caching for attribute locations
  11824. let cachedAttributes;
  11825. this.getAttributes = function () {
  11826. if ( cachedAttributes === undefined ) {
  11827. cachedAttributes = fetchAttributeLocations( gl, program );
  11828. }
  11829. return cachedAttributes;
  11830. };
  11831. // free resource
  11832. this.destroy = function () {
  11833. bindingStates.releaseStatesOfProgram( this );
  11834. gl.deleteProgram( program );
  11835. this.program = undefined;
  11836. };
  11837. //
  11838. this.name = parameters.shaderName;
  11839. this.id = programIdCount ++;
  11840. this.cacheKey = cacheKey;
  11841. this.usedTimes = 1;
  11842. this.program = program;
  11843. this.vertexShader = glVertexShader;
  11844. this.fragmentShader = glFragmentShader;
  11845. return this;
  11846. }
  11847. let _id = 0;
  11848. class WebGLShaderCache {
  11849. constructor() {
  11850. this.shaderCache = new Map();
  11851. this.materialCache = new Map();
  11852. }
  11853. update( material ) {
  11854. const vertexShader = material.vertexShader;
  11855. const fragmentShader = material.fragmentShader;
  11856. const vertexShaderStage = this._getShaderStage( vertexShader );
  11857. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11858. const materialShaders = this._getShaderCacheForMaterial( material );
  11859. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11860. materialShaders.add( vertexShaderStage );
  11861. vertexShaderStage.usedTimes ++;
  11862. }
  11863. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11864. materialShaders.add( fragmentShaderStage );
  11865. fragmentShaderStage.usedTimes ++;
  11866. }
  11867. return this;
  11868. }
  11869. remove( material ) {
  11870. const materialShaders = this.materialCache.get( material );
  11871. for ( const shaderStage of materialShaders ) {
  11872. shaderStage.usedTimes --;
  11873. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11874. }
  11875. this.materialCache.delete( material );
  11876. return this;
  11877. }
  11878. getVertexShaderID( material ) {
  11879. return this._getShaderStage( material.vertexShader ).id;
  11880. }
  11881. getFragmentShaderID( material ) {
  11882. return this._getShaderStage( material.fragmentShader ).id;
  11883. }
  11884. dispose() {
  11885. this.shaderCache.clear();
  11886. this.materialCache.clear();
  11887. }
  11888. _getShaderCacheForMaterial( material ) {
  11889. const cache = this.materialCache;
  11890. let set = cache.get( material );
  11891. if ( set === undefined ) {
  11892. set = new Set();
  11893. cache.set( material, set );
  11894. }
  11895. return set;
  11896. }
  11897. _getShaderStage( code ) {
  11898. const cache = this.shaderCache;
  11899. let stage = cache.get( code );
  11900. if ( stage === undefined ) {
  11901. stage = new WebGLShaderStage( code );
  11902. cache.set( code, stage );
  11903. }
  11904. return stage;
  11905. }
  11906. }
  11907. class WebGLShaderStage {
  11908. constructor( code ) {
  11909. this.id = _id ++;
  11910. this.code = code;
  11911. this.usedTimes = 0;
  11912. }
  11913. }
  11914. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11915. const _programLayers = new Layers();
  11916. const _customShaders = new WebGLShaderCache();
  11917. const programs = [];
  11918. const IS_WEBGL2 = capabilities.isWebGL2;
  11919. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11920. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  11921. let precision = capabilities.precision;
  11922. const shaderIDs = {
  11923. MeshDepthMaterial: 'depth',
  11924. MeshDistanceMaterial: 'distanceRGBA',
  11925. MeshNormalMaterial: 'normal',
  11926. MeshBasicMaterial: 'basic',
  11927. MeshLambertMaterial: 'lambert',
  11928. MeshPhongMaterial: 'phong',
  11929. MeshToonMaterial: 'toon',
  11930. MeshStandardMaterial: 'physical',
  11931. MeshPhysicalMaterial: 'physical',
  11932. MeshMatcapMaterial: 'matcap',
  11933. LineBasicMaterial: 'basic',
  11934. LineDashedMaterial: 'dashed',
  11935. PointsMaterial: 'points',
  11936. ShadowMaterial: 'shadow',
  11937. SpriteMaterial: 'sprite'
  11938. };
  11939. function getChannel( value ) {
  11940. if ( value === 1 ) return 'uv1';
  11941. if ( value === 2 ) return 'uv2';
  11942. if ( value === 3 ) return 'uv3';
  11943. return 'uv';
  11944. }
  11945. function getParameters( material, lights, shadows, scene, object ) {
  11946. const fog = scene.fog;
  11947. const geometry = object.geometry;
  11948. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11949. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11950. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11951. const shaderID = shaderIDs[ material.type ];
  11952. // heuristics to create shader parameters according to lights in the scene
  11953. // (not to blow over maxLights budget)
  11954. if ( material.precision !== null ) {
  11955. precision = capabilities.getMaxPrecision( material.precision );
  11956. if ( precision !== material.precision ) {
  11957. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11958. }
  11959. }
  11960. //
  11961. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11962. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11963. let morphTextureStride = 0;
  11964. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11965. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11966. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11967. //
  11968. let vertexShader, fragmentShader;
  11969. let customVertexShaderID, customFragmentShaderID;
  11970. if ( shaderID ) {
  11971. const shader = ShaderLib[ shaderID ];
  11972. vertexShader = shader.vertexShader;
  11973. fragmentShader = shader.fragmentShader;
  11974. } else {
  11975. vertexShader = material.vertexShader;
  11976. fragmentShader = material.fragmentShader;
  11977. _customShaders.update( material );
  11978. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11979. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11980. }
  11981. const currentRenderTarget = renderer.getRenderTarget();
  11982. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  11983. const HAS_MAP = !! material.map;
  11984. const HAS_MATCAP = !! material.matcap;
  11985. const HAS_ENVMAP = !! envMap;
  11986. const HAS_AOMAP = !! material.aoMap;
  11987. const HAS_LIGHTMAP = !! material.lightMap;
  11988. const HAS_BUMPMAP = !! material.bumpMap;
  11989. const HAS_NORMALMAP = !! material.normalMap;
  11990. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  11991. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  11992. const HAS_METALNESSMAP = !! material.metalnessMap;
  11993. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  11994. const HAS_CLEARCOAT = material.clearcoat > 0;
  11995. const HAS_IRIDESCENCE = material.iridescence > 0;
  11996. const HAS_SHEEN = material.sheen > 0;
  11997. const HAS_TRANSMISSION = material.transmission > 0;
  11998. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  11999. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12000. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12001. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12002. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12003. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12004. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12005. const HAS_SPECULARMAP = !! material.specularMap;
  12006. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12007. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12008. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12009. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12010. const HAS_GRADIENTMAP = !! material.gradientMap;
  12011. const HAS_ALPHAMAP = !! material.alphaMap;
  12012. const HAS_ALPHATEST = material.alphaTest > 0;
  12013. const HAS_EXTENSIONS = !! material.extensions;
  12014. const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1;
  12015. const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;
  12016. const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3;
  12017. const parameters = {
  12018. isWebGL2: IS_WEBGL2,
  12019. shaderID: shaderID,
  12020. shaderName: material.type,
  12021. vertexShader: vertexShader,
  12022. fragmentShader: fragmentShader,
  12023. defines: material.defines,
  12024. customVertexShaderID: customVertexShaderID,
  12025. customFragmentShaderID: customFragmentShaderID,
  12026. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12027. glslVersion: material.glslVersion,
  12028. precision: precision,
  12029. instancing: IS_INSTANCEDMESH,
  12030. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12031. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12032. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12033. map: HAS_MAP,
  12034. matcap: HAS_MATCAP,
  12035. envMap: HAS_ENVMAP,
  12036. envMapMode: HAS_ENVMAP && envMap.mapping,
  12037. envMapCubeUVHeight: envMapCubeUVHeight,
  12038. aoMap: HAS_AOMAP,
  12039. lightMap: HAS_LIGHTMAP,
  12040. bumpMap: HAS_BUMPMAP,
  12041. normalMap: HAS_NORMALMAP,
  12042. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12043. emissiveMap: HAS_EMISSIVEMAP,
  12044. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12045. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12046. metalnessMap: HAS_METALNESSMAP,
  12047. roughnessMap: HAS_ROUGHNESSMAP,
  12048. clearcoat: HAS_CLEARCOAT,
  12049. clearcoatMap: HAS_CLEARCOATMAP,
  12050. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12051. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12052. iridescence: HAS_IRIDESCENCE,
  12053. iridescenceMap: HAS_IRIDESCENCEMAP,
  12054. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12055. sheen: HAS_SHEEN,
  12056. sheenColorMap: HAS_SHEEN_COLORMAP,
  12057. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12058. specularMap: HAS_SPECULARMAP,
  12059. specularColorMap: HAS_SPECULAR_COLORMAP,
  12060. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12061. transmission: HAS_TRANSMISSION,
  12062. transmissionMap: HAS_TRANSMISSIONMAP,
  12063. thicknessMap: HAS_THICKNESSMAP,
  12064. gradientMap: HAS_GRADIENTMAP,
  12065. opaque: material.transparent === false && material.blending === NormalBlending,
  12066. alphaMap: HAS_ALPHAMAP,
  12067. alphaTest: HAS_ALPHATEST,
  12068. combine: material.combine,
  12069. //
  12070. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12071. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12072. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12073. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12074. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12075. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12076. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12077. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12078. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12079. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12080. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12081. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12082. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12083. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12084. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12085. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12086. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12087. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12088. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12089. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12090. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12091. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12092. //
  12093. vertexTangents: HAS_NORMALMAP && !! geometry.attributes.tangent,
  12094. vertexColors: material.vertexColors,
  12095. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12096. vertexUv1s: HAS_ATTRIBUTE_UV1,
  12097. vertexUv2s: HAS_ATTRIBUTE_UV2,
  12098. vertexUv3s: HAS_ATTRIBUTE_UV3,
  12099. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12100. fog: !! fog,
  12101. useFog: material.fog === true,
  12102. fogExp2: ( fog && fog.isFogExp2 ),
  12103. flatShading: material.flatShading === true,
  12104. sizeAttenuation: material.sizeAttenuation === true,
  12105. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12106. skinning: object.isSkinnedMesh === true,
  12107. morphTargets: geometry.morphAttributes.position !== undefined,
  12108. morphNormals: geometry.morphAttributes.normal !== undefined,
  12109. morphColors: geometry.morphAttributes.color !== undefined,
  12110. morphTargetsCount: morphTargetsCount,
  12111. morphTextureStride: morphTextureStride,
  12112. numDirLights: lights.directional.length,
  12113. numPointLights: lights.point.length,
  12114. numSpotLights: lights.spot.length,
  12115. numSpotLightMaps: lights.spotLightMap.length,
  12116. numRectAreaLights: lights.rectArea.length,
  12117. numHemiLights: lights.hemi.length,
  12118. numDirLightShadows: lights.directionalShadowMap.length,
  12119. numPointLightShadows: lights.pointShadowMap.length,
  12120. numSpotLightShadows: lights.spotShadowMap.length,
  12121. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12122. numClippingPlanes: clipping.numPlanes,
  12123. numClipIntersection: clipping.numIntersection,
  12124. dithering: material.dithering,
  12125. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12126. shadowMapType: renderer.shadowMap.type,
  12127. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12128. useLegacyLights: renderer.useLegacyLights,
  12129. premultipliedAlpha: material.premultipliedAlpha,
  12130. doubleSided: material.side === DoubleSide,
  12131. flipSided: material.side === BackSide,
  12132. useDepthPacking: material.depthPacking >= 0,
  12133. depthPacking: material.depthPacking || 0,
  12134. index0AttributeName: material.index0AttributeName,
  12135. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12136. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12137. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12138. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12139. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12140. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12141. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12142. customProgramCacheKey: material.customProgramCacheKey()
  12143. };
  12144. return parameters;
  12145. }
  12146. function getProgramCacheKey( parameters ) {
  12147. const array = [];
  12148. if ( parameters.shaderID ) {
  12149. array.push( parameters.shaderID );
  12150. } else {
  12151. array.push( parameters.customVertexShaderID );
  12152. array.push( parameters.customFragmentShaderID );
  12153. }
  12154. if ( parameters.defines !== undefined ) {
  12155. for ( const name in parameters.defines ) {
  12156. array.push( name );
  12157. array.push( parameters.defines[ name ] );
  12158. }
  12159. }
  12160. if ( parameters.isRawShaderMaterial === false ) {
  12161. getProgramCacheKeyParameters( array, parameters );
  12162. getProgramCacheKeyBooleans( array, parameters );
  12163. array.push( renderer.outputColorSpace );
  12164. }
  12165. array.push( parameters.customProgramCacheKey );
  12166. return array.join();
  12167. }
  12168. function getProgramCacheKeyParameters( array, parameters ) {
  12169. array.push( parameters.precision );
  12170. array.push( parameters.outputColorSpace );
  12171. array.push( parameters.envMapMode );
  12172. array.push( parameters.envMapCubeUVHeight );
  12173. array.push( parameters.mapUv );
  12174. array.push( parameters.alphaMapUv );
  12175. array.push( parameters.lightMapUv );
  12176. array.push( parameters.aoMapUv );
  12177. array.push( parameters.bumpMapUv );
  12178. array.push( parameters.normalMapUv );
  12179. array.push( parameters.displacementMapUv );
  12180. array.push( parameters.emissiveMapUv );
  12181. array.push( parameters.metalnessMapUv );
  12182. array.push( parameters.roughnessMapUv );
  12183. array.push( parameters.clearcoatMapUv );
  12184. array.push( parameters.clearcoatNormalMapUv );
  12185. array.push( parameters.clearcoatRoughnessMapUv );
  12186. array.push( parameters.iridescenceMapUv );
  12187. array.push( parameters.iridescenceThicknessMapUv );
  12188. array.push( parameters.sheenColorMapUv );
  12189. array.push( parameters.sheenRoughnessMapUv );
  12190. array.push( parameters.specularMapUv );
  12191. array.push( parameters.specularColorMapUv );
  12192. array.push( parameters.specularIntensityMapUv );
  12193. array.push( parameters.transmissionMapUv );
  12194. array.push( parameters.thicknessMapUv );
  12195. array.push( parameters.combine );
  12196. array.push( parameters.fogExp2 );
  12197. array.push( parameters.sizeAttenuation );
  12198. array.push( parameters.morphTargetsCount );
  12199. array.push( parameters.morphAttributeCount );
  12200. array.push( parameters.numDirLights );
  12201. array.push( parameters.numPointLights );
  12202. array.push( parameters.numSpotLights );
  12203. array.push( parameters.numSpotLightMaps );
  12204. array.push( parameters.numHemiLights );
  12205. array.push( parameters.numRectAreaLights );
  12206. array.push( parameters.numDirLightShadows );
  12207. array.push( parameters.numPointLightShadows );
  12208. array.push( parameters.numSpotLightShadows );
  12209. array.push( parameters.numSpotLightShadowsWithMaps );
  12210. array.push( parameters.shadowMapType );
  12211. array.push( parameters.toneMapping );
  12212. array.push( parameters.numClippingPlanes );
  12213. array.push( parameters.numClipIntersection );
  12214. array.push( parameters.depthPacking );
  12215. }
  12216. function getProgramCacheKeyBooleans( array, parameters ) {
  12217. _programLayers.disableAll();
  12218. if ( parameters.isWebGL2 )
  12219. _programLayers.enable( 0 );
  12220. if ( parameters.supportsVertexTextures )
  12221. _programLayers.enable( 1 );
  12222. if ( parameters.instancing )
  12223. _programLayers.enable( 2 );
  12224. if ( parameters.instancingColor )
  12225. _programLayers.enable( 3 );
  12226. if ( parameters.matcap )
  12227. _programLayers.enable( 4 );
  12228. if ( parameters.envMap )
  12229. _programLayers.enable( 5 );
  12230. if ( parameters.normalMapObjectSpace )
  12231. _programLayers.enable( 6 );
  12232. if ( parameters.normalMapTangentSpace )
  12233. _programLayers.enable( 7 );
  12234. if ( parameters.clearcoat )
  12235. _programLayers.enable( 8 );
  12236. if ( parameters.iridescence )
  12237. _programLayers.enable( 9 );
  12238. if ( parameters.alphaTest )
  12239. _programLayers.enable( 10 );
  12240. if ( parameters.vertexColors )
  12241. _programLayers.enable( 11 );
  12242. if ( parameters.vertexAlphas )
  12243. _programLayers.enable( 12 );
  12244. if ( parameters.vertexUv1s )
  12245. _programLayers.enable( 13 );
  12246. if ( parameters.vertexUv2s )
  12247. _programLayers.enable( 14 );
  12248. if ( parameters.vertexUv3s )
  12249. _programLayers.enable( 15 );
  12250. if ( parameters.vertexTangents )
  12251. _programLayers.enable( 16 );
  12252. array.push( _programLayers.mask );
  12253. _programLayers.disableAll();
  12254. if ( parameters.fog )
  12255. _programLayers.enable( 0 );
  12256. if ( parameters.useFog )
  12257. _programLayers.enable( 1 );
  12258. if ( parameters.flatShading )
  12259. _programLayers.enable( 2 );
  12260. if ( parameters.logarithmicDepthBuffer )
  12261. _programLayers.enable( 3 );
  12262. if ( parameters.skinning )
  12263. _programLayers.enable( 4 );
  12264. if ( parameters.morphTargets )
  12265. _programLayers.enable( 5 );
  12266. if ( parameters.morphNormals )
  12267. _programLayers.enable( 6 );
  12268. if ( parameters.morphColors )
  12269. _programLayers.enable( 7 );
  12270. if ( parameters.premultipliedAlpha )
  12271. _programLayers.enable( 8 );
  12272. if ( parameters.shadowMapEnabled )
  12273. _programLayers.enable( 9 );
  12274. if ( parameters.useLegacyLights )
  12275. _programLayers.enable( 10 );
  12276. if ( parameters.doubleSided )
  12277. _programLayers.enable( 11 );
  12278. if ( parameters.flipSided )
  12279. _programLayers.enable( 12 );
  12280. if ( parameters.useDepthPacking )
  12281. _programLayers.enable( 13 );
  12282. if ( parameters.dithering )
  12283. _programLayers.enable( 14 );
  12284. if ( parameters.transmission )
  12285. _programLayers.enable( 15 );
  12286. if ( parameters.sheen )
  12287. _programLayers.enable( 16 );
  12288. if ( parameters.opaque )
  12289. _programLayers.enable( 17 );
  12290. if ( parameters.pointsUvs )
  12291. _programLayers.enable( 18 );
  12292. array.push( _programLayers.mask );
  12293. }
  12294. function getUniforms( material ) {
  12295. const shaderID = shaderIDs[ material.type ];
  12296. let uniforms;
  12297. if ( shaderID ) {
  12298. const shader = ShaderLib[ shaderID ];
  12299. uniforms = UniformsUtils.clone( shader.uniforms );
  12300. } else {
  12301. uniforms = material.uniforms;
  12302. }
  12303. return uniforms;
  12304. }
  12305. function acquireProgram( parameters, cacheKey ) {
  12306. let program;
  12307. // Check if code has been already compiled
  12308. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12309. const preexistingProgram = programs[ p ];
  12310. if ( preexistingProgram.cacheKey === cacheKey ) {
  12311. program = preexistingProgram;
  12312. ++ program.usedTimes;
  12313. break;
  12314. }
  12315. }
  12316. if ( program === undefined ) {
  12317. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12318. programs.push( program );
  12319. }
  12320. return program;
  12321. }
  12322. function releaseProgram( program ) {
  12323. if ( -- program.usedTimes === 0 ) {
  12324. // Remove from unordered set
  12325. const i = programs.indexOf( program );
  12326. programs[ i ] = programs[ programs.length - 1 ];
  12327. programs.pop();
  12328. // Free WebGL resources
  12329. program.destroy();
  12330. }
  12331. }
  12332. function releaseShaderCache( material ) {
  12333. _customShaders.remove( material );
  12334. }
  12335. function dispose() {
  12336. _customShaders.dispose();
  12337. }
  12338. return {
  12339. getParameters: getParameters,
  12340. getProgramCacheKey: getProgramCacheKey,
  12341. getUniforms: getUniforms,
  12342. acquireProgram: acquireProgram,
  12343. releaseProgram: releaseProgram,
  12344. releaseShaderCache: releaseShaderCache,
  12345. // Exposed for resource monitoring & error feedback via renderer.info:
  12346. programs: programs,
  12347. dispose: dispose
  12348. };
  12349. }
  12350. function WebGLProperties() {
  12351. let properties = new WeakMap();
  12352. function get( object ) {
  12353. let map = properties.get( object );
  12354. if ( map === undefined ) {
  12355. map = {};
  12356. properties.set( object, map );
  12357. }
  12358. return map;
  12359. }
  12360. function remove( object ) {
  12361. properties.delete( object );
  12362. }
  12363. function update( object, key, value ) {
  12364. properties.get( object )[ key ] = value;
  12365. }
  12366. function dispose() {
  12367. properties = new WeakMap();
  12368. }
  12369. return {
  12370. get: get,
  12371. remove: remove,
  12372. update: update,
  12373. dispose: dispose
  12374. };
  12375. }
  12376. function painterSortStable( a, b ) {
  12377. if ( a.groupOrder !== b.groupOrder ) {
  12378. return a.groupOrder - b.groupOrder;
  12379. } else if ( a.renderOrder !== b.renderOrder ) {
  12380. return a.renderOrder - b.renderOrder;
  12381. } else if ( a.material.id !== b.material.id ) {
  12382. return a.material.id - b.material.id;
  12383. } else if ( a.z !== b.z ) {
  12384. return a.z - b.z;
  12385. } else {
  12386. return a.id - b.id;
  12387. }
  12388. }
  12389. function reversePainterSortStable( a, b ) {
  12390. if ( a.groupOrder !== b.groupOrder ) {
  12391. return a.groupOrder - b.groupOrder;
  12392. } else if ( a.renderOrder !== b.renderOrder ) {
  12393. return a.renderOrder - b.renderOrder;
  12394. } else if ( a.z !== b.z ) {
  12395. return b.z - a.z;
  12396. } else {
  12397. return a.id - b.id;
  12398. }
  12399. }
  12400. function WebGLRenderList() {
  12401. const renderItems = [];
  12402. let renderItemsIndex = 0;
  12403. const opaque = [];
  12404. const transmissive = [];
  12405. const transparent = [];
  12406. function init() {
  12407. renderItemsIndex = 0;
  12408. opaque.length = 0;
  12409. transmissive.length = 0;
  12410. transparent.length = 0;
  12411. }
  12412. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12413. let renderItem = renderItems[ renderItemsIndex ];
  12414. if ( renderItem === undefined ) {
  12415. renderItem = {
  12416. id: object.id,
  12417. object: object,
  12418. geometry: geometry,
  12419. material: material,
  12420. groupOrder: groupOrder,
  12421. renderOrder: object.renderOrder,
  12422. z: z,
  12423. group: group
  12424. };
  12425. renderItems[ renderItemsIndex ] = renderItem;
  12426. } else {
  12427. renderItem.id = object.id;
  12428. renderItem.object = object;
  12429. renderItem.geometry = geometry;
  12430. renderItem.material = material;
  12431. renderItem.groupOrder = groupOrder;
  12432. renderItem.renderOrder = object.renderOrder;
  12433. renderItem.z = z;
  12434. renderItem.group = group;
  12435. }
  12436. renderItemsIndex ++;
  12437. return renderItem;
  12438. }
  12439. function push( object, geometry, material, groupOrder, z, group ) {
  12440. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12441. if ( material.transmission > 0.0 ) {
  12442. transmissive.push( renderItem );
  12443. } else if ( material.transparent === true ) {
  12444. transparent.push( renderItem );
  12445. } else {
  12446. opaque.push( renderItem );
  12447. }
  12448. }
  12449. function unshift( object, geometry, material, groupOrder, z, group ) {
  12450. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12451. if ( material.transmission > 0.0 ) {
  12452. transmissive.unshift( renderItem );
  12453. } else if ( material.transparent === true ) {
  12454. transparent.unshift( renderItem );
  12455. } else {
  12456. opaque.unshift( renderItem );
  12457. }
  12458. }
  12459. function sort( customOpaqueSort, customTransparentSort ) {
  12460. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12461. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12462. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12463. }
  12464. function finish() {
  12465. // Clear references from inactive renderItems in the list
  12466. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12467. const renderItem = renderItems[ i ];
  12468. if ( renderItem.id === null ) break;
  12469. renderItem.id = null;
  12470. renderItem.object = null;
  12471. renderItem.geometry = null;
  12472. renderItem.material = null;
  12473. renderItem.group = null;
  12474. }
  12475. }
  12476. return {
  12477. opaque: opaque,
  12478. transmissive: transmissive,
  12479. transparent: transparent,
  12480. init: init,
  12481. push: push,
  12482. unshift: unshift,
  12483. finish: finish,
  12484. sort: sort
  12485. };
  12486. }
  12487. function WebGLRenderLists() {
  12488. let lists = new WeakMap();
  12489. function get( scene, renderCallDepth ) {
  12490. const listArray = lists.get( scene );
  12491. let list;
  12492. if ( listArray === undefined ) {
  12493. list = new WebGLRenderList();
  12494. lists.set( scene, [ list ] );
  12495. } else {
  12496. if ( renderCallDepth >= listArray.length ) {
  12497. list = new WebGLRenderList();
  12498. listArray.push( list );
  12499. } else {
  12500. list = listArray[ renderCallDepth ];
  12501. }
  12502. }
  12503. return list;
  12504. }
  12505. function dispose() {
  12506. lists = new WeakMap();
  12507. }
  12508. return {
  12509. get: get,
  12510. dispose: dispose
  12511. };
  12512. }
  12513. function UniformsCache() {
  12514. const lights = {};
  12515. return {
  12516. get: function ( light ) {
  12517. if ( lights[ light.id ] !== undefined ) {
  12518. return lights[ light.id ];
  12519. }
  12520. let uniforms;
  12521. switch ( light.type ) {
  12522. case 'DirectionalLight':
  12523. uniforms = {
  12524. direction: new Vector3(),
  12525. color: new Color()
  12526. };
  12527. break;
  12528. case 'SpotLight':
  12529. uniforms = {
  12530. position: new Vector3(),
  12531. direction: new Vector3(),
  12532. color: new Color(),
  12533. distance: 0,
  12534. coneCos: 0,
  12535. penumbraCos: 0,
  12536. decay: 0
  12537. };
  12538. break;
  12539. case 'PointLight':
  12540. uniforms = {
  12541. position: new Vector3(),
  12542. color: new Color(),
  12543. distance: 0,
  12544. decay: 0
  12545. };
  12546. break;
  12547. case 'HemisphereLight':
  12548. uniforms = {
  12549. direction: new Vector3(),
  12550. skyColor: new Color(),
  12551. groundColor: new Color()
  12552. };
  12553. break;
  12554. case 'RectAreaLight':
  12555. uniforms = {
  12556. color: new Color(),
  12557. position: new Vector3(),
  12558. halfWidth: new Vector3(),
  12559. halfHeight: new Vector3()
  12560. };
  12561. break;
  12562. }
  12563. lights[ light.id ] = uniforms;
  12564. return uniforms;
  12565. }
  12566. };
  12567. }
  12568. function ShadowUniformsCache() {
  12569. const lights = {};
  12570. return {
  12571. get: function ( light ) {
  12572. if ( lights[ light.id ] !== undefined ) {
  12573. return lights[ light.id ];
  12574. }
  12575. let uniforms;
  12576. switch ( light.type ) {
  12577. case 'DirectionalLight':
  12578. uniforms = {
  12579. shadowBias: 0,
  12580. shadowNormalBias: 0,
  12581. shadowRadius: 1,
  12582. shadowMapSize: new Vector2()
  12583. };
  12584. break;
  12585. case 'SpotLight':
  12586. uniforms = {
  12587. shadowBias: 0,
  12588. shadowNormalBias: 0,
  12589. shadowRadius: 1,
  12590. shadowMapSize: new Vector2()
  12591. };
  12592. break;
  12593. case 'PointLight':
  12594. uniforms = {
  12595. shadowBias: 0,
  12596. shadowNormalBias: 0,
  12597. shadowRadius: 1,
  12598. shadowMapSize: new Vector2(),
  12599. shadowCameraNear: 1,
  12600. shadowCameraFar: 1000
  12601. };
  12602. break;
  12603. // TODO (abelnation): set RectAreaLight shadow uniforms
  12604. }
  12605. lights[ light.id ] = uniforms;
  12606. return uniforms;
  12607. }
  12608. };
  12609. }
  12610. let nextVersion = 0;
  12611. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12612. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12613. }
  12614. function WebGLLights( extensions, capabilities ) {
  12615. const cache = new UniformsCache();
  12616. const shadowCache = ShadowUniformsCache();
  12617. const state = {
  12618. version: 0,
  12619. hash: {
  12620. directionalLength: - 1,
  12621. pointLength: - 1,
  12622. spotLength: - 1,
  12623. rectAreaLength: - 1,
  12624. hemiLength: - 1,
  12625. numDirectionalShadows: - 1,
  12626. numPointShadows: - 1,
  12627. numSpotShadows: - 1,
  12628. numSpotMaps: - 1
  12629. },
  12630. ambient: [ 0, 0, 0 ],
  12631. probe: [],
  12632. directional: [],
  12633. directionalShadow: [],
  12634. directionalShadowMap: [],
  12635. directionalShadowMatrix: [],
  12636. spot: [],
  12637. spotLightMap: [],
  12638. spotShadow: [],
  12639. spotShadowMap: [],
  12640. spotLightMatrix: [],
  12641. rectArea: [],
  12642. rectAreaLTC1: null,
  12643. rectAreaLTC2: null,
  12644. point: [],
  12645. pointShadow: [],
  12646. pointShadowMap: [],
  12647. pointShadowMatrix: [],
  12648. hemi: [],
  12649. numSpotLightShadowsWithMaps: 0
  12650. };
  12651. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12652. const vector3 = new Vector3();
  12653. const matrix4 = new Matrix4();
  12654. const matrix42 = new Matrix4();
  12655. function setup( lights, useLegacyLights ) {
  12656. let r = 0, g = 0, b = 0;
  12657. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12658. let directionalLength = 0;
  12659. let pointLength = 0;
  12660. let spotLength = 0;
  12661. let rectAreaLength = 0;
  12662. let hemiLength = 0;
  12663. let numDirectionalShadows = 0;
  12664. let numPointShadows = 0;
  12665. let numSpotShadows = 0;
  12666. let numSpotMaps = 0;
  12667. let numSpotShadowsWithMaps = 0;
  12668. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12669. lights.sort( shadowCastingAndTexturingLightsFirst );
  12670. // artist-friendly light intensity scaling factor
  12671. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12672. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12673. const light = lights[ i ];
  12674. const color = light.color;
  12675. const intensity = light.intensity;
  12676. const distance = light.distance;
  12677. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12678. if ( light.isAmbientLight ) {
  12679. r += color.r * intensity * scaleFactor;
  12680. g += color.g * intensity * scaleFactor;
  12681. b += color.b * intensity * scaleFactor;
  12682. } else if ( light.isLightProbe ) {
  12683. for ( let j = 0; j < 9; j ++ ) {
  12684. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12685. }
  12686. } else if ( light.isDirectionalLight ) {
  12687. const uniforms = cache.get( light );
  12688. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12689. if ( light.castShadow ) {
  12690. const shadow = light.shadow;
  12691. const shadowUniforms = shadowCache.get( light );
  12692. shadowUniforms.shadowBias = shadow.bias;
  12693. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12694. shadowUniforms.shadowRadius = shadow.radius;
  12695. shadowUniforms.shadowMapSize = shadow.mapSize;
  12696. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12697. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12698. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12699. numDirectionalShadows ++;
  12700. }
  12701. state.directional[ directionalLength ] = uniforms;
  12702. directionalLength ++;
  12703. } else if ( light.isSpotLight ) {
  12704. const uniforms = cache.get( light );
  12705. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12706. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12707. uniforms.distance = distance;
  12708. uniforms.coneCos = Math.cos( light.angle );
  12709. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12710. uniforms.decay = light.decay;
  12711. state.spot[ spotLength ] = uniforms;
  12712. const shadow = light.shadow;
  12713. if ( light.map ) {
  12714. state.spotLightMap[ numSpotMaps ] = light.map;
  12715. numSpotMaps ++;
  12716. // make sure the lightMatrix is up to date
  12717. // TODO : do it if required only
  12718. shadow.updateMatrices( light );
  12719. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12720. }
  12721. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12722. if ( light.castShadow ) {
  12723. const shadowUniforms = shadowCache.get( light );
  12724. shadowUniforms.shadowBias = shadow.bias;
  12725. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12726. shadowUniforms.shadowRadius = shadow.radius;
  12727. shadowUniforms.shadowMapSize = shadow.mapSize;
  12728. state.spotShadow[ spotLength ] = shadowUniforms;
  12729. state.spotShadowMap[ spotLength ] = shadowMap;
  12730. numSpotShadows ++;
  12731. }
  12732. spotLength ++;
  12733. } else if ( light.isRectAreaLight ) {
  12734. const uniforms = cache.get( light );
  12735. uniforms.color.copy( color ).multiplyScalar( intensity );
  12736. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12737. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12738. state.rectArea[ rectAreaLength ] = uniforms;
  12739. rectAreaLength ++;
  12740. } else if ( light.isPointLight ) {
  12741. const uniforms = cache.get( light );
  12742. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12743. uniforms.distance = light.distance;
  12744. uniforms.decay = light.decay;
  12745. if ( light.castShadow ) {
  12746. const shadow = light.shadow;
  12747. const shadowUniforms = shadowCache.get( light );
  12748. shadowUniforms.shadowBias = shadow.bias;
  12749. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12750. shadowUniforms.shadowRadius = shadow.radius;
  12751. shadowUniforms.shadowMapSize = shadow.mapSize;
  12752. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12753. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12754. state.pointShadow[ pointLength ] = shadowUniforms;
  12755. state.pointShadowMap[ pointLength ] = shadowMap;
  12756. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12757. numPointShadows ++;
  12758. }
  12759. state.point[ pointLength ] = uniforms;
  12760. pointLength ++;
  12761. } else if ( light.isHemisphereLight ) {
  12762. const uniforms = cache.get( light );
  12763. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12764. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12765. state.hemi[ hemiLength ] = uniforms;
  12766. hemiLength ++;
  12767. }
  12768. }
  12769. if ( rectAreaLength > 0 ) {
  12770. if ( capabilities.isWebGL2 ) {
  12771. // WebGL 2
  12772. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12773. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12774. } else {
  12775. // WebGL 1
  12776. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12777. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12778. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12779. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12780. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12781. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12782. } else {
  12783. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12784. }
  12785. }
  12786. }
  12787. state.ambient[ 0 ] = r;
  12788. state.ambient[ 1 ] = g;
  12789. state.ambient[ 2 ] = b;
  12790. const hash = state.hash;
  12791. if ( hash.directionalLength !== directionalLength ||
  12792. hash.pointLength !== pointLength ||
  12793. hash.spotLength !== spotLength ||
  12794. hash.rectAreaLength !== rectAreaLength ||
  12795. hash.hemiLength !== hemiLength ||
  12796. hash.numDirectionalShadows !== numDirectionalShadows ||
  12797. hash.numPointShadows !== numPointShadows ||
  12798. hash.numSpotShadows !== numSpotShadows ||
  12799. hash.numSpotMaps !== numSpotMaps ) {
  12800. state.directional.length = directionalLength;
  12801. state.spot.length = spotLength;
  12802. state.rectArea.length = rectAreaLength;
  12803. state.point.length = pointLength;
  12804. state.hemi.length = hemiLength;
  12805. state.directionalShadow.length = numDirectionalShadows;
  12806. state.directionalShadowMap.length = numDirectionalShadows;
  12807. state.pointShadow.length = numPointShadows;
  12808. state.pointShadowMap.length = numPointShadows;
  12809. state.spotShadow.length = numSpotShadows;
  12810. state.spotShadowMap.length = numSpotShadows;
  12811. state.directionalShadowMatrix.length = numDirectionalShadows;
  12812. state.pointShadowMatrix.length = numPointShadows;
  12813. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12814. state.spotLightMap.length = numSpotMaps;
  12815. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12816. hash.directionalLength = directionalLength;
  12817. hash.pointLength = pointLength;
  12818. hash.spotLength = spotLength;
  12819. hash.rectAreaLength = rectAreaLength;
  12820. hash.hemiLength = hemiLength;
  12821. hash.numDirectionalShadows = numDirectionalShadows;
  12822. hash.numPointShadows = numPointShadows;
  12823. hash.numSpotShadows = numSpotShadows;
  12824. hash.numSpotMaps = numSpotMaps;
  12825. state.version = nextVersion ++;
  12826. }
  12827. }
  12828. function setupView( lights, camera ) {
  12829. let directionalLength = 0;
  12830. let pointLength = 0;
  12831. let spotLength = 0;
  12832. let rectAreaLength = 0;
  12833. let hemiLength = 0;
  12834. const viewMatrix = camera.matrixWorldInverse;
  12835. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12836. const light = lights[ i ];
  12837. if ( light.isDirectionalLight ) {
  12838. const uniforms = state.directional[ directionalLength ];
  12839. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12840. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12841. uniforms.direction.sub( vector3 );
  12842. uniforms.direction.transformDirection( viewMatrix );
  12843. directionalLength ++;
  12844. } else if ( light.isSpotLight ) {
  12845. const uniforms = state.spot[ spotLength ];
  12846. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12847. uniforms.position.applyMatrix4( viewMatrix );
  12848. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12849. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12850. uniforms.direction.sub( vector3 );
  12851. uniforms.direction.transformDirection( viewMatrix );
  12852. spotLength ++;
  12853. } else if ( light.isRectAreaLight ) {
  12854. const uniforms = state.rectArea[ rectAreaLength ];
  12855. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12856. uniforms.position.applyMatrix4( viewMatrix );
  12857. // extract local rotation of light to derive width/height half vectors
  12858. matrix42.identity();
  12859. matrix4.copy( light.matrixWorld );
  12860. matrix4.premultiply( viewMatrix );
  12861. matrix42.extractRotation( matrix4 );
  12862. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12863. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12864. uniforms.halfWidth.applyMatrix4( matrix42 );
  12865. uniforms.halfHeight.applyMatrix4( matrix42 );
  12866. rectAreaLength ++;
  12867. } else if ( light.isPointLight ) {
  12868. const uniforms = state.point[ pointLength ];
  12869. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12870. uniforms.position.applyMatrix4( viewMatrix );
  12871. pointLength ++;
  12872. } else if ( light.isHemisphereLight ) {
  12873. const uniforms = state.hemi[ hemiLength ];
  12874. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12875. uniforms.direction.transformDirection( viewMatrix );
  12876. hemiLength ++;
  12877. }
  12878. }
  12879. }
  12880. return {
  12881. setup: setup,
  12882. setupView: setupView,
  12883. state: state
  12884. };
  12885. }
  12886. function WebGLRenderState( extensions, capabilities ) {
  12887. const lights = new WebGLLights( extensions, capabilities );
  12888. const lightsArray = [];
  12889. const shadowsArray = [];
  12890. function init() {
  12891. lightsArray.length = 0;
  12892. shadowsArray.length = 0;
  12893. }
  12894. function pushLight( light ) {
  12895. lightsArray.push( light );
  12896. }
  12897. function pushShadow( shadowLight ) {
  12898. shadowsArray.push( shadowLight );
  12899. }
  12900. function setupLights( useLegacyLights ) {
  12901. lights.setup( lightsArray, useLegacyLights );
  12902. }
  12903. function setupLightsView( camera ) {
  12904. lights.setupView( lightsArray, camera );
  12905. }
  12906. const state = {
  12907. lightsArray: lightsArray,
  12908. shadowsArray: shadowsArray,
  12909. lights: lights
  12910. };
  12911. return {
  12912. init: init,
  12913. state: state,
  12914. setupLights: setupLights,
  12915. setupLightsView: setupLightsView,
  12916. pushLight: pushLight,
  12917. pushShadow: pushShadow
  12918. };
  12919. }
  12920. function WebGLRenderStates( extensions, capabilities ) {
  12921. let renderStates = new WeakMap();
  12922. function get( scene, renderCallDepth = 0 ) {
  12923. const renderStateArray = renderStates.get( scene );
  12924. let renderState;
  12925. if ( renderStateArray === undefined ) {
  12926. renderState = new WebGLRenderState( extensions, capabilities );
  12927. renderStates.set( scene, [ renderState ] );
  12928. } else {
  12929. if ( renderCallDepth >= renderStateArray.length ) {
  12930. renderState = new WebGLRenderState( extensions, capabilities );
  12931. renderStateArray.push( renderState );
  12932. } else {
  12933. renderState = renderStateArray[ renderCallDepth ];
  12934. }
  12935. }
  12936. return renderState;
  12937. }
  12938. function dispose() {
  12939. renderStates = new WeakMap();
  12940. }
  12941. return {
  12942. get: get,
  12943. dispose: dispose
  12944. };
  12945. }
  12946. class MeshDepthMaterial extends Material {
  12947. constructor( parameters ) {
  12948. super();
  12949. this.isMeshDepthMaterial = true;
  12950. this.type = 'MeshDepthMaterial';
  12951. this.depthPacking = BasicDepthPacking;
  12952. this.map = null;
  12953. this.alphaMap = null;
  12954. this.displacementMap = null;
  12955. this.displacementScale = 1;
  12956. this.displacementBias = 0;
  12957. this.wireframe = false;
  12958. this.wireframeLinewidth = 1;
  12959. this.setValues( parameters );
  12960. }
  12961. copy( source ) {
  12962. super.copy( source );
  12963. this.depthPacking = source.depthPacking;
  12964. this.map = source.map;
  12965. this.alphaMap = source.alphaMap;
  12966. this.displacementMap = source.displacementMap;
  12967. this.displacementScale = source.displacementScale;
  12968. this.displacementBias = source.displacementBias;
  12969. this.wireframe = source.wireframe;
  12970. this.wireframeLinewidth = source.wireframeLinewidth;
  12971. return this;
  12972. }
  12973. }
  12974. class MeshDistanceMaterial extends Material {
  12975. constructor( parameters ) {
  12976. super();
  12977. this.isMeshDistanceMaterial = true;
  12978. this.type = 'MeshDistanceMaterial';
  12979. this.map = null;
  12980. this.alphaMap = null;
  12981. this.displacementMap = null;
  12982. this.displacementScale = 1;
  12983. this.displacementBias = 0;
  12984. this.setValues( parameters );
  12985. }
  12986. copy( source ) {
  12987. super.copy( source );
  12988. this.map = source.map;
  12989. this.alphaMap = source.alphaMap;
  12990. this.displacementMap = source.displacementMap;
  12991. this.displacementScale = source.displacementScale;
  12992. this.displacementBias = source.displacementBias;
  12993. return this;
  12994. }
  12995. }
  12996. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12997. 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}";
  12998. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12999. let _frustum = new Frustum();
  13000. const _shadowMapSize = new Vector2(),
  13001. _viewportSize = new Vector2(),
  13002. _viewport = new Vector4(),
  13003. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13004. _distanceMaterial = new MeshDistanceMaterial(),
  13005. _materialCache = {},
  13006. _maxTextureSize = _capabilities.maxTextureSize;
  13007. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13008. const shadowMaterialVertical = new ShaderMaterial( {
  13009. defines: {
  13010. VSM_SAMPLES: 8
  13011. },
  13012. uniforms: {
  13013. shadow_pass: { value: null },
  13014. resolution: { value: new Vector2() },
  13015. radius: { value: 4.0 }
  13016. },
  13017. vertexShader: vertex,
  13018. fragmentShader: fragment
  13019. } );
  13020. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13021. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13022. const fullScreenTri = new BufferGeometry();
  13023. fullScreenTri.setAttribute(
  13024. 'position',
  13025. new BufferAttribute(
  13026. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13027. 3
  13028. )
  13029. );
  13030. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13031. const scope = this;
  13032. this.enabled = false;
  13033. this.autoUpdate = true;
  13034. this.needsUpdate = false;
  13035. this.type = PCFShadowMap;
  13036. let _previousType = this.type;
  13037. this.render = function ( lights, scene, camera ) {
  13038. if ( scope.enabled === false ) return;
  13039. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13040. if ( lights.length === 0 ) return;
  13041. const currentRenderTarget = _renderer.getRenderTarget();
  13042. const activeCubeFace = _renderer.getActiveCubeFace();
  13043. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13044. const _state = _renderer.state;
  13045. // Set GL state for depth map.
  13046. _state.setBlending( NoBlending );
  13047. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13048. _state.buffers.depth.setTest( true );
  13049. _state.setScissorTest( false );
  13050. // check for shadow map type changes
  13051. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13052. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13053. // render depth map
  13054. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13055. const light = lights[ i ];
  13056. const shadow = light.shadow;
  13057. if ( shadow === undefined ) {
  13058. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13059. continue;
  13060. }
  13061. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13062. _shadowMapSize.copy( shadow.mapSize );
  13063. const shadowFrameExtents = shadow.getFrameExtents();
  13064. _shadowMapSize.multiply( shadowFrameExtents );
  13065. _viewportSize.copy( shadow.mapSize );
  13066. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13067. if ( _shadowMapSize.x > _maxTextureSize ) {
  13068. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13069. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13070. shadow.mapSize.x = _viewportSize.x;
  13071. }
  13072. if ( _shadowMapSize.y > _maxTextureSize ) {
  13073. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13074. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13075. shadow.mapSize.y = _viewportSize.y;
  13076. }
  13077. }
  13078. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13079. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13080. if ( shadow.map !== null ) {
  13081. shadow.map.dispose();
  13082. }
  13083. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13084. shadow.map.texture.name = light.name + '.shadowMap';
  13085. shadow.camera.updateProjectionMatrix();
  13086. }
  13087. _renderer.setRenderTarget( shadow.map );
  13088. _renderer.clear();
  13089. const viewportCount = shadow.getViewportCount();
  13090. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13091. const viewport = shadow.getViewport( vp );
  13092. _viewport.set(
  13093. _viewportSize.x * viewport.x,
  13094. _viewportSize.y * viewport.y,
  13095. _viewportSize.x * viewport.z,
  13096. _viewportSize.y * viewport.w
  13097. );
  13098. _state.viewport( _viewport );
  13099. shadow.updateMatrices( light, vp );
  13100. _frustum = shadow.getFrustum();
  13101. renderObject( scene, camera, shadow.camera, light, this.type );
  13102. }
  13103. // do blur pass for VSM
  13104. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13105. VSMPass( shadow, camera );
  13106. }
  13107. shadow.needsUpdate = false;
  13108. }
  13109. _previousType = this.type;
  13110. scope.needsUpdate = false;
  13111. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13112. };
  13113. function VSMPass( shadow, camera ) {
  13114. const geometry = _objects.update( fullScreenMesh );
  13115. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13116. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13117. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13118. shadowMaterialVertical.needsUpdate = true;
  13119. shadowMaterialHorizontal.needsUpdate = true;
  13120. }
  13121. if ( shadow.mapPass === null ) {
  13122. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13123. }
  13124. // vertical pass
  13125. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13126. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13127. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13128. _renderer.setRenderTarget( shadow.mapPass );
  13129. _renderer.clear();
  13130. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13131. // horizontal pass
  13132. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13133. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13134. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13135. _renderer.setRenderTarget( shadow.map );
  13136. _renderer.clear();
  13137. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13138. }
  13139. function getDepthMaterial( object, material, light, type ) {
  13140. let result = null;
  13141. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13142. if ( customMaterial !== undefined ) {
  13143. result = customMaterial;
  13144. } else {
  13145. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13146. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13147. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13148. ( material.alphaMap && material.alphaTest > 0 ) ||
  13149. ( material.map && material.alphaTest > 0 ) ) {
  13150. // in this case we need a unique material instance reflecting the
  13151. // appropriate state
  13152. const keyA = result.uuid, keyB = material.uuid;
  13153. let materialsForVariant = _materialCache[ keyA ];
  13154. if ( materialsForVariant === undefined ) {
  13155. materialsForVariant = {};
  13156. _materialCache[ keyA ] = materialsForVariant;
  13157. }
  13158. let cachedMaterial = materialsForVariant[ keyB ];
  13159. if ( cachedMaterial === undefined ) {
  13160. cachedMaterial = result.clone();
  13161. materialsForVariant[ keyB ] = cachedMaterial;
  13162. }
  13163. result = cachedMaterial;
  13164. }
  13165. }
  13166. result.visible = material.visible;
  13167. result.wireframe = material.wireframe;
  13168. if ( type === VSMShadowMap ) {
  13169. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13170. } else {
  13171. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13172. }
  13173. result.alphaMap = material.alphaMap;
  13174. result.alphaTest = material.alphaTest;
  13175. result.map = material.map;
  13176. result.clipShadows = material.clipShadows;
  13177. result.clippingPlanes = material.clippingPlanes;
  13178. result.clipIntersection = material.clipIntersection;
  13179. result.displacementMap = material.displacementMap;
  13180. result.displacementScale = material.displacementScale;
  13181. result.displacementBias = material.displacementBias;
  13182. result.wireframeLinewidth = material.wireframeLinewidth;
  13183. result.linewidth = material.linewidth;
  13184. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13185. const materialProperties = _renderer.properties.get( result );
  13186. materialProperties.light = light;
  13187. }
  13188. return result;
  13189. }
  13190. function renderObject( object, camera, shadowCamera, light, type ) {
  13191. if ( object.visible === false ) return;
  13192. const visible = object.layers.test( camera.layers );
  13193. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13194. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13195. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13196. const geometry = _objects.update( object );
  13197. const material = object.material;
  13198. if ( Array.isArray( material ) ) {
  13199. const groups = geometry.groups;
  13200. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13201. const group = groups[ k ];
  13202. const groupMaterial = material[ group.materialIndex ];
  13203. if ( groupMaterial && groupMaterial.visible ) {
  13204. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13205. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13206. }
  13207. }
  13208. } else if ( material.visible ) {
  13209. const depthMaterial = getDepthMaterial( object, material, light, type );
  13210. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13211. }
  13212. }
  13213. }
  13214. const children = object.children;
  13215. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13216. renderObject( children[ i ], camera, shadowCamera, light, type );
  13217. }
  13218. }
  13219. }
  13220. function WebGLState( gl, extensions, capabilities ) {
  13221. const isWebGL2 = capabilities.isWebGL2;
  13222. function ColorBuffer() {
  13223. let locked = false;
  13224. const color = new Vector4();
  13225. let currentColorMask = null;
  13226. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13227. return {
  13228. setMask: function ( colorMask ) {
  13229. if ( currentColorMask !== colorMask && ! locked ) {
  13230. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13231. currentColorMask = colorMask;
  13232. }
  13233. },
  13234. setLocked: function ( lock ) {
  13235. locked = lock;
  13236. },
  13237. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13238. if ( premultipliedAlpha === true ) {
  13239. r *= a; g *= a; b *= a;
  13240. }
  13241. color.set( r, g, b, a );
  13242. if ( currentColorClear.equals( color ) === false ) {
  13243. gl.clearColor( r, g, b, a );
  13244. currentColorClear.copy( color );
  13245. }
  13246. },
  13247. reset: function () {
  13248. locked = false;
  13249. currentColorMask = null;
  13250. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13251. }
  13252. };
  13253. }
  13254. function DepthBuffer() {
  13255. let locked = false;
  13256. let currentDepthMask = null;
  13257. let currentDepthFunc = null;
  13258. let currentDepthClear = null;
  13259. return {
  13260. setTest: function ( depthTest ) {
  13261. if ( depthTest ) {
  13262. enable( gl.DEPTH_TEST );
  13263. } else {
  13264. disable( gl.DEPTH_TEST );
  13265. }
  13266. },
  13267. setMask: function ( depthMask ) {
  13268. if ( currentDepthMask !== depthMask && ! locked ) {
  13269. gl.depthMask( depthMask );
  13270. currentDepthMask = depthMask;
  13271. }
  13272. },
  13273. setFunc: function ( depthFunc ) {
  13274. if ( currentDepthFunc !== depthFunc ) {
  13275. switch ( depthFunc ) {
  13276. case NeverDepth:
  13277. gl.depthFunc( gl.NEVER );
  13278. break;
  13279. case AlwaysDepth:
  13280. gl.depthFunc( gl.ALWAYS );
  13281. break;
  13282. case LessDepth:
  13283. gl.depthFunc( gl.LESS );
  13284. break;
  13285. case LessEqualDepth:
  13286. gl.depthFunc( gl.LEQUAL );
  13287. break;
  13288. case EqualDepth:
  13289. gl.depthFunc( gl.EQUAL );
  13290. break;
  13291. case GreaterEqualDepth:
  13292. gl.depthFunc( gl.GEQUAL );
  13293. break;
  13294. case GreaterDepth:
  13295. gl.depthFunc( gl.GREATER );
  13296. break;
  13297. case NotEqualDepth:
  13298. gl.depthFunc( gl.NOTEQUAL );
  13299. break;
  13300. default:
  13301. gl.depthFunc( gl.LEQUAL );
  13302. }
  13303. currentDepthFunc = depthFunc;
  13304. }
  13305. },
  13306. setLocked: function ( lock ) {
  13307. locked = lock;
  13308. },
  13309. setClear: function ( depth ) {
  13310. if ( currentDepthClear !== depth ) {
  13311. gl.clearDepth( depth );
  13312. currentDepthClear = depth;
  13313. }
  13314. },
  13315. reset: function () {
  13316. locked = false;
  13317. currentDepthMask = null;
  13318. currentDepthFunc = null;
  13319. currentDepthClear = null;
  13320. }
  13321. };
  13322. }
  13323. function StencilBuffer() {
  13324. let locked = false;
  13325. let currentStencilMask = null;
  13326. let currentStencilFunc = null;
  13327. let currentStencilRef = null;
  13328. let currentStencilFuncMask = null;
  13329. let currentStencilFail = null;
  13330. let currentStencilZFail = null;
  13331. let currentStencilZPass = null;
  13332. let currentStencilClear = null;
  13333. return {
  13334. setTest: function ( stencilTest ) {
  13335. if ( ! locked ) {
  13336. if ( stencilTest ) {
  13337. enable( gl.STENCIL_TEST );
  13338. } else {
  13339. disable( gl.STENCIL_TEST );
  13340. }
  13341. }
  13342. },
  13343. setMask: function ( stencilMask ) {
  13344. if ( currentStencilMask !== stencilMask && ! locked ) {
  13345. gl.stencilMask( stencilMask );
  13346. currentStencilMask = stencilMask;
  13347. }
  13348. },
  13349. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13350. if ( currentStencilFunc !== stencilFunc ||
  13351. currentStencilRef !== stencilRef ||
  13352. currentStencilFuncMask !== stencilMask ) {
  13353. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13354. currentStencilFunc = stencilFunc;
  13355. currentStencilRef = stencilRef;
  13356. currentStencilFuncMask = stencilMask;
  13357. }
  13358. },
  13359. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13360. if ( currentStencilFail !== stencilFail ||
  13361. currentStencilZFail !== stencilZFail ||
  13362. currentStencilZPass !== stencilZPass ) {
  13363. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13364. currentStencilFail = stencilFail;
  13365. currentStencilZFail = stencilZFail;
  13366. currentStencilZPass = stencilZPass;
  13367. }
  13368. },
  13369. setLocked: function ( lock ) {
  13370. locked = lock;
  13371. },
  13372. setClear: function ( stencil ) {
  13373. if ( currentStencilClear !== stencil ) {
  13374. gl.clearStencil( stencil );
  13375. currentStencilClear = stencil;
  13376. }
  13377. },
  13378. reset: function () {
  13379. locked = false;
  13380. currentStencilMask = null;
  13381. currentStencilFunc = null;
  13382. currentStencilRef = null;
  13383. currentStencilFuncMask = null;
  13384. currentStencilFail = null;
  13385. currentStencilZFail = null;
  13386. currentStencilZPass = null;
  13387. currentStencilClear = null;
  13388. }
  13389. };
  13390. }
  13391. //
  13392. const colorBuffer = new ColorBuffer();
  13393. const depthBuffer = new DepthBuffer();
  13394. const stencilBuffer = new StencilBuffer();
  13395. const uboBindings = new WeakMap();
  13396. const uboProgramMap = new WeakMap();
  13397. let enabledCapabilities = {};
  13398. let currentBoundFramebuffers = {};
  13399. let currentDrawbuffers = new WeakMap();
  13400. let defaultDrawbuffers = [];
  13401. let currentProgram = null;
  13402. let currentBlendingEnabled = false;
  13403. let currentBlending = null;
  13404. let currentBlendEquation = null;
  13405. let currentBlendSrc = null;
  13406. let currentBlendDst = null;
  13407. let currentBlendEquationAlpha = null;
  13408. let currentBlendSrcAlpha = null;
  13409. let currentBlendDstAlpha = null;
  13410. let currentPremultipledAlpha = false;
  13411. let currentFlipSided = null;
  13412. let currentCullFace = null;
  13413. let currentLineWidth = null;
  13414. let currentPolygonOffsetFactor = null;
  13415. let currentPolygonOffsetUnits = null;
  13416. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13417. let lineWidthAvailable = false;
  13418. let version = 0;
  13419. const glVersion = gl.getParameter( gl.VERSION );
  13420. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13421. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13422. lineWidthAvailable = ( version >= 1.0 );
  13423. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13424. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13425. lineWidthAvailable = ( version >= 2.0 );
  13426. }
  13427. let currentTextureSlot = null;
  13428. let currentBoundTextures = {};
  13429. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13430. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13431. const currentScissor = new Vector4().fromArray( scissorParam );
  13432. const currentViewport = new Vector4().fromArray( viewportParam );
  13433. function createTexture( type, target, count, dimensions ) {
  13434. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13435. const texture = gl.createTexture();
  13436. gl.bindTexture( type, texture );
  13437. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13438. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13439. for ( let i = 0; i < count; i ++ ) {
  13440. if ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) {
  13441. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13442. } else {
  13443. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13444. }
  13445. }
  13446. return texture;
  13447. }
  13448. const emptyTextures = {};
  13449. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13450. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13451. if ( isWebGL2 ) {
  13452. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13453. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13454. }
  13455. // init
  13456. colorBuffer.setClear( 0, 0, 0, 1 );
  13457. depthBuffer.setClear( 1 );
  13458. stencilBuffer.setClear( 0 );
  13459. enable( gl.DEPTH_TEST );
  13460. depthBuffer.setFunc( LessEqualDepth );
  13461. setFlipSided( false );
  13462. setCullFace( CullFaceBack );
  13463. enable( gl.CULL_FACE );
  13464. setBlending( NoBlending );
  13465. //
  13466. function enable( id ) {
  13467. if ( enabledCapabilities[ id ] !== true ) {
  13468. gl.enable( id );
  13469. enabledCapabilities[ id ] = true;
  13470. }
  13471. }
  13472. function disable( id ) {
  13473. if ( enabledCapabilities[ id ] !== false ) {
  13474. gl.disable( id );
  13475. enabledCapabilities[ id ] = false;
  13476. }
  13477. }
  13478. function bindFramebuffer( target, framebuffer ) {
  13479. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13480. gl.bindFramebuffer( target, framebuffer );
  13481. currentBoundFramebuffers[ target ] = framebuffer;
  13482. if ( isWebGL2 ) {
  13483. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13484. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13485. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13486. }
  13487. if ( target === gl.FRAMEBUFFER ) {
  13488. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13489. }
  13490. }
  13491. return true;
  13492. }
  13493. return false;
  13494. }
  13495. function drawBuffers( renderTarget, framebuffer ) {
  13496. let drawBuffers = defaultDrawbuffers;
  13497. let needsUpdate = false;
  13498. if ( renderTarget ) {
  13499. drawBuffers = currentDrawbuffers.get( framebuffer );
  13500. if ( drawBuffers === undefined ) {
  13501. drawBuffers = [];
  13502. currentDrawbuffers.set( framebuffer, drawBuffers );
  13503. }
  13504. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13505. const textures = renderTarget.texture;
  13506. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13507. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13508. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13509. }
  13510. drawBuffers.length = textures.length;
  13511. needsUpdate = true;
  13512. }
  13513. } else {
  13514. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13515. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13516. needsUpdate = true;
  13517. }
  13518. }
  13519. } else {
  13520. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13521. drawBuffers[ 0 ] = gl.BACK;
  13522. needsUpdate = true;
  13523. }
  13524. }
  13525. if ( needsUpdate ) {
  13526. if ( capabilities.isWebGL2 ) {
  13527. gl.drawBuffers( drawBuffers );
  13528. } else {
  13529. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13530. }
  13531. }
  13532. }
  13533. function useProgram( program ) {
  13534. if ( currentProgram !== program ) {
  13535. gl.useProgram( program );
  13536. currentProgram = program;
  13537. return true;
  13538. }
  13539. return false;
  13540. }
  13541. const equationToGL = {
  13542. [ AddEquation ]: gl.FUNC_ADD,
  13543. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13544. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13545. };
  13546. if ( isWebGL2 ) {
  13547. equationToGL[ MinEquation ] = gl.MIN;
  13548. equationToGL[ MaxEquation ] = gl.MAX;
  13549. } else {
  13550. const extension = extensions.get( 'EXT_blend_minmax' );
  13551. if ( extension !== null ) {
  13552. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13553. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13554. }
  13555. }
  13556. const factorToGL = {
  13557. [ ZeroFactor ]: gl.ZERO,
  13558. [ OneFactor ]: gl.ONE,
  13559. [ SrcColorFactor ]: gl.SRC_COLOR,
  13560. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13561. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13562. [ DstColorFactor ]: gl.DST_COLOR,
  13563. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13564. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13565. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13566. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13567. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13568. };
  13569. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13570. if ( blending === NoBlending ) {
  13571. if ( currentBlendingEnabled === true ) {
  13572. disable( gl.BLEND );
  13573. currentBlendingEnabled = false;
  13574. }
  13575. return;
  13576. }
  13577. if ( currentBlendingEnabled === false ) {
  13578. enable( gl.BLEND );
  13579. currentBlendingEnabled = true;
  13580. }
  13581. if ( blending !== CustomBlending ) {
  13582. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13583. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13584. gl.blendEquation( gl.FUNC_ADD );
  13585. currentBlendEquation = AddEquation;
  13586. currentBlendEquationAlpha = AddEquation;
  13587. }
  13588. if ( premultipliedAlpha ) {
  13589. switch ( blending ) {
  13590. case NormalBlending:
  13591. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13592. break;
  13593. case AdditiveBlending:
  13594. gl.blendFunc( gl.ONE, gl.ONE );
  13595. break;
  13596. case SubtractiveBlending:
  13597. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13598. break;
  13599. case MultiplyBlending:
  13600. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13601. break;
  13602. default:
  13603. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13604. break;
  13605. }
  13606. } else {
  13607. switch ( blending ) {
  13608. case NormalBlending:
  13609. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13610. break;
  13611. case AdditiveBlending:
  13612. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13613. break;
  13614. case SubtractiveBlending:
  13615. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13616. break;
  13617. case MultiplyBlending:
  13618. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13619. break;
  13620. default:
  13621. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13622. break;
  13623. }
  13624. }
  13625. currentBlendSrc = null;
  13626. currentBlendDst = null;
  13627. currentBlendSrcAlpha = null;
  13628. currentBlendDstAlpha = null;
  13629. currentBlending = blending;
  13630. currentPremultipledAlpha = premultipliedAlpha;
  13631. }
  13632. return;
  13633. }
  13634. // custom blending
  13635. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13636. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13637. blendDstAlpha = blendDstAlpha || blendDst;
  13638. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13639. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13640. currentBlendEquation = blendEquation;
  13641. currentBlendEquationAlpha = blendEquationAlpha;
  13642. }
  13643. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13644. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13645. currentBlendSrc = blendSrc;
  13646. currentBlendDst = blendDst;
  13647. currentBlendSrcAlpha = blendSrcAlpha;
  13648. currentBlendDstAlpha = blendDstAlpha;
  13649. }
  13650. currentBlending = blending;
  13651. currentPremultipledAlpha = false;
  13652. }
  13653. function setMaterial( material, frontFaceCW ) {
  13654. material.side === DoubleSide
  13655. ? disable( gl.CULL_FACE )
  13656. : enable( gl.CULL_FACE );
  13657. let flipSided = ( material.side === BackSide );
  13658. if ( frontFaceCW ) flipSided = ! flipSided;
  13659. setFlipSided( flipSided );
  13660. ( material.blending === NormalBlending && material.transparent === false )
  13661. ? setBlending( NoBlending )
  13662. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13663. depthBuffer.setFunc( material.depthFunc );
  13664. depthBuffer.setTest( material.depthTest );
  13665. depthBuffer.setMask( material.depthWrite );
  13666. colorBuffer.setMask( material.colorWrite );
  13667. const stencilWrite = material.stencilWrite;
  13668. stencilBuffer.setTest( stencilWrite );
  13669. if ( stencilWrite ) {
  13670. stencilBuffer.setMask( material.stencilWriteMask );
  13671. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13672. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13673. }
  13674. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13675. material.alphaToCoverage === true
  13676. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13677. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13678. }
  13679. //
  13680. function setFlipSided( flipSided ) {
  13681. if ( currentFlipSided !== flipSided ) {
  13682. if ( flipSided ) {
  13683. gl.frontFace( gl.CW );
  13684. } else {
  13685. gl.frontFace( gl.CCW );
  13686. }
  13687. currentFlipSided = flipSided;
  13688. }
  13689. }
  13690. function setCullFace( cullFace ) {
  13691. if ( cullFace !== CullFaceNone ) {
  13692. enable( gl.CULL_FACE );
  13693. if ( cullFace !== currentCullFace ) {
  13694. if ( cullFace === CullFaceBack ) {
  13695. gl.cullFace( gl.BACK );
  13696. } else if ( cullFace === CullFaceFront ) {
  13697. gl.cullFace( gl.FRONT );
  13698. } else {
  13699. gl.cullFace( gl.FRONT_AND_BACK );
  13700. }
  13701. }
  13702. } else {
  13703. disable( gl.CULL_FACE );
  13704. }
  13705. currentCullFace = cullFace;
  13706. }
  13707. function setLineWidth( width ) {
  13708. if ( width !== currentLineWidth ) {
  13709. if ( lineWidthAvailable ) gl.lineWidth( width );
  13710. currentLineWidth = width;
  13711. }
  13712. }
  13713. function setPolygonOffset( polygonOffset, factor, units ) {
  13714. if ( polygonOffset ) {
  13715. enable( gl.POLYGON_OFFSET_FILL );
  13716. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13717. gl.polygonOffset( factor, units );
  13718. currentPolygonOffsetFactor = factor;
  13719. currentPolygonOffsetUnits = units;
  13720. }
  13721. } else {
  13722. disable( gl.POLYGON_OFFSET_FILL );
  13723. }
  13724. }
  13725. function setScissorTest( scissorTest ) {
  13726. if ( scissorTest ) {
  13727. enable( gl.SCISSOR_TEST );
  13728. } else {
  13729. disable( gl.SCISSOR_TEST );
  13730. }
  13731. }
  13732. // texture
  13733. function activeTexture( webglSlot ) {
  13734. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13735. if ( currentTextureSlot !== webglSlot ) {
  13736. gl.activeTexture( webglSlot );
  13737. currentTextureSlot = webglSlot;
  13738. }
  13739. }
  13740. function bindTexture( webglType, webglTexture, webglSlot ) {
  13741. if ( webglSlot === undefined ) {
  13742. if ( currentTextureSlot === null ) {
  13743. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13744. } else {
  13745. webglSlot = currentTextureSlot;
  13746. }
  13747. }
  13748. let boundTexture = currentBoundTextures[ webglSlot ];
  13749. if ( boundTexture === undefined ) {
  13750. boundTexture = { type: undefined, texture: undefined };
  13751. currentBoundTextures[ webglSlot ] = boundTexture;
  13752. }
  13753. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13754. if ( currentTextureSlot !== webglSlot ) {
  13755. gl.activeTexture( webglSlot );
  13756. currentTextureSlot = webglSlot;
  13757. }
  13758. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13759. boundTexture.type = webglType;
  13760. boundTexture.texture = webglTexture;
  13761. }
  13762. }
  13763. function unbindTexture() {
  13764. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13765. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13766. gl.bindTexture( boundTexture.type, null );
  13767. boundTexture.type = undefined;
  13768. boundTexture.texture = undefined;
  13769. }
  13770. }
  13771. function compressedTexImage2D() {
  13772. try {
  13773. gl.compressedTexImage2D.apply( gl, arguments );
  13774. } catch ( error ) {
  13775. console.error( 'THREE.WebGLState:', error );
  13776. }
  13777. }
  13778. function compressedTexImage3D() {
  13779. try {
  13780. gl.compressedTexImage3D.apply( gl, arguments );
  13781. } catch ( error ) {
  13782. console.error( 'THREE.WebGLState:', error );
  13783. }
  13784. }
  13785. function texSubImage2D() {
  13786. try {
  13787. gl.texSubImage2D.apply( gl, arguments );
  13788. } catch ( error ) {
  13789. console.error( 'THREE.WebGLState:', error );
  13790. }
  13791. }
  13792. function texSubImage3D() {
  13793. try {
  13794. gl.texSubImage3D.apply( gl, arguments );
  13795. } catch ( error ) {
  13796. console.error( 'THREE.WebGLState:', error );
  13797. }
  13798. }
  13799. function compressedTexSubImage2D() {
  13800. try {
  13801. gl.compressedTexSubImage2D.apply( gl, arguments );
  13802. } catch ( error ) {
  13803. console.error( 'THREE.WebGLState:', error );
  13804. }
  13805. }
  13806. function compressedTexSubImage3D() {
  13807. try {
  13808. gl.compressedTexSubImage3D.apply( gl, arguments );
  13809. } catch ( error ) {
  13810. console.error( 'THREE.WebGLState:', error );
  13811. }
  13812. }
  13813. function texStorage2D() {
  13814. try {
  13815. gl.texStorage2D.apply( gl, arguments );
  13816. } catch ( error ) {
  13817. console.error( 'THREE.WebGLState:', error );
  13818. }
  13819. }
  13820. function texStorage3D() {
  13821. try {
  13822. gl.texStorage3D.apply( gl, arguments );
  13823. } catch ( error ) {
  13824. console.error( 'THREE.WebGLState:', error );
  13825. }
  13826. }
  13827. function texImage2D() {
  13828. try {
  13829. gl.texImage2D.apply( gl, arguments );
  13830. } catch ( error ) {
  13831. console.error( 'THREE.WebGLState:', error );
  13832. }
  13833. }
  13834. function texImage3D() {
  13835. try {
  13836. gl.texImage3D.apply( gl, arguments );
  13837. } catch ( error ) {
  13838. console.error( 'THREE.WebGLState:', error );
  13839. }
  13840. }
  13841. //
  13842. function scissor( scissor ) {
  13843. if ( currentScissor.equals( scissor ) === false ) {
  13844. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13845. currentScissor.copy( scissor );
  13846. }
  13847. }
  13848. function viewport( viewport ) {
  13849. if ( currentViewport.equals( viewport ) === false ) {
  13850. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13851. currentViewport.copy( viewport );
  13852. }
  13853. }
  13854. function updateUBOMapping( uniformsGroup, program ) {
  13855. let mapping = uboProgramMap.get( program );
  13856. if ( mapping === undefined ) {
  13857. mapping = new WeakMap();
  13858. uboProgramMap.set( program, mapping );
  13859. }
  13860. let blockIndex = mapping.get( uniformsGroup );
  13861. if ( blockIndex === undefined ) {
  13862. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13863. mapping.set( uniformsGroup, blockIndex );
  13864. }
  13865. }
  13866. function uniformBlockBinding( uniformsGroup, program ) {
  13867. const mapping = uboProgramMap.get( program );
  13868. const blockIndex = mapping.get( uniformsGroup );
  13869. if ( uboBindings.get( program ) !== blockIndex ) {
  13870. // bind shader specific block index to global block point
  13871. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13872. uboBindings.set( program, blockIndex );
  13873. }
  13874. }
  13875. //
  13876. function reset() {
  13877. // reset state
  13878. gl.disable( gl.BLEND );
  13879. gl.disable( gl.CULL_FACE );
  13880. gl.disable( gl.DEPTH_TEST );
  13881. gl.disable( gl.POLYGON_OFFSET_FILL );
  13882. gl.disable( gl.SCISSOR_TEST );
  13883. gl.disable( gl.STENCIL_TEST );
  13884. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13885. gl.blendEquation( gl.FUNC_ADD );
  13886. gl.blendFunc( gl.ONE, gl.ZERO );
  13887. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  13888. gl.colorMask( true, true, true, true );
  13889. gl.clearColor( 0, 0, 0, 0 );
  13890. gl.depthMask( true );
  13891. gl.depthFunc( gl.LESS );
  13892. gl.clearDepth( 1 );
  13893. gl.stencilMask( 0xffffffff );
  13894. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  13895. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  13896. gl.clearStencil( 0 );
  13897. gl.cullFace( gl.BACK );
  13898. gl.frontFace( gl.CCW );
  13899. gl.polygonOffset( 0, 0 );
  13900. gl.activeTexture( gl.TEXTURE0 );
  13901. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  13902. if ( isWebGL2 === true ) {
  13903. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  13904. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  13905. }
  13906. gl.useProgram( null );
  13907. gl.lineWidth( 1 );
  13908. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13909. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13910. // reset internals
  13911. enabledCapabilities = {};
  13912. currentTextureSlot = null;
  13913. currentBoundTextures = {};
  13914. currentBoundFramebuffers = {};
  13915. currentDrawbuffers = new WeakMap();
  13916. defaultDrawbuffers = [];
  13917. currentProgram = null;
  13918. currentBlendingEnabled = false;
  13919. currentBlending = null;
  13920. currentBlendEquation = null;
  13921. currentBlendSrc = null;
  13922. currentBlendDst = null;
  13923. currentBlendEquationAlpha = null;
  13924. currentBlendSrcAlpha = null;
  13925. currentBlendDstAlpha = null;
  13926. currentPremultipledAlpha = false;
  13927. currentFlipSided = null;
  13928. currentCullFace = null;
  13929. currentLineWidth = null;
  13930. currentPolygonOffsetFactor = null;
  13931. currentPolygonOffsetUnits = null;
  13932. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13933. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13934. colorBuffer.reset();
  13935. depthBuffer.reset();
  13936. stencilBuffer.reset();
  13937. }
  13938. return {
  13939. buffers: {
  13940. color: colorBuffer,
  13941. depth: depthBuffer,
  13942. stencil: stencilBuffer
  13943. },
  13944. enable: enable,
  13945. disable: disable,
  13946. bindFramebuffer: bindFramebuffer,
  13947. drawBuffers: drawBuffers,
  13948. useProgram: useProgram,
  13949. setBlending: setBlending,
  13950. setMaterial: setMaterial,
  13951. setFlipSided: setFlipSided,
  13952. setCullFace: setCullFace,
  13953. setLineWidth: setLineWidth,
  13954. setPolygonOffset: setPolygonOffset,
  13955. setScissorTest: setScissorTest,
  13956. activeTexture: activeTexture,
  13957. bindTexture: bindTexture,
  13958. unbindTexture: unbindTexture,
  13959. compressedTexImage2D: compressedTexImage2D,
  13960. compressedTexImage3D: compressedTexImage3D,
  13961. texImage2D: texImage2D,
  13962. texImage3D: texImage3D,
  13963. updateUBOMapping: updateUBOMapping,
  13964. uniformBlockBinding: uniformBlockBinding,
  13965. texStorage2D: texStorage2D,
  13966. texStorage3D: texStorage3D,
  13967. texSubImage2D: texSubImage2D,
  13968. texSubImage3D: texSubImage3D,
  13969. compressedTexSubImage2D: compressedTexSubImage2D,
  13970. compressedTexSubImage3D: compressedTexSubImage3D,
  13971. scissor: scissor,
  13972. viewport: viewport,
  13973. reset: reset
  13974. };
  13975. }
  13976. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13977. const isWebGL2 = capabilities.isWebGL2;
  13978. const maxTextures = capabilities.maxTextures;
  13979. const maxCubemapSize = capabilities.maxCubemapSize;
  13980. const maxTextureSize = capabilities.maxTextureSize;
  13981. const maxSamples = capabilities.maxSamples;
  13982. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13983. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13984. const _videoTextures = new WeakMap();
  13985. let _canvas;
  13986. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13987. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13988. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13989. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13990. let useOffscreenCanvas = false;
  13991. try {
  13992. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13993. // eslint-disable-next-line compat/compat
  13994. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13995. } catch ( err ) {
  13996. // Ignore any errors
  13997. }
  13998. function createCanvas( width, height ) {
  13999. // Use OffscreenCanvas when available. Specially needed in web workers
  14000. return useOffscreenCanvas ?
  14001. // eslint-disable-next-line compat/compat
  14002. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14003. }
  14004. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14005. let scale = 1;
  14006. // handle case if texture exceeds max size
  14007. if ( image.width > maxSize || image.height > maxSize ) {
  14008. scale = maxSize / Math.max( image.width, image.height );
  14009. }
  14010. // only perform resize if necessary
  14011. if ( scale < 1 || needsPowerOfTwo === true ) {
  14012. // only perform resize for certain image types
  14013. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14014. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14015. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14016. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14017. const width = floor( scale * image.width );
  14018. const height = floor( scale * image.height );
  14019. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14020. // cube textures can't reuse the same canvas
  14021. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14022. canvas.width = width;
  14023. canvas.height = height;
  14024. const context = canvas.getContext( '2d' );
  14025. context.drawImage( image, 0, 0, width, height );
  14026. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14027. return canvas;
  14028. } else {
  14029. if ( 'data' in image ) {
  14030. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14031. }
  14032. return image;
  14033. }
  14034. }
  14035. return image;
  14036. }
  14037. function isPowerOfTwo$1( image ) {
  14038. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14039. }
  14040. function textureNeedsPowerOfTwo( texture ) {
  14041. if ( isWebGL2 ) return false;
  14042. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14043. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14044. }
  14045. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14046. return texture.generateMipmaps && supportsMips &&
  14047. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14048. }
  14049. function generateMipmap( target ) {
  14050. _gl.generateMipmap( target );
  14051. }
  14052. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14053. if ( isWebGL2 === false ) return glFormat;
  14054. if ( internalFormatName !== null ) {
  14055. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14056. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14057. }
  14058. let internalFormat = glFormat;
  14059. if ( glFormat === _gl.RED ) {
  14060. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14061. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14062. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14063. }
  14064. if ( glFormat === _gl.RG ) {
  14065. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14066. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14067. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14068. }
  14069. if ( glFormat === _gl.RGBA ) {
  14070. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14071. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14072. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14073. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14074. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14075. }
  14076. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14077. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14078. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14079. extensions.get( 'EXT_color_buffer_float' );
  14080. }
  14081. return internalFormat;
  14082. }
  14083. function getMipLevels( texture, image, supportsMips ) {
  14084. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14085. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14086. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14087. // user-defined mipmaps
  14088. return texture.mipmaps.length;
  14089. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14090. return image.mipmaps.length;
  14091. } else {
  14092. // texture without mipmaps (only base level)
  14093. return 1;
  14094. }
  14095. }
  14096. // Fallback filters for non-power-of-2 textures
  14097. function filterFallback( f ) {
  14098. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14099. return _gl.NEAREST;
  14100. }
  14101. return _gl.LINEAR;
  14102. }
  14103. //
  14104. function onTextureDispose( event ) {
  14105. const texture = event.target;
  14106. texture.removeEventListener( 'dispose', onTextureDispose );
  14107. deallocateTexture( texture );
  14108. if ( texture.isVideoTexture ) {
  14109. _videoTextures.delete( texture );
  14110. }
  14111. }
  14112. function onRenderTargetDispose( event ) {
  14113. const renderTarget = event.target;
  14114. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14115. deallocateRenderTarget( renderTarget );
  14116. }
  14117. //
  14118. function deallocateTexture( texture ) {
  14119. const textureProperties = properties.get( texture );
  14120. if ( textureProperties.__webglInit === undefined ) return;
  14121. // check if it's necessary to remove the WebGLTexture object
  14122. const source = texture.source;
  14123. const webglTextures = _sources.get( source );
  14124. if ( webglTextures ) {
  14125. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14126. webglTexture.usedTimes --;
  14127. // the WebGLTexture object is not used anymore, remove it
  14128. if ( webglTexture.usedTimes === 0 ) {
  14129. deleteTexture( texture );
  14130. }
  14131. // remove the weak map entry if no WebGLTexture uses the source anymore
  14132. if ( Object.keys( webglTextures ).length === 0 ) {
  14133. _sources.delete( source );
  14134. }
  14135. }
  14136. properties.remove( texture );
  14137. }
  14138. function deleteTexture( texture ) {
  14139. const textureProperties = properties.get( texture );
  14140. _gl.deleteTexture( textureProperties.__webglTexture );
  14141. const source = texture.source;
  14142. const webglTextures = _sources.get( source );
  14143. delete webglTextures[ textureProperties.__cacheKey ];
  14144. info.memory.textures --;
  14145. }
  14146. function deallocateRenderTarget( renderTarget ) {
  14147. const texture = renderTarget.texture;
  14148. const renderTargetProperties = properties.get( renderTarget );
  14149. const textureProperties = properties.get( texture );
  14150. if ( textureProperties.__webglTexture !== undefined ) {
  14151. _gl.deleteTexture( textureProperties.__webglTexture );
  14152. info.memory.textures --;
  14153. }
  14154. if ( renderTarget.depthTexture ) {
  14155. renderTarget.depthTexture.dispose();
  14156. }
  14157. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14158. for ( let i = 0; i < 6; i ++ ) {
  14159. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14160. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14161. }
  14162. } else {
  14163. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14164. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14165. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14166. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14167. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14168. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14169. }
  14170. }
  14171. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14172. }
  14173. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14174. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14175. const attachmentProperties = properties.get( texture[ i ] );
  14176. if ( attachmentProperties.__webglTexture ) {
  14177. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14178. info.memory.textures --;
  14179. }
  14180. properties.remove( texture[ i ] );
  14181. }
  14182. }
  14183. properties.remove( texture );
  14184. properties.remove( renderTarget );
  14185. }
  14186. //
  14187. let textureUnits = 0;
  14188. function resetTextureUnits() {
  14189. textureUnits = 0;
  14190. }
  14191. function allocateTextureUnit() {
  14192. const textureUnit = textureUnits;
  14193. if ( textureUnit >= maxTextures ) {
  14194. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14195. }
  14196. textureUnits += 1;
  14197. return textureUnit;
  14198. }
  14199. function getTextureCacheKey( texture ) {
  14200. const array = [];
  14201. array.push( texture.wrapS );
  14202. array.push( texture.wrapT );
  14203. array.push( texture.wrapR || 0 );
  14204. array.push( texture.magFilter );
  14205. array.push( texture.minFilter );
  14206. array.push( texture.anisotropy );
  14207. array.push( texture.internalFormat );
  14208. array.push( texture.format );
  14209. array.push( texture.type );
  14210. array.push( texture.generateMipmaps );
  14211. array.push( texture.premultiplyAlpha );
  14212. array.push( texture.flipY );
  14213. array.push( texture.unpackAlignment );
  14214. array.push( texture.colorSpace );
  14215. return array.join();
  14216. }
  14217. //
  14218. function setTexture2D( texture, slot ) {
  14219. const textureProperties = properties.get( texture );
  14220. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14221. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14222. const image = texture.image;
  14223. if ( image === null ) {
  14224. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14225. } else if ( image.complete === false ) {
  14226. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14227. } else {
  14228. uploadTexture( textureProperties, texture, slot );
  14229. return;
  14230. }
  14231. }
  14232. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14233. }
  14234. function setTexture2DArray( texture, slot ) {
  14235. const textureProperties = properties.get( texture );
  14236. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14237. uploadTexture( textureProperties, texture, slot );
  14238. return;
  14239. }
  14240. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14241. }
  14242. function setTexture3D( texture, slot ) {
  14243. const textureProperties = properties.get( texture );
  14244. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14245. uploadTexture( textureProperties, texture, slot );
  14246. return;
  14247. }
  14248. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14249. }
  14250. function setTextureCube( texture, slot ) {
  14251. const textureProperties = properties.get( texture );
  14252. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14253. uploadCubeTexture( textureProperties, texture, slot );
  14254. return;
  14255. }
  14256. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14257. }
  14258. const wrappingToGL = {
  14259. [ RepeatWrapping ]: _gl.REPEAT,
  14260. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14261. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14262. };
  14263. const filterToGL = {
  14264. [ NearestFilter ]: _gl.NEAREST,
  14265. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14266. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14267. [ LinearFilter ]: _gl.LINEAR,
  14268. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14269. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14270. };
  14271. function setTextureParameters( textureType, texture, supportsMips ) {
  14272. if ( supportsMips ) {
  14273. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14274. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14275. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14276. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14277. }
  14278. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14279. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14280. } else {
  14281. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14282. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14283. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14284. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  14285. }
  14286. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14287. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14288. }
  14289. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14290. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14291. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14292. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14293. }
  14294. }
  14295. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14296. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14297. if ( texture.magFilter === NearestFilter ) return;
  14298. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14299. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14300. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14301. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14302. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14303. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14304. }
  14305. }
  14306. }
  14307. function initTexture( textureProperties, texture ) {
  14308. let forceUpload = false;
  14309. if ( textureProperties.__webglInit === undefined ) {
  14310. textureProperties.__webglInit = true;
  14311. texture.addEventListener( 'dispose', onTextureDispose );
  14312. }
  14313. // create Source <-> WebGLTextures mapping if necessary
  14314. const source = texture.source;
  14315. let webglTextures = _sources.get( source );
  14316. if ( webglTextures === undefined ) {
  14317. webglTextures = {};
  14318. _sources.set( source, webglTextures );
  14319. }
  14320. // check if there is already a WebGLTexture object for the given texture parameters
  14321. const textureCacheKey = getTextureCacheKey( texture );
  14322. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14323. // if not, create a new instance of WebGLTexture
  14324. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14325. // create new entry
  14326. webglTextures[ textureCacheKey ] = {
  14327. texture: _gl.createTexture(),
  14328. usedTimes: 0
  14329. };
  14330. info.memory.textures ++;
  14331. // when a new instance of WebGLTexture was created, a texture upload is required
  14332. // even if the image contents are identical
  14333. forceUpload = true;
  14334. }
  14335. webglTextures[ textureCacheKey ].usedTimes ++;
  14336. // every time the texture cache key changes, it's necessary to check if an instance of
  14337. // WebGLTexture can be deleted in order to avoid a memory leak.
  14338. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14339. if ( webglTexture !== undefined ) {
  14340. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14341. if ( webglTexture.usedTimes === 0 ) {
  14342. deleteTexture( texture );
  14343. }
  14344. }
  14345. // store references to cache key and WebGLTexture object
  14346. textureProperties.__cacheKey = textureCacheKey;
  14347. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14348. }
  14349. return forceUpload;
  14350. }
  14351. function uploadTexture( textureProperties, texture, slot ) {
  14352. let textureType = _gl.TEXTURE_2D;
  14353. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14354. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14355. const forceUpload = initTexture( textureProperties, texture );
  14356. const source = texture.source;
  14357. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14358. const sourceProperties = properties.get( source );
  14359. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14360. state.activeTexture( _gl.TEXTURE0 + slot );
  14361. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14362. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14363. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14364. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14365. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14366. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14367. image = verifyColorSpace( texture, image );
  14368. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14369. glFormat = utils.convert( texture.format, texture.colorSpace );
  14370. let glType = utils.convert( texture.type ),
  14371. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14372. setTextureParameters( textureType, texture, supportsMips );
  14373. let mipmap;
  14374. const mipmaps = texture.mipmaps;
  14375. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14376. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14377. const levels = getMipLevels( texture, image, supportsMips );
  14378. if ( texture.isDepthTexture ) {
  14379. // populate depth texture with dummy data
  14380. glInternalFormat = _gl.DEPTH_COMPONENT;
  14381. if ( isWebGL2 ) {
  14382. if ( texture.type === FloatType ) {
  14383. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14384. } else if ( texture.type === UnsignedIntType ) {
  14385. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14386. } else if ( texture.type === UnsignedInt248Type ) {
  14387. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14388. } else {
  14389. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14390. }
  14391. } else {
  14392. if ( texture.type === FloatType ) {
  14393. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14394. }
  14395. }
  14396. // validation checks for WebGL 1
  14397. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14398. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14399. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14400. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14401. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14402. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14403. texture.type = UnsignedIntType;
  14404. glType = utils.convert( texture.type );
  14405. }
  14406. }
  14407. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14408. // Depth stencil textures need the DEPTH_STENCIL internal format
  14409. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14410. glInternalFormat = _gl.DEPTH_STENCIL;
  14411. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14412. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14413. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14414. if ( texture.type !== UnsignedInt248Type ) {
  14415. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14416. texture.type = UnsignedInt248Type;
  14417. glType = utils.convert( texture.type );
  14418. }
  14419. }
  14420. //
  14421. if ( allocateMemory ) {
  14422. if ( useTexStorage ) {
  14423. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14424. } else {
  14425. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14426. }
  14427. }
  14428. } else if ( texture.isDataTexture ) {
  14429. // use manually created mipmaps if available
  14430. // if there are no manual mipmaps
  14431. // set 0 level mipmap and then use GL to generate other mipmap levels
  14432. if ( mipmaps.length > 0 && supportsMips ) {
  14433. if ( useTexStorage && allocateMemory ) {
  14434. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14435. }
  14436. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14437. mipmap = mipmaps[ i ];
  14438. if ( useTexStorage ) {
  14439. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14440. } else {
  14441. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14442. }
  14443. }
  14444. texture.generateMipmaps = false;
  14445. } else {
  14446. if ( useTexStorage ) {
  14447. if ( allocateMemory ) {
  14448. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14449. }
  14450. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14451. } else {
  14452. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14453. }
  14454. }
  14455. } else if ( texture.isCompressedTexture ) {
  14456. if ( texture.isCompressedArrayTexture ) {
  14457. if ( useTexStorage && allocateMemory ) {
  14458. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14459. }
  14460. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14461. mipmap = mipmaps[ i ];
  14462. if ( texture.format !== RGBAFormat ) {
  14463. if ( glFormat !== null ) {
  14464. if ( useTexStorage ) {
  14465. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14466. } else {
  14467. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14468. }
  14469. } else {
  14470. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14471. }
  14472. } else {
  14473. if ( useTexStorage ) {
  14474. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14475. } else {
  14476. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14477. }
  14478. }
  14479. }
  14480. } else {
  14481. if ( useTexStorage && allocateMemory ) {
  14482. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14483. }
  14484. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14485. mipmap = mipmaps[ i ];
  14486. if ( texture.format !== RGBAFormat ) {
  14487. if ( glFormat !== null ) {
  14488. if ( useTexStorage ) {
  14489. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14490. } else {
  14491. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14492. }
  14493. } else {
  14494. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14495. }
  14496. } else {
  14497. if ( useTexStorage ) {
  14498. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14499. } else {
  14500. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14501. }
  14502. }
  14503. }
  14504. }
  14505. } else if ( texture.isDataArrayTexture ) {
  14506. if ( useTexStorage ) {
  14507. if ( allocateMemory ) {
  14508. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14509. }
  14510. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14511. } else {
  14512. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14513. }
  14514. } else if ( texture.isData3DTexture ) {
  14515. if ( useTexStorage ) {
  14516. if ( allocateMemory ) {
  14517. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14518. }
  14519. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14520. } else {
  14521. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14522. }
  14523. } else if ( texture.isFramebufferTexture ) {
  14524. if ( allocateMemory ) {
  14525. if ( useTexStorage ) {
  14526. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14527. } else {
  14528. let width = image.width, height = image.height;
  14529. for ( let i = 0; i < levels; i ++ ) {
  14530. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14531. width >>= 1;
  14532. height >>= 1;
  14533. }
  14534. }
  14535. }
  14536. } else {
  14537. // regular Texture (image, video, canvas)
  14538. // use manually created mipmaps if available
  14539. // if there are no manual mipmaps
  14540. // set 0 level mipmap and then use GL to generate other mipmap levels
  14541. if ( mipmaps.length > 0 && supportsMips ) {
  14542. if ( useTexStorage && allocateMemory ) {
  14543. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14544. }
  14545. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14546. mipmap = mipmaps[ i ];
  14547. if ( useTexStorage ) {
  14548. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14549. } else {
  14550. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14551. }
  14552. }
  14553. texture.generateMipmaps = false;
  14554. } else {
  14555. if ( useTexStorage ) {
  14556. if ( allocateMemory ) {
  14557. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14558. }
  14559. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14560. } else {
  14561. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14562. }
  14563. }
  14564. }
  14565. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14566. generateMipmap( textureType );
  14567. }
  14568. sourceProperties.__version = source.version;
  14569. if ( texture.onUpdate ) texture.onUpdate( texture );
  14570. }
  14571. textureProperties.__version = texture.version;
  14572. }
  14573. function uploadCubeTexture( textureProperties, texture, slot ) {
  14574. if ( texture.image.length !== 6 ) return;
  14575. const forceUpload = initTexture( textureProperties, texture );
  14576. const source = texture.source;
  14577. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14578. const sourceProperties = properties.get( source );
  14579. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14580. state.activeTexture( _gl.TEXTURE0 + slot );
  14581. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14582. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14583. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14584. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14585. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14586. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14587. const cubeImage = [];
  14588. for ( let i = 0; i < 6; i ++ ) {
  14589. if ( ! isCompressed && ! isDataTexture ) {
  14590. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14591. } else {
  14592. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14593. }
  14594. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14595. }
  14596. const image = cubeImage[ 0 ],
  14597. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14598. glFormat = utils.convert( texture.format, texture.colorSpace ),
  14599. glType = utils.convert( texture.type ),
  14600. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14601. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14602. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14603. let levels = getMipLevels( texture, image, supportsMips );
  14604. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14605. let mipmaps;
  14606. if ( isCompressed ) {
  14607. if ( useTexStorage && allocateMemory ) {
  14608. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14609. }
  14610. for ( let i = 0; i < 6; i ++ ) {
  14611. mipmaps = cubeImage[ i ].mipmaps;
  14612. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14613. const mipmap = mipmaps[ j ];
  14614. if ( texture.format !== RGBAFormat ) {
  14615. if ( glFormat !== null ) {
  14616. if ( useTexStorage ) {
  14617. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14618. } else {
  14619. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14620. }
  14621. } else {
  14622. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14623. }
  14624. } else {
  14625. if ( useTexStorage ) {
  14626. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14627. } else {
  14628. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14629. }
  14630. }
  14631. }
  14632. }
  14633. } else {
  14634. mipmaps = texture.mipmaps;
  14635. if ( useTexStorage && allocateMemory ) {
  14636. // TODO: Uniformly handle mipmap definitions
  14637. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14638. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14639. if ( mipmaps.length > 0 ) levels ++;
  14640. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14641. }
  14642. for ( let i = 0; i < 6; i ++ ) {
  14643. if ( isDataTexture ) {
  14644. if ( useTexStorage ) {
  14645. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14646. } else {
  14647. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14648. }
  14649. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14650. const mipmap = mipmaps[ j ];
  14651. const mipmapImage = mipmap.image[ i ].image;
  14652. if ( useTexStorage ) {
  14653. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14654. } else {
  14655. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14656. }
  14657. }
  14658. } else {
  14659. if ( useTexStorage ) {
  14660. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14661. } else {
  14662. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14663. }
  14664. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14665. const mipmap = mipmaps[ j ];
  14666. if ( useTexStorage ) {
  14667. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14668. } else {
  14669. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14670. }
  14671. }
  14672. }
  14673. }
  14674. }
  14675. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14676. // We assume images for cube map have the same size.
  14677. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14678. }
  14679. sourceProperties.__version = source.version;
  14680. if ( texture.onUpdate ) texture.onUpdate( texture );
  14681. }
  14682. textureProperties.__version = texture.version;
  14683. }
  14684. // Render targets
  14685. // Setup storage for target texture and bind it to correct framebuffer
  14686. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14687. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14688. const glType = utils.convert( texture.type );
  14689. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14690. const renderTargetProperties = properties.get( renderTarget );
  14691. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14692. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14693. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14694. } else {
  14695. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14696. }
  14697. }
  14698. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14699. if ( useMultisampledRTT( renderTarget ) ) {
  14700. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14701. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14702. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14703. }
  14704. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14705. }
  14706. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14707. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14708. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14709. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14710. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14711. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14712. const depthTexture = renderTarget.depthTexture;
  14713. if ( depthTexture && depthTexture.isDepthTexture ) {
  14714. if ( depthTexture.type === FloatType ) {
  14715. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14716. } else if ( depthTexture.type === UnsignedIntType ) {
  14717. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14718. }
  14719. }
  14720. const samples = getRenderTargetSamples( renderTarget );
  14721. if ( useMultisampledRTT( renderTarget ) ) {
  14722. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14723. } else {
  14724. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14725. }
  14726. } else {
  14727. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14728. }
  14729. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14730. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14731. const samples = getRenderTargetSamples( renderTarget );
  14732. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14733. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14734. } else if ( useMultisampledRTT( renderTarget ) ) {
  14735. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14736. } else {
  14737. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14738. }
  14739. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14740. } else {
  14741. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14742. for ( let i = 0; i < textures.length; i ++ ) {
  14743. const texture = textures[ i ];
  14744. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14745. const glType = utils.convert( texture.type );
  14746. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14747. const samples = getRenderTargetSamples( renderTarget );
  14748. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14749. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14750. } else if ( useMultisampledRTT( renderTarget ) ) {
  14751. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14752. } else {
  14753. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14754. }
  14755. }
  14756. }
  14757. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14758. }
  14759. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14760. function setupDepthTexture( framebuffer, renderTarget ) {
  14761. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14762. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14763. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14764. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14765. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14766. }
  14767. // upload an empty depth texture with framebuffer size
  14768. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14769. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14770. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14771. renderTarget.depthTexture.image.width = renderTarget.width;
  14772. renderTarget.depthTexture.image.height = renderTarget.height;
  14773. renderTarget.depthTexture.needsUpdate = true;
  14774. }
  14775. setTexture2D( renderTarget.depthTexture, 0 );
  14776. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14777. const samples = getRenderTargetSamples( renderTarget );
  14778. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14779. if ( useMultisampledRTT( renderTarget ) ) {
  14780. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14781. } else {
  14782. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14783. }
  14784. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14785. if ( useMultisampledRTT( renderTarget ) ) {
  14786. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14787. } else {
  14788. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14789. }
  14790. } else {
  14791. throw new Error( 'Unknown depthTexture format' );
  14792. }
  14793. }
  14794. // Setup GL resources for a non-texture depth buffer
  14795. function setupDepthRenderbuffer( renderTarget ) {
  14796. const renderTargetProperties = properties.get( renderTarget );
  14797. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14798. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14799. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14800. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14801. } else {
  14802. if ( isCube ) {
  14803. renderTargetProperties.__webglDepthbuffer = [];
  14804. for ( let i = 0; i < 6; i ++ ) {
  14805. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14806. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14807. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14808. }
  14809. } else {
  14810. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14811. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14812. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14813. }
  14814. }
  14815. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14816. }
  14817. // rebind framebuffer with external textures
  14818. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14819. const renderTargetProperties = properties.get( renderTarget );
  14820. if ( colorTexture !== undefined ) {
  14821. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  14822. }
  14823. if ( depthTexture !== undefined ) {
  14824. setupDepthRenderbuffer( renderTarget );
  14825. }
  14826. }
  14827. // Set up GL resources for the render target
  14828. function setupRenderTarget( renderTarget ) {
  14829. const texture = renderTarget.texture;
  14830. const renderTargetProperties = properties.get( renderTarget );
  14831. const textureProperties = properties.get( texture );
  14832. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14833. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14834. if ( textureProperties.__webglTexture === undefined ) {
  14835. textureProperties.__webglTexture = _gl.createTexture();
  14836. }
  14837. textureProperties.__version = texture.version;
  14838. info.memory.textures ++;
  14839. }
  14840. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14841. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14842. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14843. // Setup framebuffer
  14844. if ( isCube ) {
  14845. renderTargetProperties.__webglFramebuffer = [];
  14846. for ( let i = 0; i < 6; i ++ ) {
  14847. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14848. }
  14849. } else {
  14850. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14851. if ( isMultipleRenderTargets ) {
  14852. if ( capabilities.drawBuffers ) {
  14853. const textures = renderTarget.texture;
  14854. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14855. const attachmentProperties = properties.get( textures[ i ] );
  14856. if ( attachmentProperties.__webglTexture === undefined ) {
  14857. attachmentProperties.__webglTexture = _gl.createTexture();
  14858. info.memory.textures ++;
  14859. }
  14860. }
  14861. } else {
  14862. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14863. }
  14864. }
  14865. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14866. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14867. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14868. renderTargetProperties.__webglColorRenderbuffer = [];
  14869. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14870. for ( let i = 0; i < textures.length; i ++ ) {
  14871. const texture = textures[ i ];
  14872. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14873. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14874. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14875. const glType = utils.convert( texture.type );
  14876. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  14877. const samples = getRenderTargetSamples( renderTarget );
  14878. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14879. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14880. }
  14881. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14882. if ( renderTarget.depthBuffer ) {
  14883. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14884. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14885. }
  14886. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14887. }
  14888. }
  14889. // Setup color buffer
  14890. if ( isCube ) {
  14891. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  14892. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14893. for ( let i = 0; i < 6; i ++ ) {
  14894. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14895. }
  14896. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14897. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14898. }
  14899. state.unbindTexture();
  14900. } else if ( isMultipleRenderTargets ) {
  14901. const textures = renderTarget.texture;
  14902. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14903. const attachment = textures[ i ];
  14904. const attachmentProperties = properties.get( attachment );
  14905. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  14906. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  14907. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );
  14908. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14909. generateMipmap( _gl.TEXTURE_2D );
  14910. }
  14911. }
  14912. state.unbindTexture();
  14913. } else {
  14914. let glTextureType = _gl.TEXTURE_2D;
  14915. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14916. if ( isWebGL2 ) {
  14917. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14918. } else {
  14919. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14920. }
  14921. }
  14922. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14923. setTextureParameters( glTextureType, texture, supportsMips );
  14924. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );
  14925. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14926. generateMipmap( glTextureType );
  14927. }
  14928. state.unbindTexture();
  14929. }
  14930. // Setup depth and stencil buffers
  14931. if ( renderTarget.depthBuffer ) {
  14932. setupDepthRenderbuffer( renderTarget );
  14933. }
  14934. }
  14935. function updateRenderTargetMipmap( renderTarget ) {
  14936. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14937. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14938. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14939. const texture = textures[ i ];
  14940. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14941. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14942. const webglTexture = properties.get( texture ).__webglTexture;
  14943. state.bindTexture( target, webglTexture );
  14944. generateMipmap( target );
  14945. state.unbindTexture();
  14946. }
  14947. }
  14948. }
  14949. function updateMultisampleRenderTarget( renderTarget ) {
  14950. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14951. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14952. const width = renderTarget.width;
  14953. const height = renderTarget.height;
  14954. let mask = _gl.COLOR_BUFFER_BIT;
  14955. const invalidationArray = [];
  14956. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14957. const renderTargetProperties = properties.get( renderTarget );
  14958. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14959. // If MRT we need to remove FBO attachments
  14960. if ( isMultipleRenderTargets ) {
  14961. for ( let i = 0; i < textures.length; i ++ ) {
  14962. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14963. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  14964. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14965. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  14966. }
  14967. }
  14968. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14969. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14970. for ( let i = 0; i < textures.length; i ++ ) {
  14971. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  14972. if ( renderTarget.depthBuffer ) {
  14973. invalidationArray.push( depthStyle );
  14974. }
  14975. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14976. if ( ignoreDepthValues === false ) {
  14977. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  14978. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  14979. }
  14980. if ( isMultipleRenderTargets ) {
  14981. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14982. }
  14983. if ( ignoreDepthValues === true ) {
  14984. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  14985. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  14986. }
  14987. if ( isMultipleRenderTargets ) {
  14988. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14989. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  14990. }
  14991. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  14992. if ( supportsInvalidateFramebuffer ) {
  14993. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  14994. }
  14995. }
  14996. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  14997. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  14998. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14999. if ( isMultipleRenderTargets ) {
  15000. for ( let i = 0; i < textures.length; i ++ ) {
  15001. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15002. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15003. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15004. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15005. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15006. }
  15007. }
  15008. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15009. }
  15010. }
  15011. function getRenderTargetSamples( renderTarget ) {
  15012. return Math.min( maxSamples, renderTarget.samples );
  15013. }
  15014. function useMultisampledRTT( renderTarget ) {
  15015. const renderTargetProperties = properties.get( renderTarget );
  15016. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15017. }
  15018. function updateVideoTexture( texture ) {
  15019. const frame = info.render.frame;
  15020. // Check the last frame we updated the VideoTexture
  15021. if ( _videoTextures.get( texture ) !== frame ) {
  15022. _videoTextures.set( texture, frame );
  15023. texture.update();
  15024. }
  15025. }
  15026. function verifyColorSpace( texture, image ) {
  15027. const colorSpace = texture.colorSpace;
  15028. const format = texture.format;
  15029. const type = texture.type;
  15030. if ( texture.isCompressedTexture === true || texture.format === _SRGBAFormat ) return image;
  15031. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15032. // sRGB
  15033. if ( colorSpace === SRGBColorSpace ) {
  15034. if ( isWebGL2 === false ) {
  15035. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  15036. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  15037. texture.format = _SRGBAFormat;
  15038. // it's not possible to generate mips in WebGL 1 with this extension
  15039. texture.minFilter = LinearFilter;
  15040. texture.generateMipmaps = false;
  15041. } else {
  15042. // slow fallback (CPU decode)
  15043. image = ImageUtils.sRGBToLinear( image );
  15044. }
  15045. } else {
  15046. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15047. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15048. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15049. }
  15050. }
  15051. } else {
  15052. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15053. }
  15054. }
  15055. return image;
  15056. }
  15057. //
  15058. this.allocateTextureUnit = allocateTextureUnit;
  15059. this.resetTextureUnits = resetTextureUnits;
  15060. this.setTexture2D = setTexture2D;
  15061. this.setTexture2DArray = setTexture2DArray;
  15062. this.setTexture3D = setTexture3D;
  15063. this.setTextureCube = setTextureCube;
  15064. this.rebindTextures = rebindTextures;
  15065. this.setupRenderTarget = setupRenderTarget;
  15066. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15067. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15068. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15069. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15070. this.useMultisampledRTT = useMultisampledRTT;
  15071. }
  15072. function WebGLUtils( gl, extensions, capabilities ) {
  15073. const isWebGL2 = capabilities.isWebGL2;
  15074. function convert( p, colorSpace = NoColorSpace ) {
  15075. let extension;
  15076. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15077. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15078. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15079. if ( p === ByteType ) return gl.BYTE;
  15080. if ( p === ShortType ) return gl.SHORT;
  15081. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15082. if ( p === IntType ) return gl.INT;
  15083. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15084. if ( p === FloatType ) return gl.FLOAT;
  15085. if ( p === HalfFloatType ) {
  15086. if ( isWebGL2 ) return gl.HALF_FLOAT;
  15087. extension = extensions.get( 'OES_texture_half_float' );
  15088. if ( extension !== null ) {
  15089. return extension.HALF_FLOAT_OES;
  15090. } else {
  15091. return null;
  15092. }
  15093. }
  15094. if ( p === AlphaFormat ) return gl.ALPHA;
  15095. if ( p === RGBAFormat ) return gl.RGBA;
  15096. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15097. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15098. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15099. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15100. // WebGL 1 sRGB fallback
  15101. if ( p === _SRGBAFormat ) {
  15102. extension = extensions.get( 'EXT_sRGB' );
  15103. if ( extension !== null ) {
  15104. return extension.SRGB_ALPHA_EXT;
  15105. } else {
  15106. return null;
  15107. }
  15108. }
  15109. // WebGL2 formats.
  15110. if ( p === RedFormat ) return gl.RED;
  15111. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15112. if ( p === RGFormat ) return gl.RG;
  15113. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15114. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15115. // S3TC
  15116. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15117. if ( colorSpace === SRGBColorSpace ) {
  15118. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15119. if ( extension !== null ) {
  15120. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15121. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15122. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15123. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15124. } else {
  15125. return null;
  15126. }
  15127. } else {
  15128. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15129. if ( extension !== null ) {
  15130. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15131. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15132. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15133. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15134. } else {
  15135. return null;
  15136. }
  15137. }
  15138. }
  15139. // PVRTC
  15140. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15141. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15142. if ( extension !== null ) {
  15143. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15144. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15145. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15146. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15147. } else {
  15148. return null;
  15149. }
  15150. }
  15151. // ETC1
  15152. if ( p === RGB_ETC1_Format ) {
  15153. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15154. if ( extension !== null ) {
  15155. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15156. } else {
  15157. return null;
  15158. }
  15159. }
  15160. // ETC2
  15161. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15162. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15163. if ( extension !== null ) {
  15164. if ( p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15165. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15166. } else {
  15167. return null;
  15168. }
  15169. }
  15170. // ASTC
  15171. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15172. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15173. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15174. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15175. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15176. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15177. if ( extension !== null ) {
  15178. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15179. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15180. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15181. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15182. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15183. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15184. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15185. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15186. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15187. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15188. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15189. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15190. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15191. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15192. } else {
  15193. return null;
  15194. }
  15195. }
  15196. // BPTC
  15197. if ( p === RGBA_BPTC_Format ) {
  15198. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15199. if ( extension !== null ) {
  15200. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15201. } else {
  15202. return null;
  15203. }
  15204. }
  15205. // RGTC
  15206. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15207. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15208. if ( extension !== null ) {
  15209. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15210. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15211. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15212. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15213. } else {
  15214. return null;
  15215. }
  15216. }
  15217. //
  15218. if ( p === UnsignedInt248Type ) {
  15219. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  15220. extension = extensions.get( 'WEBGL_depth_texture' );
  15221. if ( extension !== null ) {
  15222. return extension.UNSIGNED_INT_24_8_WEBGL;
  15223. } else {
  15224. return null;
  15225. }
  15226. }
  15227. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15228. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15229. }
  15230. return { convert: convert };
  15231. }
  15232. class ArrayCamera extends PerspectiveCamera {
  15233. constructor( array = [] ) {
  15234. super();
  15235. this.isArrayCamera = true;
  15236. this.cameras = array;
  15237. }
  15238. }
  15239. class Group extends Object3D {
  15240. constructor() {
  15241. super();
  15242. this.isGroup = true;
  15243. this.type = 'Group';
  15244. }
  15245. }
  15246. const _moveEvent = { type: 'move' };
  15247. class WebXRController {
  15248. constructor() {
  15249. this._targetRay = null;
  15250. this._grip = null;
  15251. this._hand = null;
  15252. }
  15253. getHandSpace() {
  15254. if ( this._hand === null ) {
  15255. this._hand = new Group();
  15256. this._hand.matrixAutoUpdate = false;
  15257. this._hand.visible = false;
  15258. this._hand.joints = {};
  15259. this._hand.inputState = { pinching: false };
  15260. }
  15261. return this._hand;
  15262. }
  15263. getTargetRaySpace() {
  15264. if ( this._targetRay === null ) {
  15265. this._targetRay = new Group();
  15266. this._targetRay.matrixAutoUpdate = false;
  15267. this._targetRay.visible = false;
  15268. this._targetRay.hasLinearVelocity = false;
  15269. this._targetRay.linearVelocity = new Vector3();
  15270. this._targetRay.hasAngularVelocity = false;
  15271. this._targetRay.angularVelocity = new Vector3();
  15272. }
  15273. return this._targetRay;
  15274. }
  15275. getGripSpace() {
  15276. if ( this._grip === null ) {
  15277. this._grip = new Group();
  15278. this._grip.matrixAutoUpdate = false;
  15279. this._grip.visible = false;
  15280. this._grip.hasLinearVelocity = false;
  15281. this._grip.linearVelocity = new Vector3();
  15282. this._grip.hasAngularVelocity = false;
  15283. this._grip.angularVelocity = new Vector3();
  15284. }
  15285. return this._grip;
  15286. }
  15287. dispatchEvent( event ) {
  15288. if ( this._targetRay !== null ) {
  15289. this._targetRay.dispatchEvent( event );
  15290. }
  15291. if ( this._grip !== null ) {
  15292. this._grip.dispatchEvent( event );
  15293. }
  15294. if ( this._hand !== null ) {
  15295. this._hand.dispatchEvent( event );
  15296. }
  15297. return this;
  15298. }
  15299. connect( inputSource ) {
  15300. if ( inputSource && inputSource.hand ) {
  15301. const hand = this._hand;
  15302. if ( hand ) {
  15303. for ( const inputjoint of inputSource.hand.values() ) {
  15304. // Initialize hand with joints when connected
  15305. this._getHandJoint( hand, inputjoint );
  15306. }
  15307. }
  15308. }
  15309. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15310. return this;
  15311. }
  15312. disconnect( inputSource ) {
  15313. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15314. if ( this._targetRay !== null ) {
  15315. this._targetRay.visible = false;
  15316. }
  15317. if ( this._grip !== null ) {
  15318. this._grip.visible = false;
  15319. }
  15320. if ( this._hand !== null ) {
  15321. this._hand.visible = false;
  15322. }
  15323. return this;
  15324. }
  15325. update( inputSource, frame, referenceSpace ) {
  15326. let inputPose = null;
  15327. let gripPose = null;
  15328. let handPose = null;
  15329. const targetRay = this._targetRay;
  15330. const grip = this._grip;
  15331. const hand = this._hand;
  15332. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15333. if ( hand && inputSource.hand ) {
  15334. handPose = true;
  15335. for ( const inputjoint of inputSource.hand.values() ) {
  15336. // Update the joints groups with the XRJoint poses
  15337. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15338. // The transform of this joint will be updated with the joint pose on each frame
  15339. const joint = this._getHandJoint( hand, inputjoint );
  15340. if ( jointPose !== null ) {
  15341. joint.matrix.fromArray( jointPose.transform.matrix );
  15342. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15343. joint.matrixWorldNeedsUpdate = true;
  15344. joint.jointRadius = jointPose.radius;
  15345. }
  15346. joint.visible = jointPose !== null;
  15347. }
  15348. // Custom events
  15349. // Check pinchz
  15350. const indexTip = hand.joints[ 'index-finger-tip' ];
  15351. const thumbTip = hand.joints[ 'thumb-tip' ];
  15352. const distance = indexTip.position.distanceTo( thumbTip.position );
  15353. const distanceToPinch = 0.02;
  15354. const threshold = 0.005;
  15355. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15356. hand.inputState.pinching = false;
  15357. this.dispatchEvent( {
  15358. type: 'pinchend',
  15359. handedness: inputSource.handedness,
  15360. target: this
  15361. } );
  15362. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15363. hand.inputState.pinching = true;
  15364. this.dispatchEvent( {
  15365. type: 'pinchstart',
  15366. handedness: inputSource.handedness,
  15367. target: this
  15368. } );
  15369. }
  15370. } else {
  15371. if ( grip !== null && inputSource.gripSpace ) {
  15372. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15373. if ( gripPose !== null ) {
  15374. grip.matrix.fromArray( gripPose.transform.matrix );
  15375. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15376. grip.matrixWorldNeedsUpdate = true;
  15377. if ( gripPose.linearVelocity ) {
  15378. grip.hasLinearVelocity = true;
  15379. grip.linearVelocity.copy( gripPose.linearVelocity );
  15380. } else {
  15381. grip.hasLinearVelocity = false;
  15382. }
  15383. if ( gripPose.angularVelocity ) {
  15384. grip.hasAngularVelocity = true;
  15385. grip.angularVelocity.copy( gripPose.angularVelocity );
  15386. } else {
  15387. grip.hasAngularVelocity = false;
  15388. }
  15389. }
  15390. }
  15391. }
  15392. if ( targetRay !== null ) {
  15393. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15394. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15395. if ( inputPose === null && gripPose !== null ) {
  15396. inputPose = gripPose;
  15397. }
  15398. if ( inputPose !== null ) {
  15399. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15400. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15401. targetRay.matrixWorldNeedsUpdate = true;
  15402. if ( inputPose.linearVelocity ) {
  15403. targetRay.hasLinearVelocity = true;
  15404. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15405. } else {
  15406. targetRay.hasLinearVelocity = false;
  15407. }
  15408. if ( inputPose.angularVelocity ) {
  15409. targetRay.hasAngularVelocity = true;
  15410. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15411. } else {
  15412. targetRay.hasAngularVelocity = false;
  15413. }
  15414. this.dispatchEvent( _moveEvent );
  15415. }
  15416. }
  15417. }
  15418. if ( targetRay !== null ) {
  15419. targetRay.visible = ( inputPose !== null );
  15420. }
  15421. if ( grip !== null ) {
  15422. grip.visible = ( gripPose !== null );
  15423. }
  15424. if ( hand !== null ) {
  15425. hand.visible = ( handPose !== null );
  15426. }
  15427. return this;
  15428. }
  15429. // private method
  15430. _getHandJoint( hand, inputjoint ) {
  15431. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15432. const joint = new Group();
  15433. joint.matrixAutoUpdate = false;
  15434. joint.visible = false;
  15435. hand.joints[ inputjoint.jointName ] = joint;
  15436. hand.add( joint );
  15437. }
  15438. return hand.joints[ inputjoint.jointName ];
  15439. }
  15440. }
  15441. class DepthTexture extends Texture {
  15442. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15443. format = format !== undefined ? format : DepthFormat;
  15444. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15445. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15446. }
  15447. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15448. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15449. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15450. this.isDepthTexture = true;
  15451. this.image = { width: width, height: height };
  15452. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15453. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15454. this.flipY = false;
  15455. this.generateMipmaps = false;
  15456. }
  15457. }
  15458. class WebXRManager extends EventDispatcher {
  15459. constructor( renderer, gl ) {
  15460. super();
  15461. const scope = this;
  15462. let session = null;
  15463. let framebufferScaleFactor = 1.0;
  15464. let referenceSpace = null;
  15465. let referenceSpaceType = 'local-floor';
  15466. // Set default foveation to maximum.
  15467. let foveation = 1.0;
  15468. let customReferenceSpace = null;
  15469. let pose = null;
  15470. let glBinding = null;
  15471. let glProjLayer = null;
  15472. let glBaseLayer = null;
  15473. let xrFrame = null;
  15474. const attributes = gl.getContextAttributes();
  15475. let initialRenderTarget = null;
  15476. let newRenderTarget = null;
  15477. const controllers = [];
  15478. const controllerInputSources = [];
  15479. const planes = new Set();
  15480. const planesLastChangedTimes = new Map();
  15481. //
  15482. const cameraL = new PerspectiveCamera();
  15483. cameraL.layers.enable( 1 );
  15484. cameraL.viewport = new Vector4();
  15485. const cameraR = new PerspectiveCamera();
  15486. cameraR.layers.enable( 2 );
  15487. cameraR.viewport = new Vector4();
  15488. const cameras = [ cameraL, cameraR ];
  15489. const cameraVR = new ArrayCamera();
  15490. cameraVR.layers.enable( 1 );
  15491. cameraVR.layers.enable( 2 );
  15492. let _currentDepthNear = null;
  15493. let _currentDepthFar = null;
  15494. //
  15495. this.cameraAutoUpdate = true;
  15496. this.enabled = false;
  15497. this.isPresenting = false;
  15498. this.getController = function ( index ) {
  15499. let controller = controllers[ index ];
  15500. if ( controller === undefined ) {
  15501. controller = new WebXRController();
  15502. controllers[ index ] = controller;
  15503. }
  15504. return controller.getTargetRaySpace();
  15505. };
  15506. this.getControllerGrip = function ( index ) {
  15507. let controller = controllers[ index ];
  15508. if ( controller === undefined ) {
  15509. controller = new WebXRController();
  15510. controllers[ index ] = controller;
  15511. }
  15512. return controller.getGripSpace();
  15513. };
  15514. this.getHand = function ( index ) {
  15515. let controller = controllers[ index ];
  15516. if ( controller === undefined ) {
  15517. controller = new WebXRController();
  15518. controllers[ index ] = controller;
  15519. }
  15520. return controller.getHandSpace();
  15521. };
  15522. //
  15523. function onSessionEvent( event ) {
  15524. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15525. if ( controllerIndex === - 1 ) {
  15526. return;
  15527. }
  15528. const controller = controllers[ controllerIndex ];
  15529. if ( controller !== undefined ) {
  15530. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  15531. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15532. }
  15533. }
  15534. function onSessionEnd() {
  15535. session.removeEventListener( 'select', onSessionEvent );
  15536. session.removeEventListener( 'selectstart', onSessionEvent );
  15537. session.removeEventListener( 'selectend', onSessionEvent );
  15538. session.removeEventListener( 'squeeze', onSessionEvent );
  15539. session.removeEventListener( 'squeezestart', onSessionEvent );
  15540. session.removeEventListener( 'squeezeend', onSessionEvent );
  15541. session.removeEventListener( 'end', onSessionEnd );
  15542. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15543. for ( let i = 0; i < controllers.length; i ++ ) {
  15544. const inputSource = controllerInputSources[ i ];
  15545. if ( inputSource === null ) continue;
  15546. controllerInputSources[ i ] = null;
  15547. controllers[ i ].disconnect( inputSource );
  15548. }
  15549. _currentDepthNear = null;
  15550. _currentDepthFar = null;
  15551. // restore framebuffer/rendering state
  15552. renderer.setRenderTarget( initialRenderTarget );
  15553. glBaseLayer = null;
  15554. glProjLayer = null;
  15555. glBinding = null;
  15556. session = null;
  15557. newRenderTarget = null;
  15558. //
  15559. animation.stop();
  15560. scope.isPresenting = false;
  15561. scope.dispatchEvent( { type: 'sessionend' } );
  15562. }
  15563. this.setFramebufferScaleFactor = function ( value ) {
  15564. framebufferScaleFactor = value;
  15565. if ( scope.isPresenting === true ) {
  15566. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15567. }
  15568. };
  15569. this.setReferenceSpaceType = function ( value ) {
  15570. referenceSpaceType = value;
  15571. if ( scope.isPresenting === true ) {
  15572. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15573. }
  15574. };
  15575. this.getReferenceSpace = function () {
  15576. return customReferenceSpace || referenceSpace;
  15577. };
  15578. this.setReferenceSpace = function ( space ) {
  15579. customReferenceSpace = space;
  15580. };
  15581. this.getBaseLayer = function () {
  15582. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15583. };
  15584. this.getBinding = function () {
  15585. return glBinding;
  15586. };
  15587. this.getFrame = function () {
  15588. return xrFrame;
  15589. };
  15590. this.getSession = function () {
  15591. return session;
  15592. };
  15593. this.setSession = async function ( value ) {
  15594. session = value;
  15595. if ( session !== null ) {
  15596. initialRenderTarget = renderer.getRenderTarget();
  15597. session.addEventListener( 'select', onSessionEvent );
  15598. session.addEventListener( 'selectstart', onSessionEvent );
  15599. session.addEventListener( 'selectend', onSessionEvent );
  15600. session.addEventListener( 'squeeze', onSessionEvent );
  15601. session.addEventListener( 'squeezestart', onSessionEvent );
  15602. session.addEventListener( 'squeezeend', onSessionEvent );
  15603. session.addEventListener( 'end', onSessionEnd );
  15604. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15605. if ( attributes.xrCompatible !== true ) {
  15606. await gl.makeXRCompatible();
  15607. }
  15608. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15609. const layerInit = {
  15610. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15611. alpha: true,
  15612. depth: attributes.depth,
  15613. stencil: attributes.stencil,
  15614. framebufferScaleFactor: framebufferScaleFactor
  15615. };
  15616. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15617. session.updateRenderState( { baseLayer: glBaseLayer } );
  15618. newRenderTarget = new WebGLRenderTarget(
  15619. glBaseLayer.framebufferWidth,
  15620. glBaseLayer.framebufferHeight,
  15621. {
  15622. format: RGBAFormat,
  15623. type: UnsignedByteType,
  15624. colorSpace: renderer.outputColorSpace,
  15625. stencilBuffer: attributes.stencil
  15626. }
  15627. );
  15628. } else {
  15629. let depthFormat = null;
  15630. let depthType = null;
  15631. let glDepthFormat = null;
  15632. if ( attributes.depth ) {
  15633. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15634. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15635. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15636. }
  15637. const projectionlayerInit = {
  15638. colorFormat: gl.RGBA8,
  15639. depthFormat: glDepthFormat,
  15640. scaleFactor: framebufferScaleFactor
  15641. };
  15642. glBinding = new XRWebGLBinding( session, gl );
  15643. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15644. session.updateRenderState( { layers: [ glProjLayer ] } );
  15645. newRenderTarget = new WebGLRenderTarget(
  15646. glProjLayer.textureWidth,
  15647. glProjLayer.textureHeight,
  15648. {
  15649. format: RGBAFormat,
  15650. type: UnsignedByteType,
  15651. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15652. stencilBuffer: attributes.stencil,
  15653. colorSpace: renderer.outputColorSpace,
  15654. samples: attributes.antialias ? 4 : 0
  15655. } );
  15656. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15657. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15658. }
  15659. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15660. this.setFoveation( foveation );
  15661. customReferenceSpace = null;
  15662. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15663. animation.setContext( session );
  15664. animation.start();
  15665. scope.isPresenting = true;
  15666. scope.dispatchEvent( { type: 'sessionstart' } );
  15667. }
  15668. };
  15669. this.getEnvironmentBlendMode = function () {
  15670. if ( session !== null ) {
  15671. return session.environmentBlendMode;
  15672. }
  15673. };
  15674. function onInputSourcesChange( event ) {
  15675. // Notify disconnected
  15676. for ( let i = 0; i < event.removed.length; i ++ ) {
  15677. const inputSource = event.removed[ i ];
  15678. const index = controllerInputSources.indexOf( inputSource );
  15679. if ( index >= 0 ) {
  15680. controllerInputSources[ index ] = null;
  15681. controllers[ index ].disconnect( inputSource );
  15682. }
  15683. }
  15684. // Notify connected
  15685. for ( let i = 0; i < event.added.length; i ++ ) {
  15686. const inputSource = event.added[ i ];
  15687. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15688. if ( controllerIndex === - 1 ) {
  15689. // Assign input source a controller that currently has no input source
  15690. for ( let i = 0; i < controllers.length; i ++ ) {
  15691. if ( i >= controllerInputSources.length ) {
  15692. controllerInputSources.push( inputSource );
  15693. controllerIndex = i;
  15694. break;
  15695. } else if ( controllerInputSources[ i ] === null ) {
  15696. controllerInputSources[ i ] = inputSource;
  15697. controllerIndex = i;
  15698. break;
  15699. }
  15700. }
  15701. // If all controllers do currently receive input we ignore new ones
  15702. if ( controllerIndex === - 1 ) break;
  15703. }
  15704. const controller = controllers[ controllerIndex ];
  15705. if ( controller ) {
  15706. controller.connect( inputSource );
  15707. }
  15708. }
  15709. }
  15710. //
  15711. const cameraLPos = new Vector3();
  15712. const cameraRPos = new Vector3();
  15713. /**
  15714. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15715. * the cameras' projection and world matrices have already been set.
  15716. * And that near and far planes are identical for both cameras.
  15717. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15718. */
  15719. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15720. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15721. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15722. const ipd = cameraLPos.distanceTo( cameraRPos );
  15723. const projL = cameraL.projectionMatrix.elements;
  15724. const projR = cameraR.projectionMatrix.elements;
  15725. // VR systems will have identical far and near planes, and
  15726. // most likely identical top and bottom frustum extents.
  15727. // Use the left camera for these values.
  15728. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15729. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15730. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15731. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15732. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15733. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15734. const left = near * leftFov;
  15735. const right = near * rightFov;
  15736. // Calculate the new camera's position offset from the
  15737. // left camera. xOffset should be roughly half `ipd`.
  15738. const zOffset = ipd / ( - leftFov + rightFov );
  15739. const xOffset = zOffset * - leftFov;
  15740. // TODO: Better way to apply this offset?
  15741. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15742. camera.translateX( xOffset );
  15743. camera.translateZ( zOffset );
  15744. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15745. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15746. // Find the union of the frustum values of the cameras and scale
  15747. // the values so that the near plane's position does not change in world space,
  15748. // although must now be relative to the new union camera.
  15749. const near2 = near + zOffset;
  15750. const far2 = far + zOffset;
  15751. const left2 = left - xOffset;
  15752. const right2 = right + ( ipd - xOffset );
  15753. const top2 = topFov * far / far2 * near2;
  15754. const bottom2 = bottomFov * far / far2 * near2;
  15755. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15756. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15757. }
  15758. function updateCamera( camera, parent ) {
  15759. if ( parent === null ) {
  15760. camera.matrixWorld.copy( camera.matrix );
  15761. } else {
  15762. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15763. }
  15764. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15765. }
  15766. this.updateCamera = function ( camera ) {
  15767. if ( session === null ) return;
  15768. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15769. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15770. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15771. // Note that the new renderState won't apply until the next frame. See #18320
  15772. session.updateRenderState( {
  15773. depthNear: cameraVR.near,
  15774. depthFar: cameraVR.far
  15775. } );
  15776. _currentDepthNear = cameraVR.near;
  15777. _currentDepthFar = cameraVR.far;
  15778. }
  15779. const parent = camera.parent;
  15780. const cameras = cameraVR.cameras;
  15781. updateCamera( cameraVR, parent );
  15782. for ( let i = 0; i < cameras.length; i ++ ) {
  15783. updateCamera( cameras[ i ], parent );
  15784. }
  15785. // update projection matrix for proper view frustum culling
  15786. if ( cameras.length === 2 ) {
  15787. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15788. } else {
  15789. // assume single camera setup (AR)
  15790. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15791. }
  15792. // update user camera and its children
  15793. updateUserCamera( camera, cameraVR, parent );
  15794. };
  15795. function updateUserCamera( camera, cameraVR, parent ) {
  15796. if ( parent === null ) {
  15797. camera.matrix.copy( cameraVR.matrixWorld );
  15798. } else {
  15799. camera.matrix.copy( parent.matrixWorld );
  15800. camera.matrix.invert();
  15801. camera.matrix.multiply( cameraVR.matrixWorld );
  15802. }
  15803. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15804. camera.updateMatrixWorld( true );
  15805. const children = camera.children;
  15806. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15807. children[ i ].updateMatrixWorld( true );
  15808. }
  15809. camera.projectionMatrix.copy( cameraVR.projectionMatrix );
  15810. camera.projectionMatrixInverse.copy( cameraVR.projectionMatrixInverse );
  15811. if ( camera.isPerspectiveCamera ) {
  15812. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  15813. camera.zoom = 1;
  15814. }
  15815. }
  15816. this.getCamera = function () {
  15817. return cameraVR;
  15818. };
  15819. this.getFoveation = function () {
  15820. if ( glProjLayer === null && glBaseLayer === null ) {
  15821. return undefined;
  15822. }
  15823. return foveation;
  15824. };
  15825. this.setFoveation = function ( value ) {
  15826. // 0 = no foveation = full resolution
  15827. // 1 = maximum foveation = the edges render at lower resolution
  15828. foveation = value;
  15829. if ( glProjLayer !== null ) {
  15830. glProjLayer.fixedFoveation = value;
  15831. }
  15832. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15833. glBaseLayer.fixedFoveation = value;
  15834. }
  15835. };
  15836. this.getPlanes = function () {
  15837. return planes;
  15838. };
  15839. // Animation Loop
  15840. let onAnimationFrameCallback = null;
  15841. function onAnimationFrame( time, frame ) {
  15842. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15843. xrFrame = frame;
  15844. if ( pose !== null ) {
  15845. const views = pose.views;
  15846. if ( glBaseLayer !== null ) {
  15847. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15848. renderer.setRenderTarget( newRenderTarget );
  15849. }
  15850. let cameraVRNeedsUpdate = false;
  15851. // check if it's necessary to rebuild cameraVR's camera list
  15852. if ( views.length !== cameraVR.cameras.length ) {
  15853. cameraVR.cameras.length = 0;
  15854. cameraVRNeedsUpdate = true;
  15855. }
  15856. for ( let i = 0; i < views.length; i ++ ) {
  15857. const view = views[ i ];
  15858. let viewport = null;
  15859. if ( glBaseLayer !== null ) {
  15860. viewport = glBaseLayer.getViewport( view );
  15861. } else {
  15862. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15863. viewport = glSubImage.viewport;
  15864. // For side-by-side projection, we only produce a single texture for both eyes.
  15865. if ( i === 0 ) {
  15866. renderer.setRenderTargetTextures(
  15867. newRenderTarget,
  15868. glSubImage.colorTexture,
  15869. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15870. renderer.setRenderTarget( newRenderTarget );
  15871. }
  15872. }
  15873. let camera = cameras[ i ];
  15874. if ( camera === undefined ) {
  15875. camera = new PerspectiveCamera();
  15876. camera.layers.enable( i );
  15877. camera.viewport = new Vector4();
  15878. cameras[ i ] = camera;
  15879. }
  15880. camera.matrix.fromArray( view.transform.matrix );
  15881. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15882. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15883. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15884. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15885. if ( i === 0 ) {
  15886. cameraVR.matrix.copy( camera.matrix );
  15887. cameraVR.matrix.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15888. }
  15889. if ( cameraVRNeedsUpdate === true ) {
  15890. cameraVR.cameras.push( camera );
  15891. }
  15892. }
  15893. }
  15894. //
  15895. for ( let i = 0; i < controllers.length; i ++ ) {
  15896. const inputSource = controllerInputSources[ i ];
  15897. const controller = controllers[ i ];
  15898. if ( inputSource !== null && controller !== undefined ) {
  15899. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15900. }
  15901. }
  15902. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15903. if ( frame.detectedPlanes ) {
  15904. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15905. let planesToRemove = null;
  15906. for ( const plane of planes ) {
  15907. if ( ! frame.detectedPlanes.has( plane ) ) {
  15908. if ( planesToRemove === null ) {
  15909. planesToRemove = [];
  15910. }
  15911. planesToRemove.push( plane );
  15912. }
  15913. }
  15914. if ( planesToRemove !== null ) {
  15915. for ( const plane of planesToRemove ) {
  15916. planes.delete( plane );
  15917. planesLastChangedTimes.delete( plane );
  15918. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15919. }
  15920. }
  15921. for ( const plane of frame.detectedPlanes ) {
  15922. if ( ! planes.has( plane ) ) {
  15923. planes.add( plane );
  15924. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15925. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15926. } else {
  15927. const lastKnownTime = planesLastChangedTimes.get( plane );
  15928. if ( plane.lastChangedTime > lastKnownTime ) {
  15929. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15930. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15931. }
  15932. }
  15933. }
  15934. }
  15935. xrFrame = null;
  15936. }
  15937. const animation = new WebGLAnimation();
  15938. animation.setAnimationLoop( onAnimationFrame );
  15939. this.setAnimationLoop = function ( callback ) {
  15940. onAnimationFrameCallback = callback;
  15941. };
  15942. this.dispose = function () {};
  15943. }
  15944. }
  15945. function WebGLMaterials( renderer, properties ) {
  15946. function refreshTransformUniform( map, uniform ) {
  15947. if ( map.matrixAutoUpdate === true ) {
  15948. map.updateMatrix();
  15949. }
  15950. uniform.value.copy( map.matrix );
  15951. }
  15952. function refreshFogUniforms( uniforms, fog ) {
  15953. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15954. if ( fog.isFog ) {
  15955. uniforms.fogNear.value = fog.near;
  15956. uniforms.fogFar.value = fog.far;
  15957. } else if ( fog.isFogExp2 ) {
  15958. uniforms.fogDensity.value = fog.density;
  15959. }
  15960. }
  15961. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15962. if ( material.isMeshBasicMaterial ) {
  15963. refreshUniformsCommon( uniforms, material );
  15964. } else if ( material.isMeshLambertMaterial ) {
  15965. refreshUniformsCommon( uniforms, material );
  15966. } else if ( material.isMeshToonMaterial ) {
  15967. refreshUniformsCommon( uniforms, material );
  15968. refreshUniformsToon( uniforms, material );
  15969. } else if ( material.isMeshPhongMaterial ) {
  15970. refreshUniformsCommon( uniforms, material );
  15971. refreshUniformsPhong( uniforms, material );
  15972. } else if ( material.isMeshStandardMaterial ) {
  15973. refreshUniformsCommon( uniforms, material );
  15974. refreshUniformsStandard( uniforms, material );
  15975. if ( material.isMeshPhysicalMaterial ) {
  15976. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15977. }
  15978. } else if ( material.isMeshMatcapMaterial ) {
  15979. refreshUniformsCommon( uniforms, material );
  15980. refreshUniformsMatcap( uniforms, material );
  15981. } else if ( material.isMeshDepthMaterial ) {
  15982. refreshUniformsCommon( uniforms, material );
  15983. } else if ( material.isMeshDistanceMaterial ) {
  15984. refreshUniformsCommon( uniforms, material );
  15985. refreshUniformsDistance( uniforms, material );
  15986. } else if ( material.isMeshNormalMaterial ) {
  15987. refreshUniformsCommon( uniforms, material );
  15988. } else if ( material.isLineBasicMaterial ) {
  15989. refreshUniformsLine( uniforms, material );
  15990. if ( material.isLineDashedMaterial ) {
  15991. refreshUniformsDash( uniforms, material );
  15992. }
  15993. } else if ( material.isPointsMaterial ) {
  15994. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15995. } else if ( material.isSpriteMaterial ) {
  15996. refreshUniformsSprites( uniforms, material );
  15997. } else if ( material.isShadowMaterial ) {
  15998. uniforms.color.value.copy( material.color );
  15999. uniforms.opacity.value = material.opacity;
  16000. } else if ( material.isShaderMaterial ) {
  16001. material.uniformsNeedUpdate = false; // #15581
  16002. }
  16003. }
  16004. function refreshUniformsCommon( uniforms, material ) {
  16005. uniforms.opacity.value = material.opacity;
  16006. if ( material.color ) {
  16007. uniforms.diffuse.value.copy( material.color );
  16008. }
  16009. if ( material.emissive ) {
  16010. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16011. }
  16012. if ( material.map ) {
  16013. uniforms.map.value = material.map;
  16014. refreshTransformUniform( material.map, uniforms.mapTransform );
  16015. }
  16016. if ( material.alphaMap ) {
  16017. uniforms.alphaMap.value = material.alphaMap;
  16018. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16019. }
  16020. if ( material.bumpMap ) {
  16021. uniforms.bumpMap.value = material.bumpMap;
  16022. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16023. uniforms.bumpScale.value = material.bumpScale;
  16024. if ( material.side === BackSide ) {
  16025. uniforms.bumpScale.value *= - 1;
  16026. }
  16027. }
  16028. if ( material.normalMap ) {
  16029. uniforms.normalMap.value = material.normalMap;
  16030. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16031. uniforms.normalScale.value.copy( material.normalScale );
  16032. if ( material.side === BackSide ) {
  16033. uniforms.normalScale.value.negate();
  16034. }
  16035. }
  16036. if ( material.displacementMap ) {
  16037. uniforms.displacementMap.value = material.displacementMap;
  16038. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16039. uniforms.displacementScale.value = material.displacementScale;
  16040. uniforms.displacementBias.value = material.displacementBias;
  16041. }
  16042. if ( material.emissiveMap ) {
  16043. uniforms.emissiveMap.value = material.emissiveMap;
  16044. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16045. }
  16046. if ( material.specularMap ) {
  16047. uniforms.specularMap.value = material.specularMap;
  16048. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16049. }
  16050. if ( material.alphaTest > 0 ) {
  16051. uniforms.alphaTest.value = material.alphaTest;
  16052. }
  16053. const envMap = properties.get( material ).envMap;
  16054. if ( envMap ) {
  16055. uniforms.envMap.value = envMap;
  16056. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16057. uniforms.reflectivity.value = material.reflectivity;
  16058. uniforms.ior.value = material.ior;
  16059. uniforms.refractionRatio.value = material.refractionRatio;
  16060. }
  16061. if ( material.lightMap ) {
  16062. uniforms.lightMap.value = material.lightMap;
  16063. // artist-friendly light intensity scaling factor
  16064. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  16065. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16066. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16067. }
  16068. if ( material.aoMap ) {
  16069. uniforms.aoMap.value = material.aoMap;
  16070. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16071. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16072. }
  16073. }
  16074. function refreshUniformsLine( uniforms, material ) {
  16075. uniforms.diffuse.value.copy( material.color );
  16076. uniforms.opacity.value = material.opacity;
  16077. if ( material.map ) {
  16078. uniforms.map.value = material.map;
  16079. refreshTransformUniform( material.map, uniforms.mapTransform );
  16080. }
  16081. }
  16082. function refreshUniformsDash( uniforms, material ) {
  16083. uniforms.dashSize.value = material.dashSize;
  16084. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16085. uniforms.scale.value = material.scale;
  16086. }
  16087. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16088. uniforms.diffuse.value.copy( material.color );
  16089. uniforms.opacity.value = material.opacity;
  16090. uniforms.size.value = material.size * pixelRatio;
  16091. uniforms.scale.value = height * 0.5;
  16092. if ( material.map ) {
  16093. uniforms.map.value = material.map;
  16094. refreshTransformUniform( material.map, uniforms.uvTransform );
  16095. }
  16096. if ( material.alphaMap ) {
  16097. uniforms.alphaMap.value = material.alphaMap;
  16098. }
  16099. if ( material.alphaTest > 0 ) {
  16100. uniforms.alphaTest.value = material.alphaTest;
  16101. }
  16102. }
  16103. function refreshUniformsSprites( uniforms, material ) {
  16104. uniforms.diffuse.value.copy( material.color );
  16105. uniforms.opacity.value = material.opacity;
  16106. uniforms.rotation.value = material.rotation;
  16107. if ( material.map ) {
  16108. uniforms.map.value = material.map;
  16109. refreshTransformUniform( material.map, uniforms.mapTransform );
  16110. }
  16111. if ( material.alphaMap ) {
  16112. uniforms.alphaMap.value = material.alphaMap;
  16113. }
  16114. if ( material.alphaTest > 0 ) {
  16115. uniforms.alphaTest.value = material.alphaTest;
  16116. }
  16117. }
  16118. function refreshUniformsPhong( uniforms, material ) {
  16119. uniforms.specular.value.copy( material.specular );
  16120. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16121. }
  16122. function refreshUniformsToon( uniforms, material ) {
  16123. if ( material.gradientMap ) {
  16124. uniforms.gradientMap.value = material.gradientMap;
  16125. }
  16126. }
  16127. function refreshUniformsStandard( uniforms, material ) {
  16128. uniforms.metalness.value = material.metalness;
  16129. if ( material.metalnessMap ) {
  16130. uniforms.metalnessMap.value = material.metalnessMap;
  16131. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16132. }
  16133. uniforms.roughness.value = material.roughness;
  16134. if ( material.roughnessMap ) {
  16135. uniforms.roughnessMap.value = material.roughnessMap;
  16136. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16137. }
  16138. const envMap = properties.get( material ).envMap;
  16139. if ( envMap ) {
  16140. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16141. uniforms.envMapIntensity.value = material.envMapIntensity;
  16142. }
  16143. }
  16144. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16145. uniforms.ior.value = material.ior; // also part of uniforms common
  16146. if ( material.sheen > 0 ) {
  16147. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16148. uniforms.sheenRoughness.value = material.sheenRoughness;
  16149. if ( material.sheenColorMap ) {
  16150. uniforms.sheenColorMap.value = material.sheenColorMap;
  16151. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16152. }
  16153. if ( material.sheenRoughnessMap ) {
  16154. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16155. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16156. }
  16157. }
  16158. if ( material.clearcoat > 0 ) {
  16159. uniforms.clearcoat.value = material.clearcoat;
  16160. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16161. if ( material.clearcoatMap ) {
  16162. uniforms.clearcoatMap.value = material.clearcoatMap;
  16163. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16164. }
  16165. if ( material.clearcoatRoughnessMap ) {
  16166. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16167. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16168. }
  16169. if ( material.clearcoatNormalMap ) {
  16170. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16171. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16172. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16173. if ( material.side === BackSide ) {
  16174. uniforms.clearcoatNormalScale.value.negate();
  16175. }
  16176. }
  16177. }
  16178. if ( material.iridescence > 0 ) {
  16179. uniforms.iridescence.value = material.iridescence;
  16180. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16181. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16182. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16183. if ( material.iridescenceMap ) {
  16184. uniforms.iridescenceMap.value = material.iridescenceMap;
  16185. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16186. }
  16187. if ( material.iridescenceThicknessMap ) {
  16188. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16189. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16190. }
  16191. }
  16192. if ( material.transmission > 0 ) {
  16193. uniforms.transmission.value = material.transmission;
  16194. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16195. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16196. if ( material.transmissionMap ) {
  16197. uniforms.transmissionMap.value = material.transmissionMap;
  16198. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16199. }
  16200. uniforms.thickness.value = material.thickness;
  16201. if ( material.thicknessMap ) {
  16202. uniforms.thicknessMap.value = material.thicknessMap;
  16203. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16204. }
  16205. uniforms.attenuationDistance.value = material.attenuationDistance;
  16206. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16207. }
  16208. uniforms.specularIntensity.value = material.specularIntensity;
  16209. uniforms.specularColor.value.copy( material.specularColor );
  16210. if ( material.specularColorMap ) {
  16211. uniforms.specularColorMap.value = material.specularColorMap;
  16212. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16213. }
  16214. if ( material.specularIntensityMap ) {
  16215. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16216. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16217. }
  16218. }
  16219. function refreshUniformsMatcap( uniforms, material ) {
  16220. if ( material.matcap ) {
  16221. uniforms.matcap.value = material.matcap;
  16222. }
  16223. }
  16224. function refreshUniformsDistance( uniforms, material ) {
  16225. const light = properties.get( material ).light;
  16226. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16227. uniforms.nearDistance.value = light.shadow.camera.near;
  16228. uniforms.farDistance.value = light.shadow.camera.far;
  16229. }
  16230. return {
  16231. refreshFogUniforms: refreshFogUniforms,
  16232. refreshMaterialUniforms: refreshMaterialUniforms
  16233. };
  16234. }
  16235. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16236. let buffers = {};
  16237. let updateList = {};
  16238. let allocatedBindingPoints = [];
  16239. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  16240. function bind( uniformsGroup, program ) {
  16241. const webglProgram = program.program;
  16242. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16243. }
  16244. function update( uniformsGroup, program ) {
  16245. let buffer = buffers[ uniformsGroup.id ];
  16246. if ( buffer === undefined ) {
  16247. prepareUniformsGroup( uniformsGroup );
  16248. buffer = createBuffer( uniformsGroup );
  16249. buffers[ uniformsGroup.id ] = buffer;
  16250. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16251. }
  16252. // ensure to update the binding points/block indices mapping for this program
  16253. const webglProgram = program.program;
  16254. state.updateUBOMapping( uniformsGroup, webglProgram );
  16255. // update UBO once per frame
  16256. const frame = info.render.frame;
  16257. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16258. updateBufferData( uniformsGroup );
  16259. updateList[ uniformsGroup.id ] = frame;
  16260. }
  16261. }
  16262. function createBuffer( uniformsGroup ) {
  16263. // the setup of an UBO is independent of a particular shader program but global
  16264. const bindingPointIndex = allocateBindingPointIndex();
  16265. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16266. const buffer = gl.createBuffer();
  16267. const size = uniformsGroup.__size;
  16268. const usage = uniformsGroup.usage;
  16269. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16270. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16271. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16272. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16273. return buffer;
  16274. }
  16275. function allocateBindingPointIndex() {
  16276. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16277. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16278. allocatedBindingPoints.push( i );
  16279. return i;
  16280. }
  16281. }
  16282. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16283. return 0;
  16284. }
  16285. function updateBufferData( uniformsGroup ) {
  16286. const buffer = buffers[ uniformsGroup.id ];
  16287. const uniforms = uniformsGroup.uniforms;
  16288. const cache = uniformsGroup.__cache;
  16289. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16290. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16291. const uniform = uniforms[ i ];
  16292. // partly update the buffer if necessary
  16293. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16294. const offset = uniform.__offset;
  16295. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16296. let arrayOffset = 0;
  16297. for ( let i = 0; i < values.length; i ++ ) {
  16298. const value = values[ i ];
  16299. const info = getUniformSize( value );
  16300. if ( typeof value === 'number' ) {
  16301. uniform.__data[ 0 ] = value;
  16302. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16303. } else if ( value.isMatrix3 ) {
  16304. // manually converting 3x3 to 3x4
  16305. uniform.__data[ 0 ] = value.elements[ 0 ];
  16306. uniform.__data[ 1 ] = value.elements[ 1 ];
  16307. uniform.__data[ 2 ] = value.elements[ 2 ];
  16308. uniform.__data[ 3 ] = value.elements[ 0 ];
  16309. uniform.__data[ 4 ] = value.elements[ 3 ];
  16310. uniform.__data[ 5 ] = value.elements[ 4 ];
  16311. uniform.__data[ 6 ] = value.elements[ 5 ];
  16312. uniform.__data[ 7 ] = value.elements[ 0 ];
  16313. uniform.__data[ 8 ] = value.elements[ 6 ];
  16314. uniform.__data[ 9 ] = value.elements[ 7 ];
  16315. uniform.__data[ 10 ] = value.elements[ 8 ];
  16316. uniform.__data[ 11 ] = value.elements[ 0 ];
  16317. } else {
  16318. value.toArray( uniform.__data, arrayOffset );
  16319. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16320. }
  16321. }
  16322. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16323. }
  16324. }
  16325. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16326. }
  16327. function hasUniformChanged( uniform, index, cache ) {
  16328. const value = uniform.value;
  16329. if ( cache[ index ] === undefined ) {
  16330. // cache entry does not exist so far
  16331. if ( typeof value === 'number' ) {
  16332. cache[ index ] = value;
  16333. } else {
  16334. const values = Array.isArray( value ) ? value : [ value ];
  16335. const tempValues = [];
  16336. for ( let i = 0; i < values.length; i ++ ) {
  16337. tempValues.push( values[ i ].clone() );
  16338. }
  16339. cache[ index ] = tempValues;
  16340. }
  16341. return true;
  16342. } else {
  16343. // compare current value with cached entry
  16344. if ( typeof value === 'number' ) {
  16345. if ( cache[ index ] !== value ) {
  16346. cache[ index ] = value;
  16347. return true;
  16348. }
  16349. } else {
  16350. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16351. const values = Array.isArray( value ) ? value : [ value ];
  16352. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16353. const cachedObject = cachedObjects[ i ];
  16354. if ( cachedObject.equals( values[ i ] ) === false ) {
  16355. cachedObject.copy( values[ i ] );
  16356. return true;
  16357. }
  16358. }
  16359. }
  16360. }
  16361. return false;
  16362. }
  16363. function prepareUniformsGroup( uniformsGroup ) {
  16364. // determine total buffer size according to the STD140 layout
  16365. // Hint: STD140 is the only supported layout in WebGL 2
  16366. const uniforms = uniformsGroup.uniforms;
  16367. let offset = 0; // global buffer offset in bytes
  16368. const chunkSize = 16; // size of a chunk in bytes
  16369. let chunkOffset = 0; // offset within a single chunk in bytes
  16370. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16371. const uniform = uniforms[ i ];
  16372. const infos = {
  16373. boundary: 0, // bytes
  16374. storage: 0 // bytes
  16375. };
  16376. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16377. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16378. const value = values[ j ];
  16379. const info = getUniformSize( value );
  16380. infos.boundary += info.boundary;
  16381. infos.storage += info.storage;
  16382. }
  16383. // the following two properties will be used for partial buffer updates
  16384. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16385. uniform.__offset = offset;
  16386. //
  16387. if ( i > 0 ) {
  16388. chunkOffset = offset % chunkSize;
  16389. const remainingSizeInChunk = chunkSize - chunkOffset;
  16390. // check for chunk overflow
  16391. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16392. // add padding and adjust offset
  16393. offset += ( chunkSize - chunkOffset );
  16394. uniform.__offset = offset;
  16395. }
  16396. }
  16397. offset += infos.storage;
  16398. }
  16399. // ensure correct final padding
  16400. chunkOffset = offset % chunkSize;
  16401. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16402. //
  16403. uniformsGroup.__size = offset;
  16404. uniformsGroup.__cache = {};
  16405. return this;
  16406. }
  16407. function getUniformSize( value ) {
  16408. const info = {
  16409. boundary: 0, // bytes
  16410. storage: 0 // bytes
  16411. };
  16412. // determine sizes according to STD140
  16413. if ( typeof value === 'number' ) {
  16414. // float/int
  16415. info.boundary = 4;
  16416. info.storage = 4;
  16417. } else if ( value.isVector2 ) {
  16418. // vec2
  16419. info.boundary = 8;
  16420. info.storage = 8;
  16421. } else if ( value.isVector3 || value.isColor ) {
  16422. // vec3
  16423. info.boundary = 16;
  16424. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16425. } else if ( value.isVector4 ) {
  16426. // vec4
  16427. info.boundary = 16;
  16428. info.storage = 16;
  16429. } else if ( value.isMatrix3 ) {
  16430. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16431. info.boundary = 48;
  16432. info.storage = 48;
  16433. } else if ( value.isMatrix4 ) {
  16434. // mat4
  16435. info.boundary = 64;
  16436. info.storage = 64;
  16437. } else if ( value.isTexture ) {
  16438. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16439. } else {
  16440. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16441. }
  16442. return info;
  16443. }
  16444. function onUniformsGroupsDispose( event ) {
  16445. const uniformsGroup = event.target;
  16446. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16447. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16448. allocatedBindingPoints.splice( index, 1 );
  16449. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16450. delete buffers[ uniformsGroup.id ];
  16451. delete updateList[ uniformsGroup.id ];
  16452. }
  16453. function dispose() {
  16454. for ( const id in buffers ) {
  16455. gl.deleteBuffer( buffers[ id ] );
  16456. }
  16457. allocatedBindingPoints = [];
  16458. buffers = {};
  16459. updateList = {};
  16460. }
  16461. return {
  16462. bind: bind,
  16463. update: update,
  16464. dispose: dispose
  16465. };
  16466. }
  16467. function createCanvasElement() {
  16468. const canvas = createElementNS( 'canvas' );
  16469. canvas.style.display = 'block';
  16470. return canvas;
  16471. }
  16472. class WebGLRenderer {
  16473. constructor( parameters = {} ) {
  16474. const {
  16475. canvas = createCanvasElement(),
  16476. context = null,
  16477. depth = true,
  16478. stencil = true,
  16479. alpha = false,
  16480. antialias = false,
  16481. premultipliedAlpha = true,
  16482. preserveDrawingBuffer = false,
  16483. powerPreference = 'default',
  16484. failIfMajorPerformanceCaveat = false,
  16485. } = parameters;
  16486. this.isWebGLRenderer = true;
  16487. let _alpha;
  16488. if ( context !== null ) {
  16489. _alpha = context.getContextAttributes().alpha;
  16490. } else {
  16491. _alpha = alpha;
  16492. }
  16493. let currentRenderList = null;
  16494. let currentRenderState = null;
  16495. // render() can be called from within a callback triggered by another render.
  16496. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16497. const renderListStack = [];
  16498. const renderStateStack = [];
  16499. // public properties
  16500. this.domElement = canvas;
  16501. // Debug configuration container
  16502. this.debug = {
  16503. /**
  16504. * Enables error checking and reporting when shader programs are being compiled
  16505. * @type {boolean}
  16506. */
  16507. checkShaderErrors: true,
  16508. /**
  16509. * Callback for custom error reporting.
  16510. * @type {?Function}
  16511. */
  16512. onShaderError: null
  16513. };
  16514. // clearing
  16515. this.autoClear = true;
  16516. this.autoClearColor = true;
  16517. this.autoClearDepth = true;
  16518. this.autoClearStencil = true;
  16519. // scene graph
  16520. this.sortObjects = true;
  16521. // user-defined clipping
  16522. this.clippingPlanes = [];
  16523. this.localClippingEnabled = false;
  16524. // physically based shading
  16525. this.outputColorSpace = SRGBColorSpace;
  16526. // physical lights
  16527. this.useLegacyLights = true;
  16528. // tone mapping
  16529. this.toneMapping = NoToneMapping;
  16530. this.toneMappingExposure = 1.0;
  16531. // internal properties
  16532. const _this = this;
  16533. let _isContextLost = false;
  16534. // internal state cache
  16535. let _currentActiveCubeFace = 0;
  16536. let _currentActiveMipmapLevel = 0;
  16537. let _currentRenderTarget = null;
  16538. let _currentMaterialId = - 1;
  16539. let _currentCamera = null;
  16540. const _currentViewport = new Vector4();
  16541. const _currentScissor = new Vector4();
  16542. let _currentScissorTest = null;
  16543. //
  16544. let _width = canvas.width;
  16545. let _height = canvas.height;
  16546. let _pixelRatio = 1;
  16547. let _opaqueSort = null;
  16548. let _transparentSort = null;
  16549. const _viewport = new Vector4( 0, 0, _width, _height );
  16550. const _scissor = new Vector4( 0, 0, _width, _height );
  16551. let _scissorTest = false;
  16552. // frustum
  16553. const _frustum = new Frustum();
  16554. // clipping
  16555. let _clippingEnabled = false;
  16556. let _localClippingEnabled = false;
  16557. // transmission
  16558. let _transmissionRenderTarget = null;
  16559. // camera matrices cache
  16560. const _projScreenMatrix = new Matrix4();
  16561. const _vector3 = new Vector3();
  16562. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16563. function getTargetPixelRatio() {
  16564. return _currentRenderTarget === null ? _pixelRatio : 1;
  16565. }
  16566. // initialize
  16567. let _gl = context;
  16568. function getContext( contextNames, contextAttributes ) {
  16569. for ( let i = 0; i < contextNames.length; i ++ ) {
  16570. const contextName = contextNames[ i ];
  16571. const context = canvas.getContext( contextName, contextAttributes );
  16572. if ( context !== null ) return context;
  16573. }
  16574. return null;
  16575. }
  16576. try {
  16577. const contextAttributes = {
  16578. alpha: true,
  16579. depth,
  16580. stencil,
  16581. antialias,
  16582. premultipliedAlpha,
  16583. preserveDrawingBuffer,
  16584. powerPreference,
  16585. failIfMajorPerformanceCaveat,
  16586. };
  16587. // OffscreenCanvas does not have setAttribute, see #22811
  16588. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16589. // event listeners must be registered before WebGL context is created, see #12753
  16590. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16591. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16592. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16593. if ( _gl === null ) {
  16594. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16595. if ( _this.isWebGL1Renderer === true ) {
  16596. contextNames.shift();
  16597. }
  16598. _gl = getContext( contextNames, contextAttributes );
  16599. if ( _gl === null ) {
  16600. if ( getContext( contextNames ) ) {
  16601. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16602. } else {
  16603. throw new Error( 'Error creating WebGL context.' );
  16604. }
  16605. }
  16606. }
  16607. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16608. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16609. _gl.getShaderPrecisionFormat = function () {
  16610. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16611. };
  16612. }
  16613. } catch ( error ) {
  16614. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16615. throw error;
  16616. }
  16617. let extensions, capabilities, state, info;
  16618. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16619. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16620. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16621. let utils, bindingStates, uniformsGroups;
  16622. function initGLContext() {
  16623. extensions = new WebGLExtensions( _gl );
  16624. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16625. extensions.init( capabilities );
  16626. utils = new WebGLUtils( _gl, extensions, capabilities );
  16627. state = new WebGLState( _gl, extensions, capabilities );
  16628. info = new WebGLInfo( _gl );
  16629. properties = new WebGLProperties();
  16630. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16631. cubemaps = new WebGLCubeMaps( _this );
  16632. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16633. attributes = new WebGLAttributes( _gl, capabilities );
  16634. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16635. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16636. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16637. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16638. clipping = new WebGLClipping( properties );
  16639. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16640. materials = new WebGLMaterials( _this, properties );
  16641. renderLists = new WebGLRenderLists();
  16642. renderStates = new WebGLRenderStates( extensions, capabilities );
  16643. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16644. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16645. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16646. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16647. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16648. info.programs = programCache.programs;
  16649. _this.capabilities = capabilities;
  16650. _this.extensions = extensions;
  16651. _this.properties = properties;
  16652. _this.renderLists = renderLists;
  16653. _this.shadowMap = shadowMap;
  16654. _this.state = state;
  16655. _this.info = info;
  16656. }
  16657. initGLContext();
  16658. // xr
  16659. const xr = new WebXRManager( _this, _gl );
  16660. this.xr = xr;
  16661. // API
  16662. this.getContext = function () {
  16663. return _gl;
  16664. };
  16665. this.getContextAttributes = function () {
  16666. return _gl.getContextAttributes();
  16667. };
  16668. this.forceContextLoss = function () {
  16669. const extension = extensions.get( 'WEBGL_lose_context' );
  16670. if ( extension ) extension.loseContext();
  16671. };
  16672. this.forceContextRestore = function () {
  16673. const extension = extensions.get( 'WEBGL_lose_context' );
  16674. if ( extension ) extension.restoreContext();
  16675. };
  16676. this.getPixelRatio = function () {
  16677. return _pixelRatio;
  16678. };
  16679. this.setPixelRatio = function ( value ) {
  16680. if ( value === undefined ) return;
  16681. _pixelRatio = value;
  16682. this.setSize( _width, _height, false );
  16683. };
  16684. this.getSize = function ( target ) {
  16685. return target.set( _width, _height );
  16686. };
  16687. this.setSize = function ( width, height, updateStyle = true ) {
  16688. if ( xr.isPresenting ) {
  16689. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16690. return;
  16691. }
  16692. _width = width;
  16693. _height = height;
  16694. canvas.width = Math.floor( width * _pixelRatio );
  16695. canvas.height = Math.floor( height * _pixelRatio );
  16696. if ( updateStyle === true ) {
  16697. canvas.style.width = width + 'px';
  16698. canvas.style.height = height + 'px';
  16699. }
  16700. this.setViewport( 0, 0, width, height );
  16701. };
  16702. this.getDrawingBufferSize = function ( target ) {
  16703. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16704. };
  16705. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16706. _width = width;
  16707. _height = height;
  16708. _pixelRatio = pixelRatio;
  16709. canvas.width = Math.floor( width * pixelRatio );
  16710. canvas.height = Math.floor( height * pixelRatio );
  16711. this.setViewport( 0, 0, width, height );
  16712. };
  16713. this.getCurrentViewport = function ( target ) {
  16714. return target.copy( _currentViewport );
  16715. };
  16716. this.getViewport = function ( target ) {
  16717. return target.copy( _viewport );
  16718. };
  16719. this.setViewport = function ( x, y, width, height ) {
  16720. if ( x.isVector4 ) {
  16721. _viewport.set( x.x, x.y, x.z, x.w );
  16722. } else {
  16723. _viewport.set( x, y, width, height );
  16724. }
  16725. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16726. };
  16727. this.getScissor = function ( target ) {
  16728. return target.copy( _scissor );
  16729. };
  16730. this.setScissor = function ( x, y, width, height ) {
  16731. if ( x.isVector4 ) {
  16732. _scissor.set( x.x, x.y, x.z, x.w );
  16733. } else {
  16734. _scissor.set( x, y, width, height );
  16735. }
  16736. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16737. };
  16738. this.getScissorTest = function () {
  16739. return _scissorTest;
  16740. };
  16741. this.setScissorTest = function ( boolean ) {
  16742. state.setScissorTest( _scissorTest = boolean );
  16743. };
  16744. this.setOpaqueSort = function ( method ) {
  16745. _opaqueSort = method;
  16746. };
  16747. this.setTransparentSort = function ( method ) {
  16748. _transparentSort = method;
  16749. };
  16750. // Clearing
  16751. this.getClearColor = function ( target ) {
  16752. return target.copy( background.getClearColor() );
  16753. };
  16754. this.setClearColor = function () {
  16755. background.setClearColor.apply( background, arguments );
  16756. };
  16757. this.getClearAlpha = function () {
  16758. return background.getClearAlpha();
  16759. };
  16760. this.setClearAlpha = function () {
  16761. background.setClearAlpha.apply( background, arguments );
  16762. };
  16763. this.clear = function ( color = true, depth = true, stencil = true ) {
  16764. let bits = 0;
  16765. if ( color ) bits |= _gl.COLOR_BUFFER_BIT;
  16766. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16767. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16768. _gl.clear( bits );
  16769. };
  16770. this.clearColor = function () {
  16771. this.clear( true, false, false );
  16772. };
  16773. this.clearDepth = function () {
  16774. this.clear( false, true, false );
  16775. };
  16776. this.clearStencil = function () {
  16777. this.clear( false, false, true );
  16778. };
  16779. //
  16780. this.dispose = function () {
  16781. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16782. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16783. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16784. renderLists.dispose();
  16785. renderStates.dispose();
  16786. properties.dispose();
  16787. cubemaps.dispose();
  16788. cubeuvmaps.dispose();
  16789. objects.dispose();
  16790. bindingStates.dispose();
  16791. uniformsGroups.dispose();
  16792. programCache.dispose();
  16793. xr.dispose();
  16794. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16795. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16796. if ( _transmissionRenderTarget ) {
  16797. _transmissionRenderTarget.dispose();
  16798. _transmissionRenderTarget = null;
  16799. }
  16800. animation.stop();
  16801. };
  16802. // Events
  16803. function onContextLost( event ) {
  16804. event.preventDefault();
  16805. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16806. _isContextLost = true;
  16807. }
  16808. function onContextRestore( /* event */ ) {
  16809. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16810. _isContextLost = false;
  16811. const infoAutoReset = info.autoReset;
  16812. const shadowMapEnabled = shadowMap.enabled;
  16813. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16814. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16815. const shadowMapType = shadowMap.type;
  16816. initGLContext();
  16817. info.autoReset = infoAutoReset;
  16818. shadowMap.enabled = shadowMapEnabled;
  16819. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16820. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16821. shadowMap.type = shadowMapType;
  16822. }
  16823. function onContextCreationError( event ) {
  16824. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16825. }
  16826. function onMaterialDispose( event ) {
  16827. const material = event.target;
  16828. material.removeEventListener( 'dispose', onMaterialDispose );
  16829. deallocateMaterial( material );
  16830. }
  16831. // Buffer deallocation
  16832. function deallocateMaterial( material ) {
  16833. releaseMaterialProgramReferences( material );
  16834. properties.remove( material );
  16835. }
  16836. function releaseMaterialProgramReferences( material ) {
  16837. const programs = properties.get( material ).programs;
  16838. if ( programs !== undefined ) {
  16839. programs.forEach( function ( program ) {
  16840. programCache.releaseProgram( program );
  16841. } );
  16842. if ( material.isShaderMaterial ) {
  16843. programCache.releaseShaderCache( material );
  16844. }
  16845. }
  16846. }
  16847. // Buffer rendering
  16848. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16849. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16850. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16851. const program = setProgram( camera, scene, geometry, material, object );
  16852. state.setMaterial( material, frontFaceCW );
  16853. //
  16854. let index = geometry.index;
  16855. let rangeFactor = 1;
  16856. if ( material.wireframe === true ) {
  16857. index = geometries.getWireframeAttribute( geometry );
  16858. rangeFactor = 2;
  16859. }
  16860. //
  16861. const drawRange = geometry.drawRange;
  16862. const position = geometry.attributes.position;
  16863. let drawStart = drawRange.start * rangeFactor;
  16864. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16865. if ( group !== null ) {
  16866. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16867. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16868. }
  16869. if ( index !== null ) {
  16870. drawStart = Math.max( drawStart, 0 );
  16871. drawEnd = Math.min( drawEnd, index.count );
  16872. } else if ( position !== undefined && position !== null ) {
  16873. drawStart = Math.max( drawStart, 0 );
  16874. drawEnd = Math.min( drawEnd, position.count );
  16875. }
  16876. const drawCount = drawEnd - drawStart;
  16877. if ( drawCount < 0 || drawCount === Infinity ) return;
  16878. //
  16879. bindingStates.setup( object, material, program, geometry, index );
  16880. let attribute;
  16881. let renderer = bufferRenderer;
  16882. if ( index !== null ) {
  16883. attribute = attributes.get( index );
  16884. renderer = indexedBufferRenderer;
  16885. renderer.setIndex( attribute );
  16886. }
  16887. //
  16888. if ( object.isMesh ) {
  16889. if ( material.wireframe === true ) {
  16890. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16891. renderer.setMode( _gl.LINES );
  16892. } else {
  16893. renderer.setMode( _gl.TRIANGLES );
  16894. }
  16895. } else if ( object.isLine ) {
  16896. let lineWidth = material.linewidth;
  16897. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16898. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16899. if ( object.isLineSegments ) {
  16900. renderer.setMode( _gl.LINES );
  16901. } else if ( object.isLineLoop ) {
  16902. renderer.setMode( _gl.LINE_LOOP );
  16903. } else {
  16904. renderer.setMode( _gl.LINE_STRIP );
  16905. }
  16906. } else if ( object.isPoints ) {
  16907. renderer.setMode( _gl.POINTS );
  16908. } else if ( object.isSprite ) {
  16909. renderer.setMode( _gl.TRIANGLES );
  16910. }
  16911. if ( object.isInstancedMesh ) {
  16912. renderer.renderInstances( drawStart, drawCount, object.count );
  16913. } else if ( geometry.isInstancedBufferGeometry ) {
  16914. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16915. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16916. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16917. } else {
  16918. renderer.render( drawStart, drawCount );
  16919. }
  16920. };
  16921. // Compile
  16922. this.compile = function ( scene, camera ) {
  16923. function prepare( material, scene, object ) {
  16924. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16925. material.side = BackSide;
  16926. material.needsUpdate = true;
  16927. getProgram( material, scene, object );
  16928. material.side = FrontSide;
  16929. material.needsUpdate = true;
  16930. getProgram( material, scene, object );
  16931. material.side = DoubleSide;
  16932. } else {
  16933. getProgram( material, scene, object );
  16934. }
  16935. }
  16936. currentRenderState = renderStates.get( scene );
  16937. currentRenderState.init();
  16938. renderStateStack.push( currentRenderState );
  16939. scene.traverseVisible( function ( object ) {
  16940. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16941. currentRenderState.pushLight( object );
  16942. if ( object.castShadow ) {
  16943. currentRenderState.pushShadow( object );
  16944. }
  16945. }
  16946. } );
  16947. currentRenderState.setupLights( _this.useLegacyLights );
  16948. scene.traverse( function ( object ) {
  16949. const material = object.material;
  16950. if ( material ) {
  16951. if ( Array.isArray( material ) ) {
  16952. for ( let i = 0; i < material.length; i ++ ) {
  16953. const material2 = material[ i ];
  16954. prepare( material2, scene, object );
  16955. }
  16956. } else {
  16957. prepare( material, scene, object );
  16958. }
  16959. }
  16960. } );
  16961. renderStateStack.pop();
  16962. currentRenderState = null;
  16963. };
  16964. // Animation Loop
  16965. let onAnimationFrameCallback = null;
  16966. function onAnimationFrame( time ) {
  16967. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16968. }
  16969. function onXRSessionStart() {
  16970. animation.stop();
  16971. }
  16972. function onXRSessionEnd() {
  16973. animation.start();
  16974. }
  16975. const animation = new WebGLAnimation();
  16976. animation.setAnimationLoop( onAnimationFrame );
  16977. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16978. this.setAnimationLoop = function ( callback ) {
  16979. onAnimationFrameCallback = callback;
  16980. xr.setAnimationLoop( callback );
  16981. ( callback === null ) ? animation.stop() : animation.start();
  16982. };
  16983. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16984. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16985. // Rendering
  16986. this.render = function ( scene, camera ) {
  16987. if ( camera !== undefined && camera.isCamera !== true ) {
  16988. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16989. return;
  16990. }
  16991. if ( _isContextLost === true ) return;
  16992. // update scene graph
  16993. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16994. // update camera matrices and frustum
  16995. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16996. if ( xr.enabled === true && xr.isPresenting === true ) {
  16997. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16998. camera = xr.getCamera(); // use XR camera for rendering
  16999. }
  17000. //
  17001. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17002. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17003. currentRenderState.init();
  17004. renderStateStack.push( currentRenderState );
  17005. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17006. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17007. _localClippingEnabled = this.localClippingEnabled;
  17008. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17009. currentRenderList = renderLists.get( scene, renderListStack.length );
  17010. currentRenderList.init();
  17011. renderListStack.push( currentRenderList );
  17012. projectObject( scene, camera, 0, _this.sortObjects );
  17013. currentRenderList.finish();
  17014. if ( _this.sortObjects === true ) {
  17015. currentRenderList.sort( _opaqueSort, _transparentSort );
  17016. }
  17017. //
  17018. if ( _clippingEnabled === true ) clipping.beginShadows();
  17019. const shadowsArray = currentRenderState.state.shadowsArray;
  17020. shadowMap.render( shadowsArray, scene, camera );
  17021. if ( _clippingEnabled === true ) clipping.endShadows();
  17022. //
  17023. if ( this.info.autoReset === true ) this.info.reset();
  17024. //
  17025. background.render( currentRenderList, scene );
  17026. // render scene
  17027. currentRenderState.setupLights( _this.useLegacyLights );
  17028. if ( camera.isArrayCamera ) {
  17029. const cameras = camera.cameras;
  17030. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17031. const camera2 = cameras[ i ];
  17032. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17033. }
  17034. } else {
  17035. renderScene( currentRenderList, scene, camera );
  17036. }
  17037. //
  17038. if ( _currentRenderTarget !== null ) {
  17039. // resolve multisample renderbuffers to a single-sample texture if necessary
  17040. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17041. // Generate mipmap if we're using any kind of mipmap filtering
  17042. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17043. }
  17044. //
  17045. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17046. // _gl.finish();
  17047. bindingStates.resetDefaultState();
  17048. _currentMaterialId = - 1;
  17049. _currentCamera = null;
  17050. renderStateStack.pop();
  17051. if ( renderStateStack.length > 0 ) {
  17052. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17053. } else {
  17054. currentRenderState = null;
  17055. }
  17056. renderListStack.pop();
  17057. if ( renderListStack.length > 0 ) {
  17058. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17059. } else {
  17060. currentRenderList = null;
  17061. }
  17062. };
  17063. function projectObject( object, camera, groupOrder, sortObjects ) {
  17064. if ( object.visible === false ) return;
  17065. const visible = object.layers.test( camera.layers );
  17066. if ( visible ) {
  17067. if ( object.isGroup ) {
  17068. groupOrder = object.renderOrder;
  17069. } else if ( object.isLOD ) {
  17070. if ( object.autoUpdate === true ) object.update( camera );
  17071. } else if ( object.isLight ) {
  17072. currentRenderState.pushLight( object );
  17073. if ( object.castShadow ) {
  17074. currentRenderState.pushShadow( object );
  17075. }
  17076. } else if ( object.isSprite ) {
  17077. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17078. if ( sortObjects ) {
  17079. _vector3.setFromMatrixPosition( object.matrixWorld )
  17080. .applyMatrix4( _projScreenMatrix );
  17081. }
  17082. const geometry = objects.update( object );
  17083. const material = object.material;
  17084. if ( material.visible ) {
  17085. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17086. }
  17087. }
  17088. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17089. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17090. if ( object.isSkinnedMesh ) {
  17091. // update skeleton only once in a frame
  17092. if ( object.skeleton.frame !== info.render.frame ) {
  17093. object.skeleton.update();
  17094. object.skeleton.frame = info.render.frame;
  17095. }
  17096. }
  17097. const geometry = objects.update( object );
  17098. const material = object.material;
  17099. if ( sortObjects ) {
  17100. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17101. _vector3
  17102. .copy( geometry.boundingSphere.center )
  17103. .applyMatrix4( object.matrixWorld )
  17104. .applyMatrix4( _projScreenMatrix );
  17105. }
  17106. if ( Array.isArray( material ) ) {
  17107. const groups = geometry.groups;
  17108. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17109. const group = groups[ i ];
  17110. const groupMaterial = material[ group.materialIndex ];
  17111. if ( groupMaterial && groupMaterial.visible ) {
  17112. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17113. }
  17114. }
  17115. } else if ( material.visible ) {
  17116. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17117. }
  17118. }
  17119. }
  17120. }
  17121. const children = object.children;
  17122. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17123. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17124. }
  17125. }
  17126. function renderScene( currentRenderList, scene, camera, viewport ) {
  17127. const opaqueObjects = currentRenderList.opaque;
  17128. const transmissiveObjects = currentRenderList.transmissive;
  17129. const transparentObjects = currentRenderList.transparent;
  17130. currentRenderState.setupLightsView( camera );
  17131. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17132. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17133. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17134. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17135. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17136. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17137. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17138. state.buffers.depth.setTest( true );
  17139. state.buffers.depth.setMask( true );
  17140. state.buffers.color.setMask( true );
  17141. state.setPolygonOffset( false );
  17142. }
  17143. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17144. if ( _transmissionRenderTarget === null ) {
  17145. const isWebGL2 = capabilities.isWebGL2;
  17146. _transmissionRenderTarget = new WebGLRenderTarget( 1024, 1024, {
  17147. generateMipmaps: true,
  17148. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17149. minFilter: LinearMipmapLinearFilter,
  17150. samples: ( isWebGL2 && antialias === true ) ? 4 : 0
  17151. } );
  17152. // debug
  17153. /*
  17154. const geometry = new PlaneGeometry();
  17155. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17156. const mesh = new Mesh( geometry, material );
  17157. scene.add( mesh );
  17158. */
  17159. }
  17160. //
  17161. const currentRenderTarget = _this.getRenderTarget();
  17162. _this.setRenderTarget( _transmissionRenderTarget );
  17163. _this.clear();
  17164. // Turn off the features which can affect the frag color for opaque objects pass.
  17165. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17166. const currentToneMapping = _this.toneMapping;
  17167. _this.toneMapping = NoToneMapping;
  17168. renderObjects( opaqueObjects, scene, camera );
  17169. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17170. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17171. let renderTargetNeedsUpdate = false;
  17172. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17173. const renderItem = transmissiveObjects[ i ];
  17174. const object = renderItem.object;
  17175. const geometry = renderItem.geometry;
  17176. const material = renderItem.material;
  17177. const group = renderItem.group;
  17178. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17179. const currentSide = material.side;
  17180. material.side = BackSide;
  17181. material.needsUpdate = true;
  17182. renderObject( object, scene, camera, geometry, material, group );
  17183. material.side = currentSide;
  17184. material.needsUpdate = true;
  17185. renderTargetNeedsUpdate = true;
  17186. }
  17187. }
  17188. if ( renderTargetNeedsUpdate === true ) {
  17189. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17190. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17191. }
  17192. _this.setRenderTarget( currentRenderTarget );
  17193. _this.toneMapping = currentToneMapping;
  17194. }
  17195. function renderObjects( renderList, scene, camera ) {
  17196. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17197. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17198. const renderItem = renderList[ i ];
  17199. const object = renderItem.object;
  17200. const geometry = renderItem.geometry;
  17201. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17202. const group = renderItem.group;
  17203. if ( object.layers.test( camera.layers ) ) {
  17204. renderObject( object, scene, camera, geometry, material, group );
  17205. }
  17206. }
  17207. }
  17208. function renderObject( object, scene, camera, geometry, material, group ) {
  17209. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17210. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17211. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17212. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17213. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17214. material.side = BackSide;
  17215. material.needsUpdate = true;
  17216. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17217. material.side = FrontSide;
  17218. material.needsUpdate = true;
  17219. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17220. material.side = DoubleSide;
  17221. } else {
  17222. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17223. }
  17224. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17225. }
  17226. function getProgram( material, scene, object ) {
  17227. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17228. const materialProperties = properties.get( material );
  17229. const lights = currentRenderState.state.lights;
  17230. const shadowsArray = currentRenderState.state.shadowsArray;
  17231. const lightsStateVersion = lights.state.version;
  17232. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17233. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17234. let programs = materialProperties.programs;
  17235. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17236. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17237. materialProperties.fog = scene.fog;
  17238. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17239. if ( programs === undefined ) {
  17240. // new material
  17241. material.addEventListener( 'dispose', onMaterialDispose );
  17242. programs = new Map();
  17243. materialProperties.programs = programs;
  17244. }
  17245. let program = programs.get( programCacheKey );
  17246. if ( program !== undefined ) {
  17247. // early out if program and light state is identical
  17248. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17249. updateCommonMaterialProperties( material, parameters );
  17250. return program;
  17251. }
  17252. } else {
  17253. parameters.uniforms = programCache.getUniforms( material );
  17254. material.onBuild( object, parameters, _this );
  17255. material.onBeforeCompile( parameters, _this );
  17256. program = programCache.acquireProgram( parameters, programCacheKey );
  17257. programs.set( programCacheKey, program );
  17258. materialProperties.uniforms = parameters.uniforms;
  17259. }
  17260. const uniforms = materialProperties.uniforms;
  17261. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17262. uniforms.clippingPlanes = clipping.uniform;
  17263. }
  17264. updateCommonMaterialProperties( material, parameters );
  17265. // store the light setup it was created for
  17266. materialProperties.needsLights = materialNeedsLights( material );
  17267. materialProperties.lightsStateVersion = lightsStateVersion;
  17268. if ( materialProperties.needsLights ) {
  17269. // wire up the material to this renderer's lighting state
  17270. uniforms.ambientLightColor.value = lights.state.ambient;
  17271. uniforms.lightProbe.value = lights.state.probe;
  17272. uniforms.directionalLights.value = lights.state.directional;
  17273. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17274. uniforms.spotLights.value = lights.state.spot;
  17275. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17276. uniforms.rectAreaLights.value = lights.state.rectArea;
  17277. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17278. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17279. uniforms.pointLights.value = lights.state.point;
  17280. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17281. uniforms.hemisphereLights.value = lights.state.hemi;
  17282. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17283. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17284. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17285. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17286. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17287. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17288. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17289. // TODO (abelnation): add area lights shadow info to uniforms
  17290. }
  17291. const progUniforms = program.getUniforms();
  17292. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17293. materialProperties.currentProgram = program;
  17294. materialProperties.uniformsList = uniformsList;
  17295. return program;
  17296. }
  17297. function updateCommonMaterialProperties( material, parameters ) {
  17298. const materialProperties = properties.get( material );
  17299. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17300. materialProperties.instancing = parameters.instancing;
  17301. materialProperties.skinning = parameters.skinning;
  17302. materialProperties.morphTargets = parameters.morphTargets;
  17303. materialProperties.morphNormals = parameters.morphNormals;
  17304. materialProperties.morphColors = parameters.morphColors;
  17305. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17306. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17307. materialProperties.numIntersection = parameters.numClipIntersection;
  17308. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17309. materialProperties.vertexTangents = parameters.vertexTangents;
  17310. materialProperties.toneMapping = parameters.toneMapping;
  17311. }
  17312. function setProgram( camera, scene, geometry, material, object ) {
  17313. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17314. textures.resetTextureUnits();
  17315. const fog = scene.fog;
  17316. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17317. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17318. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17319. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17320. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  17321. const morphTargets = !! geometry.morphAttributes.position;
  17322. const morphNormals = !! geometry.morphAttributes.normal;
  17323. const morphColors = !! geometry.morphAttributes.color;
  17324. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17325. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17326. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17327. const materialProperties = properties.get( material );
  17328. const lights = currentRenderState.state.lights;
  17329. if ( _clippingEnabled === true ) {
  17330. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17331. const useCache =
  17332. camera === _currentCamera &&
  17333. material.id === _currentMaterialId;
  17334. // we might want to call this function with some ClippingGroup
  17335. // object instead of the material, once it becomes feasible
  17336. // (#8465, #8379)
  17337. clipping.setState( material, camera, useCache );
  17338. }
  17339. }
  17340. //
  17341. let needsProgramChange = false;
  17342. if ( material.version === materialProperties.__version ) {
  17343. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17344. needsProgramChange = true;
  17345. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17346. needsProgramChange = true;
  17347. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17348. needsProgramChange = true;
  17349. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17350. needsProgramChange = true;
  17351. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17352. needsProgramChange = true;
  17353. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17354. needsProgramChange = true;
  17355. } else if ( materialProperties.envMap !== envMap ) {
  17356. needsProgramChange = true;
  17357. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17358. needsProgramChange = true;
  17359. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17360. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17361. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17362. needsProgramChange = true;
  17363. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17364. needsProgramChange = true;
  17365. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17366. needsProgramChange = true;
  17367. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17368. needsProgramChange = true;
  17369. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17370. needsProgramChange = true;
  17371. } else if ( materialProperties.morphColors !== morphColors ) {
  17372. needsProgramChange = true;
  17373. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17374. needsProgramChange = true;
  17375. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17376. needsProgramChange = true;
  17377. }
  17378. } else {
  17379. needsProgramChange = true;
  17380. materialProperties.__version = material.version;
  17381. }
  17382. //
  17383. let program = materialProperties.currentProgram;
  17384. if ( needsProgramChange === true ) {
  17385. program = getProgram( material, scene, object );
  17386. }
  17387. let refreshProgram = false;
  17388. let refreshMaterial = false;
  17389. let refreshLights = false;
  17390. const p_uniforms = program.getUniforms(),
  17391. m_uniforms = materialProperties.uniforms;
  17392. if ( state.useProgram( program.program ) ) {
  17393. refreshProgram = true;
  17394. refreshMaterial = true;
  17395. refreshLights = true;
  17396. }
  17397. if ( material.id !== _currentMaterialId ) {
  17398. _currentMaterialId = material.id;
  17399. refreshMaterial = true;
  17400. }
  17401. if ( refreshProgram || _currentCamera !== camera ) {
  17402. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17403. if ( capabilities.logarithmicDepthBuffer ) {
  17404. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17405. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17406. }
  17407. if ( _currentCamera !== camera ) {
  17408. _currentCamera = camera;
  17409. // lighting uniforms depend on the camera so enforce an update
  17410. // now, in case this material supports lights - or later, when
  17411. // the next material that does gets activated:
  17412. refreshMaterial = true; // set to true on material change
  17413. refreshLights = true; // remains set until update done
  17414. }
  17415. // load material specific uniforms
  17416. // (shader material also gets them for the sake of genericity)
  17417. if ( material.isShaderMaterial ||
  17418. material.isMeshPhongMaterial ||
  17419. material.isMeshToonMaterial ||
  17420. material.isMeshStandardMaterial ||
  17421. material.envMap ) {
  17422. const uCamPos = p_uniforms.map.cameraPosition;
  17423. if ( uCamPos !== undefined ) {
  17424. uCamPos.setValue( _gl,
  17425. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17426. }
  17427. }
  17428. if ( material.isMeshPhongMaterial ||
  17429. material.isMeshToonMaterial ||
  17430. material.isMeshLambertMaterial ||
  17431. material.isMeshBasicMaterial ||
  17432. material.isMeshStandardMaterial ||
  17433. material.isShaderMaterial ) {
  17434. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17435. }
  17436. if ( material.isMeshPhongMaterial ||
  17437. material.isMeshToonMaterial ||
  17438. material.isMeshLambertMaterial ||
  17439. material.isMeshBasicMaterial ||
  17440. material.isMeshStandardMaterial ||
  17441. material.isShaderMaterial ||
  17442. material.isShadowMaterial ||
  17443. object.isSkinnedMesh ) {
  17444. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17445. }
  17446. }
  17447. // skinning and morph target uniforms must be set even if material didn't change
  17448. // auto-setting of texture unit for bone and morph texture must go before other textures
  17449. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17450. if ( object.isSkinnedMesh ) {
  17451. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17452. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17453. const skeleton = object.skeleton;
  17454. if ( skeleton ) {
  17455. if ( capabilities.floatVertexTextures ) {
  17456. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17457. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17458. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17459. } else {
  17460. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17461. }
  17462. }
  17463. }
  17464. const morphAttributes = geometry.morphAttributes;
  17465. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17466. morphtargets.update( object, geometry, program );
  17467. }
  17468. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17469. materialProperties.receiveShadow = object.receiveShadow;
  17470. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17471. }
  17472. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17473. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17474. m_uniforms.envMap.value = envMap;
  17475. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17476. }
  17477. if ( refreshMaterial ) {
  17478. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17479. if ( materialProperties.needsLights ) {
  17480. // the current material requires lighting info
  17481. // note: all lighting uniforms are always set correctly
  17482. // they simply reference the renderer's state for their
  17483. // values
  17484. //
  17485. // use the current material's .needsUpdate flags to set
  17486. // the GL state when required
  17487. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17488. }
  17489. // refresh uniforms common to several materials
  17490. if ( fog && material.fog === true ) {
  17491. materials.refreshFogUniforms( m_uniforms, fog );
  17492. }
  17493. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17494. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17495. }
  17496. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17497. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17498. material.uniformsNeedUpdate = false;
  17499. }
  17500. if ( material.isSpriteMaterial ) {
  17501. p_uniforms.setValue( _gl, 'center', object.center );
  17502. }
  17503. // common matrices
  17504. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17505. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17506. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17507. // UBOs
  17508. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17509. const groups = material.uniformsGroups;
  17510. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17511. if ( capabilities.isWebGL2 ) {
  17512. const group = groups[ i ];
  17513. uniformsGroups.update( group, program );
  17514. uniformsGroups.bind( group, program );
  17515. } else {
  17516. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17517. }
  17518. }
  17519. }
  17520. return program;
  17521. }
  17522. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17523. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17524. uniforms.ambientLightColor.needsUpdate = value;
  17525. uniforms.lightProbe.needsUpdate = value;
  17526. uniforms.directionalLights.needsUpdate = value;
  17527. uniforms.directionalLightShadows.needsUpdate = value;
  17528. uniforms.pointLights.needsUpdate = value;
  17529. uniforms.pointLightShadows.needsUpdate = value;
  17530. uniforms.spotLights.needsUpdate = value;
  17531. uniforms.spotLightShadows.needsUpdate = value;
  17532. uniforms.rectAreaLights.needsUpdate = value;
  17533. uniforms.hemisphereLights.needsUpdate = value;
  17534. }
  17535. function materialNeedsLights( material ) {
  17536. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17537. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17538. ( material.isShaderMaterial && material.lights === true );
  17539. }
  17540. this.getActiveCubeFace = function () {
  17541. return _currentActiveCubeFace;
  17542. };
  17543. this.getActiveMipmapLevel = function () {
  17544. return _currentActiveMipmapLevel;
  17545. };
  17546. this.getRenderTarget = function () {
  17547. return _currentRenderTarget;
  17548. };
  17549. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17550. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17551. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17552. const renderTargetProperties = properties.get( renderTarget );
  17553. renderTargetProperties.__hasExternalTextures = true;
  17554. if ( renderTargetProperties.__hasExternalTextures ) {
  17555. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17556. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17557. // The multisample_render_to_texture extension doesn't work properly if there
  17558. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17559. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17560. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17561. renderTargetProperties.__useRenderToTexture = false;
  17562. }
  17563. }
  17564. }
  17565. };
  17566. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17567. const renderTargetProperties = properties.get( renderTarget );
  17568. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17569. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17570. };
  17571. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17572. _currentRenderTarget = renderTarget;
  17573. _currentActiveCubeFace = activeCubeFace;
  17574. _currentActiveMipmapLevel = activeMipmapLevel;
  17575. let useDefaultFramebuffer = true;
  17576. let framebuffer = null;
  17577. let isCube = false;
  17578. let isRenderTarget3D = false;
  17579. if ( renderTarget ) {
  17580. const renderTargetProperties = properties.get( renderTarget );
  17581. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17582. // We need to make sure to rebind the framebuffer.
  17583. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17584. useDefaultFramebuffer = false;
  17585. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17586. textures.setupRenderTarget( renderTarget );
  17587. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17588. // Color and depth texture must be rebound in order for the swapchain to update.
  17589. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17590. }
  17591. const texture = renderTarget.texture;
  17592. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17593. isRenderTarget3D = true;
  17594. }
  17595. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17596. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17597. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17598. isCube = true;
  17599. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17600. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17601. } else {
  17602. framebuffer = __webglFramebuffer;
  17603. }
  17604. _currentViewport.copy( renderTarget.viewport );
  17605. _currentScissor.copy( renderTarget.scissor );
  17606. _currentScissorTest = renderTarget.scissorTest;
  17607. } else {
  17608. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17609. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17610. _currentScissorTest = _scissorTest;
  17611. }
  17612. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17613. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17614. state.drawBuffers( renderTarget, framebuffer );
  17615. }
  17616. state.viewport( _currentViewport );
  17617. state.scissor( _currentScissor );
  17618. state.setScissorTest( _currentScissorTest );
  17619. if ( isCube ) {
  17620. const textureProperties = properties.get( renderTarget.texture );
  17621. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17622. } else if ( isRenderTarget3D ) {
  17623. const textureProperties = properties.get( renderTarget.texture );
  17624. const layer = activeCubeFace || 0;
  17625. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17626. }
  17627. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17628. };
  17629. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17630. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17631. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17632. return;
  17633. }
  17634. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17635. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17636. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17637. }
  17638. if ( framebuffer ) {
  17639. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17640. try {
  17641. const texture = renderTarget.texture;
  17642. const textureFormat = texture.format;
  17643. const textureType = texture.type;
  17644. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17645. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17646. return;
  17647. }
  17648. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17649. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17650. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17651. ! halfFloatSupportedByExt ) {
  17652. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17653. return;
  17654. }
  17655. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17656. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17657. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17658. }
  17659. } finally {
  17660. // restore framebuffer of current render target if necessary
  17661. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17662. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17663. }
  17664. }
  17665. };
  17666. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17667. const levelScale = Math.pow( 2, - level );
  17668. const width = Math.floor( texture.image.width * levelScale );
  17669. const height = Math.floor( texture.image.height * levelScale );
  17670. textures.setTexture2D( texture, 0 );
  17671. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  17672. state.unbindTexture();
  17673. };
  17674. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17675. const width = srcTexture.image.width;
  17676. const height = srcTexture.image.height;
  17677. const glFormat = utils.convert( dstTexture.format );
  17678. const glType = utils.convert( dstTexture.type );
  17679. textures.setTexture2D( dstTexture, 0 );
  17680. // As another texture upload may have changed pixelStorei
  17681. // parameters, make sure they are correct for the dstTexture
  17682. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17683. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17684. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17685. if ( srcTexture.isDataTexture ) {
  17686. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17687. } else {
  17688. if ( srcTexture.isCompressedTexture ) {
  17689. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17690. } else {
  17691. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17692. }
  17693. }
  17694. // Generate mipmaps only when copying level 0
  17695. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  17696. state.unbindTexture();
  17697. };
  17698. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17699. if ( _this.isWebGL1Renderer ) {
  17700. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17701. return;
  17702. }
  17703. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17704. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17705. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17706. const glFormat = utils.convert( dstTexture.format );
  17707. const glType = utils.convert( dstTexture.type );
  17708. let glTarget;
  17709. if ( dstTexture.isData3DTexture ) {
  17710. textures.setTexture3D( dstTexture, 0 );
  17711. glTarget = _gl.TEXTURE_3D;
  17712. } else if ( dstTexture.isDataArrayTexture ) {
  17713. textures.setTexture2DArray( dstTexture, 0 );
  17714. glTarget = _gl.TEXTURE_2D_ARRAY;
  17715. } else {
  17716. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17717. return;
  17718. }
  17719. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17720. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17721. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17722. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  17723. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  17724. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  17725. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  17726. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  17727. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17728. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  17729. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  17730. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  17731. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  17732. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  17733. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17734. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17735. } else {
  17736. if ( srcTexture.isCompressedArrayTexture ) {
  17737. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17738. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17739. } else {
  17740. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17741. }
  17742. }
  17743. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  17744. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  17745. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  17746. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  17747. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  17748. // Generate mipmaps only when copying level 0
  17749. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17750. state.unbindTexture();
  17751. };
  17752. this.initTexture = function ( texture ) {
  17753. if ( texture.isCubeTexture ) {
  17754. textures.setTextureCube( texture, 0 );
  17755. } else if ( texture.isData3DTexture ) {
  17756. textures.setTexture3D( texture, 0 );
  17757. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17758. textures.setTexture2DArray( texture, 0 );
  17759. } else {
  17760. textures.setTexture2D( texture, 0 );
  17761. }
  17762. state.unbindTexture();
  17763. };
  17764. this.resetState = function () {
  17765. _currentActiveCubeFace = 0;
  17766. _currentActiveMipmapLevel = 0;
  17767. _currentRenderTarget = null;
  17768. state.reset();
  17769. bindingStates.reset();
  17770. };
  17771. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17772. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17773. }
  17774. }
  17775. get physicallyCorrectLights() { // @deprecated, r150
  17776. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17777. return ! this.useLegacyLights;
  17778. }
  17779. set physicallyCorrectLights( value ) { // @deprecated, r150
  17780. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17781. this.useLegacyLights = ! value;
  17782. }
  17783. get outputEncoding() { // @deprecated, r152
  17784. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  17785. return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  17786. }
  17787. set outputEncoding( encoding ) { // @deprecated, r152
  17788. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  17789. this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  17790. }
  17791. }
  17792. class WebGL1Renderer extends WebGLRenderer {}
  17793. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17794. class FogExp2 {
  17795. constructor( color, density = 0.00025 ) {
  17796. this.isFogExp2 = true;
  17797. this.name = '';
  17798. this.color = new Color( color );
  17799. this.density = density;
  17800. }
  17801. clone() {
  17802. return new FogExp2( this.color, this.density );
  17803. }
  17804. toJSON( /* meta */ ) {
  17805. return {
  17806. type: 'FogExp2',
  17807. color: this.color.getHex(),
  17808. density: this.density
  17809. };
  17810. }
  17811. }
  17812. class Fog {
  17813. constructor( color, near = 1, far = 1000 ) {
  17814. this.isFog = true;
  17815. this.name = '';
  17816. this.color = new Color( color );
  17817. this.near = near;
  17818. this.far = far;
  17819. }
  17820. clone() {
  17821. return new Fog( this.color, this.near, this.far );
  17822. }
  17823. toJSON( /* meta */ ) {
  17824. return {
  17825. type: 'Fog',
  17826. color: this.color.getHex(),
  17827. near: this.near,
  17828. far: this.far
  17829. };
  17830. }
  17831. }
  17832. class Scene extends Object3D {
  17833. constructor() {
  17834. super();
  17835. this.isScene = true;
  17836. this.type = 'Scene';
  17837. this.background = null;
  17838. this.environment = null;
  17839. this.fog = null;
  17840. this.backgroundBlurriness = 0;
  17841. this.backgroundIntensity = 1;
  17842. this.overrideMaterial = null;
  17843. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17844. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17845. }
  17846. }
  17847. copy( source, recursive ) {
  17848. super.copy( source, recursive );
  17849. if ( source.background !== null ) this.background = source.background.clone();
  17850. if ( source.environment !== null ) this.environment = source.environment.clone();
  17851. if ( source.fog !== null ) this.fog = source.fog.clone();
  17852. this.backgroundBlurriness = source.backgroundBlurriness;
  17853. this.backgroundIntensity = source.backgroundIntensity;
  17854. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17855. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17856. return this;
  17857. }
  17858. toJSON( meta ) {
  17859. const data = super.toJSON( meta );
  17860. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17861. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17862. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17863. return data;
  17864. }
  17865. get autoUpdate() { // @deprecated, r144
  17866. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17867. return this.matrixWorldAutoUpdate;
  17868. }
  17869. set autoUpdate( value ) { // @deprecated, r144
  17870. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17871. this.matrixWorldAutoUpdate = value;
  17872. }
  17873. }
  17874. class InterleavedBuffer {
  17875. constructor( array, stride ) {
  17876. this.isInterleavedBuffer = true;
  17877. this.array = array;
  17878. this.stride = stride;
  17879. this.count = array !== undefined ? array.length / stride : 0;
  17880. this.usage = StaticDrawUsage;
  17881. this.updateRange = { offset: 0, count: - 1 };
  17882. this.version = 0;
  17883. this.uuid = generateUUID();
  17884. }
  17885. onUploadCallback() {}
  17886. set needsUpdate( value ) {
  17887. if ( value === true ) this.version ++;
  17888. }
  17889. setUsage( value ) {
  17890. this.usage = value;
  17891. return this;
  17892. }
  17893. copy( source ) {
  17894. this.array = new source.array.constructor( source.array );
  17895. this.count = source.count;
  17896. this.stride = source.stride;
  17897. this.usage = source.usage;
  17898. return this;
  17899. }
  17900. copyAt( index1, attribute, index2 ) {
  17901. index1 *= this.stride;
  17902. index2 *= attribute.stride;
  17903. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17904. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17905. }
  17906. return this;
  17907. }
  17908. set( value, offset = 0 ) {
  17909. this.array.set( value, offset );
  17910. return this;
  17911. }
  17912. clone( data ) {
  17913. if ( data.arrayBuffers === undefined ) {
  17914. data.arrayBuffers = {};
  17915. }
  17916. if ( this.array.buffer._uuid === undefined ) {
  17917. this.array.buffer._uuid = generateUUID();
  17918. }
  17919. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17920. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17921. }
  17922. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17923. const ib = new this.constructor( array, this.stride );
  17924. ib.setUsage( this.usage );
  17925. return ib;
  17926. }
  17927. onUpload( callback ) {
  17928. this.onUploadCallback = callback;
  17929. return this;
  17930. }
  17931. toJSON( data ) {
  17932. if ( data.arrayBuffers === undefined ) {
  17933. data.arrayBuffers = {};
  17934. }
  17935. // generate UUID for array buffer if necessary
  17936. if ( this.array.buffer._uuid === undefined ) {
  17937. this.array.buffer._uuid = generateUUID();
  17938. }
  17939. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17940. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17941. }
  17942. //
  17943. return {
  17944. uuid: this.uuid,
  17945. buffer: this.array.buffer._uuid,
  17946. type: this.array.constructor.name,
  17947. stride: this.stride
  17948. };
  17949. }
  17950. }
  17951. const _vector$5 = /*@__PURE__*/ new Vector3();
  17952. class InterleavedBufferAttribute {
  17953. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17954. this.isInterleavedBufferAttribute = true;
  17955. this.name = '';
  17956. this.data = interleavedBuffer;
  17957. this.itemSize = itemSize;
  17958. this.offset = offset;
  17959. this.normalized = normalized;
  17960. }
  17961. get count() {
  17962. return this.data.count;
  17963. }
  17964. get array() {
  17965. return this.data.array;
  17966. }
  17967. set needsUpdate( value ) {
  17968. this.data.needsUpdate = value;
  17969. }
  17970. applyMatrix4( m ) {
  17971. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17972. _vector$5.fromBufferAttribute( this, i );
  17973. _vector$5.applyMatrix4( m );
  17974. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17975. }
  17976. return this;
  17977. }
  17978. applyNormalMatrix( m ) {
  17979. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17980. _vector$5.fromBufferAttribute( this, i );
  17981. _vector$5.applyNormalMatrix( m );
  17982. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17983. }
  17984. return this;
  17985. }
  17986. transformDirection( m ) {
  17987. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17988. _vector$5.fromBufferAttribute( this, i );
  17989. _vector$5.transformDirection( m );
  17990. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17991. }
  17992. return this;
  17993. }
  17994. setX( index, x ) {
  17995. if ( this.normalized ) x = normalize( x, this.array );
  17996. this.data.array[ index * this.data.stride + this.offset ] = x;
  17997. return this;
  17998. }
  17999. setY( index, y ) {
  18000. if ( this.normalized ) y = normalize( y, this.array );
  18001. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18002. return this;
  18003. }
  18004. setZ( index, z ) {
  18005. if ( this.normalized ) z = normalize( z, this.array );
  18006. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18007. return this;
  18008. }
  18009. setW( index, w ) {
  18010. if ( this.normalized ) w = normalize( w, this.array );
  18011. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18012. return this;
  18013. }
  18014. getX( index ) {
  18015. let x = this.data.array[ index * this.data.stride + this.offset ];
  18016. if ( this.normalized ) x = denormalize( x, this.array );
  18017. return x;
  18018. }
  18019. getY( index ) {
  18020. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18021. if ( this.normalized ) y = denormalize( y, this.array );
  18022. return y;
  18023. }
  18024. getZ( index ) {
  18025. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18026. if ( this.normalized ) z = denormalize( z, this.array );
  18027. return z;
  18028. }
  18029. getW( index ) {
  18030. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18031. if ( this.normalized ) w = denormalize( w, this.array );
  18032. return w;
  18033. }
  18034. setXY( index, x, y ) {
  18035. index = index * this.data.stride + this.offset;
  18036. if ( this.normalized ) {
  18037. x = normalize( x, this.array );
  18038. y = normalize( y, this.array );
  18039. }
  18040. this.data.array[ index + 0 ] = x;
  18041. this.data.array[ index + 1 ] = y;
  18042. return this;
  18043. }
  18044. setXYZ( index, x, y, z ) {
  18045. index = index * this.data.stride + this.offset;
  18046. if ( this.normalized ) {
  18047. x = normalize( x, this.array );
  18048. y = normalize( y, this.array );
  18049. z = normalize( z, this.array );
  18050. }
  18051. this.data.array[ index + 0 ] = x;
  18052. this.data.array[ index + 1 ] = y;
  18053. this.data.array[ index + 2 ] = z;
  18054. return this;
  18055. }
  18056. setXYZW( index, x, y, z, w ) {
  18057. index = index * this.data.stride + this.offset;
  18058. if ( this.normalized ) {
  18059. x = normalize( x, this.array );
  18060. y = normalize( y, this.array );
  18061. z = normalize( z, this.array );
  18062. w = normalize( w, this.array );
  18063. }
  18064. this.data.array[ index + 0 ] = x;
  18065. this.data.array[ index + 1 ] = y;
  18066. this.data.array[ index + 2 ] = z;
  18067. this.data.array[ index + 3 ] = w;
  18068. return this;
  18069. }
  18070. clone( data ) {
  18071. if ( data === undefined ) {
  18072. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18073. const array = [];
  18074. for ( let i = 0; i < this.count; i ++ ) {
  18075. const index = i * this.data.stride + this.offset;
  18076. for ( let j = 0; j < this.itemSize; j ++ ) {
  18077. array.push( this.data.array[ index + j ] );
  18078. }
  18079. }
  18080. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18081. } else {
  18082. if ( data.interleavedBuffers === undefined ) {
  18083. data.interleavedBuffers = {};
  18084. }
  18085. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18086. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18087. }
  18088. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18089. }
  18090. }
  18091. toJSON( data ) {
  18092. if ( data === undefined ) {
  18093. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18094. const array = [];
  18095. for ( let i = 0; i < this.count; i ++ ) {
  18096. const index = i * this.data.stride + this.offset;
  18097. for ( let j = 0; j < this.itemSize; j ++ ) {
  18098. array.push( this.data.array[ index + j ] );
  18099. }
  18100. }
  18101. // de-interleave data and save it as an ordinary buffer attribute for now
  18102. return {
  18103. itemSize: this.itemSize,
  18104. type: this.array.constructor.name,
  18105. array: array,
  18106. normalized: this.normalized
  18107. };
  18108. } else {
  18109. // save as true interleaved attribute
  18110. if ( data.interleavedBuffers === undefined ) {
  18111. data.interleavedBuffers = {};
  18112. }
  18113. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18114. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18115. }
  18116. return {
  18117. isInterleavedBufferAttribute: true,
  18118. itemSize: this.itemSize,
  18119. data: this.data.uuid,
  18120. offset: this.offset,
  18121. normalized: this.normalized
  18122. };
  18123. }
  18124. }
  18125. }
  18126. class SpriteMaterial extends Material {
  18127. constructor( parameters ) {
  18128. super();
  18129. this.isSpriteMaterial = true;
  18130. this.type = 'SpriteMaterial';
  18131. this.color = new Color( 0xffffff );
  18132. this.map = null;
  18133. this.alphaMap = null;
  18134. this.rotation = 0;
  18135. this.sizeAttenuation = true;
  18136. this.transparent = true;
  18137. this.fog = true;
  18138. this.setValues( parameters );
  18139. }
  18140. copy( source ) {
  18141. super.copy( source );
  18142. this.color.copy( source.color );
  18143. this.map = source.map;
  18144. this.alphaMap = source.alphaMap;
  18145. this.rotation = source.rotation;
  18146. this.sizeAttenuation = source.sizeAttenuation;
  18147. this.fog = source.fog;
  18148. return this;
  18149. }
  18150. }
  18151. let _geometry;
  18152. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18153. const _worldScale = /*@__PURE__*/ new Vector3();
  18154. const _mvPosition = /*@__PURE__*/ new Vector3();
  18155. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18156. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18157. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18158. const _vA = /*@__PURE__*/ new Vector3();
  18159. const _vB = /*@__PURE__*/ new Vector3();
  18160. const _vC = /*@__PURE__*/ new Vector3();
  18161. const _uvA = /*@__PURE__*/ new Vector2();
  18162. const _uvB = /*@__PURE__*/ new Vector2();
  18163. const _uvC = /*@__PURE__*/ new Vector2();
  18164. class Sprite extends Object3D {
  18165. constructor( material ) {
  18166. super();
  18167. this.isSprite = true;
  18168. this.type = 'Sprite';
  18169. if ( _geometry === undefined ) {
  18170. _geometry = new BufferGeometry();
  18171. const float32Array = new Float32Array( [
  18172. - 0.5, - 0.5, 0, 0, 0,
  18173. 0.5, - 0.5, 0, 1, 0,
  18174. 0.5, 0.5, 0, 1, 1,
  18175. - 0.5, 0.5, 0, 0, 1
  18176. ] );
  18177. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18178. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18179. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18180. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18181. }
  18182. this.geometry = _geometry;
  18183. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18184. this.center = new Vector2( 0.5, 0.5 );
  18185. }
  18186. raycast( raycaster, intersects ) {
  18187. if ( raycaster.camera === null ) {
  18188. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18189. }
  18190. _worldScale.setFromMatrixScale( this.matrixWorld );
  18191. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18192. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18193. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18194. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18195. _worldScale.multiplyScalar( - _mvPosition.z );
  18196. }
  18197. const rotation = this.material.rotation;
  18198. let sin, cos;
  18199. if ( rotation !== 0 ) {
  18200. cos = Math.cos( rotation );
  18201. sin = Math.sin( rotation );
  18202. }
  18203. const center = this.center;
  18204. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18205. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18206. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18207. _uvA.set( 0, 0 );
  18208. _uvB.set( 1, 0 );
  18209. _uvC.set( 1, 1 );
  18210. // check first triangle
  18211. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18212. if ( intersect === null ) {
  18213. // check second triangle
  18214. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18215. _uvB.set( 0, 1 );
  18216. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18217. if ( intersect === null ) {
  18218. return;
  18219. }
  18220. }
  18221. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18222. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18223. intersects.push( {
  18224. distance: distance,
  18225. point: _intersectPoint.clone(),
  18226. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18227. face: null,
  18228. object: this
  18229. } );
  18230. }
  18231. copy( source, recursive ) {
  18232. super.copy( source, recursive );
  18233. if ( source.center !== undefined ) this.center.copy( source.center );
  18234. this.material = source.material;
  18235. return this;
  18236. }
  18237. }
  18238. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18239. // compute position in camera space
  18240. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18241. // to check if rotation is not zero
  18242. if ( sin !== undefined ) {
  18243. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18244. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18245. } else {
  18246. _rotatedPosition.copy( _alignedPosition );
  18247. }
  18248. vertexPosition.copy( mvPosition );
  18249. vertexPosition.x += _rotatedPosition.x;
  18250. vertexPosition.y += _rotatedPosition.y;
  18251. // transform to world space
  18252. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18253. }
  18254. const _v1$2 = /*@__PURE__*/ new Vector3();
  18255. const _v2$1 = /*@__PURE__*/ new Vector3();
  18256. class LOD extends Object3D {
  18257. constructor() {
  18258. super();
  18259. this._currentLevel = 0;
  18260. this.type = 'LOD';
  18261. Object.defineProperties( this, {
  18262. levels: {
  18263. enumerable: true,
  18264. value: []
  18265. },
  18266. isLOD: {
  18267. value: true,
  18268. }
  18269. } );
  18270. this.autoUpdate = true;
  18271. }
  18272. copy( source ) {
  18273. super.copy( source, false );
  18274. const levels = source.levels;
  18275. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18276. const level = levels[ i ];
  18277. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18278. }
  18279. this.autoUpdate = source.autoUpdate;
  18280. return this;
  18281. }
  18282. addLevel( object, distance = 0, hysteresis = 0 ) {
  18283. distance = Math.abs( distance );
  18284. const levels = this.levels;
  18285. let l;
  18286. for ( l = 0; l < levels.length; l ++ ) {
  18287. if ( distance < levels[ l ].distance ) {
  18288. break;
  18289. }
  18290. }
  18291. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18292. this.add( object );
  18293. return this;
  18294. }
  18295. getCurrentLevel() {
  18296. return this._currentLevel;
  18297. }
  18298. getObjectForDistance( distance ) {
  18299. const levels = this.levels;
  18300. if ( levels.length > 0 ) {
  18301. let i, l;
  18302. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18303. let levelDistance = levels[ i ].distance;
  18304. if ( levels[ i ].object.visible ) {
  18305. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18306. }
  18307. if ( distance < levelDistance ) {
  18308. break;
  18309. }
  18310. }
  18311. return levels[ i - 1 ].object;
  18312. }
  18313. return null;
  18314. }
  18315. raycast( raycaster, intersects ) {
  18316. const levels = this.levels;
  18317. if ( levels.length > 0 ) {
  18318. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18319. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18320. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18321. }
  18322. }
  18323. update( camera ) {
  18324. const levels = this.levels;
  18325. if ( levels.length > 1 ) {
  18326. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18327. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18328. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18329. levels[ 0 ].object.visible = true;
  18330. let i, l;
  18331. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18332. let levelDistance = levels[ i ].distance;
  18333. if ( levels[ i ].object.visible ) {
  18334. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18335. }
  18336. if ( distance >= levelDistance ) {
  18337. levels[ i - 1 ].object.visible = false;
  18338. levels[ i ].object.visible = true;
  18339. } else {
  18340. break;
  18341. }
  18342. }
  18343. this._currentLevel = i - 1;
  18344. for ( ; i < l; i ++ ) {
  18345. levels[ i ].object.visible = false;
  18346. }
  18347. }
  18348. }
  18349. toJSON( meta ) {
  18350. const data = super.toJSON( meta );
  18351. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18352. data.object.levels = [];
  18353. const levels = this.levels;
  18354. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18355. const level = levels[ i ];
  18356. data.object.levels.push( {
  18357. object: level.object.uuid,
  18358. distance: level.distance,
  18359. hysteresis: level.hysteresis
  18360. } );
  18361. }
  18362. return data;
  18363. }
  18364. }
  18365. const _basePosition = /*@__PURE__*/ new Vector3();
  18366. const _skinIndex = /*@__PURE__*/ new Vector4();
  18367. const _skinWeight = /*@__PURE__*/ new Vector4();
  18368. const _vector3 = /*@__PURE__*/ new Vector3();
  18369. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18370. const _vertex = /*@__PURE__*/ new Vector3();
  18371. class SkinnedMesh extends Mesh {
  18372. constructor( geometry, material ) {
  18373. super( geometry, material );
  18374. this.isSkinnedMesh = true;
  18375. this.type = 'SkinnedMesh';
  18376. this.bindMode = 'attached';
  18377. this.bindMatrix = new Matrix4();
  18378. this.bindMatrixInverse = new Matrix4();
  18379. this.boundingBox = null;
  18380. this.boundingSphere = null;
  18381. }
  18382. computeBoundingBox() {
  18383. const geometry = this.geometry;
  18384. if ( this.boundingBox === null ) {
  18385. this.boundingBox = new Box3();
  18386. }
  18387. this.boundingBox.makeEmpty();
  18388. const positionAttribute = geometry.getAttribute( 'position' );
  18389. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18390. _vertex.fromBufferAttribute( positionAttribute, i );
  18391. this.applyBoneTransform( i, _vertex );
  18392. this.boundingBox.expandByPoint( _vertex );
  18393. }
  18394. }
  18395. computeBoundingSphere() {
  18396. const geometry = this.geometry;
  18397. if ( this.boundingSphere === null ) {
  18398. this.boundingSphere = new Sphere();
  18399. }
  18400. this.boundingSphere.makeEmpty();
  18401. const positionAttribute = geometry.getAttribute( 'position' );
  18402. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18403. _vertex.fromBufferAttribute( positionAttribute, i );
  18404. this.applyBoneTransform( i, _vertex );
  18405. this.boundingSphere.expandByPoint( _vertex );
  18406. }
  18407. }
  18408. copy( source, recursive ) {
  18409. super.copy( source, recursive );
  18410. this.bindMode = source.bindMode;
  18411. this.bindMatrix.copy( source.bindMatrix );
  18412. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18413. this.skeleton = source.skeleton;
  18414. return this;
  18415. }
  18416. // raycast( raycaster, intersects ) {
  18417. // if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18418. // _sphere.copy( this.boundingSphere );
  18419. // _sphere.applyMatrix4( this.matrixWorld );
  18420. // if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18421. // this._computeIntersections( raycaster, intersects );
  18422. // }
  18423. getVertexPosition( index, target ) {
  18424. super.getVertexPosition( index, target );
  18425. this.applyBoneTransform( index, target );
  18426. return target;
  18427. }
  18428. bind( skeleton, bindMatrix ) {
  18429. this.skeleton = skeleton;
  18430. if ( bindMatrix === undefined ) {
  18431. this.updateMatrixWorld( true );
  18432. this.skeleton.calculateInverses();
  18433. bindMatrix = this.matrixWorld;
  18434. }
  18435. this.bindMatrix.copy( bindMatrix );
  18436. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18437. }
  18438. pose() {
  18439. this.skeleton.pose();
  18440. }
  18441. normalizeSkinWeights() {
  18442. const vector = new Vector4();
  18443. const skinWeight = this.geometry.attributes.skinWeight;
  18444. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18445. vector.fromBufferAttribute( skinWeight, i );
  18446. const scale = 1.0 / vector.manhattanLength();
  18447. if ( scale !== Infinity ) {
  18448. vector.multiplyScalar( scale );
  18449. } else {
  18450. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18451. }
  18452. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18453. }
  18454. }
  18455. updateMatrixWorld( force ) {
  18456. super.updateMatrixWorld( force );
  18457. if ( this.bindMode === 'attached' ) {
  18458. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18459. } else if ( this.bindMode === 'detached' ) {
  18460. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18461. } else {
  18462. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18463. }
  18464. }
  18465. applyBoneTransform( index, vector ) {
  18466. const skeleton = this.skeleton;
  18467. const geometry = this.geometry;
  18468. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18469. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18470. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18471. vector.set( 0, 0, 0 );
  18472. for ( let i = 0; i < 4; i ++ ) {
  18473. const weight = _skinWeight.getComponent( i );
  18474. if ( weight !== 0 ) {
  18475. const boneIndex = _skinIndex.getComponent( i );
  18476. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18477. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18478. }
  18479. }
  18480. return vector.applyMatrix4( this.bindMatrixInverse );
  18481. }
  18482. boneTransform( index, vector ) { // @deprecated, r151
  18483. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  18484. return this.applyBoneTransform( index, vector );
  18485. }
  18486. }
  18487. class Bone extends Object3D {
  18488. constructor() {
  18489. super();
  18490. this.isBone = true;
  18491. this.type = 'Bone';
  18492. }
  18493. }
  18494. class DataTexture extends Texture {
  18495. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18496. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18497. this.isDataTexture = true;
  18498. this.image = { data: data, width: width, height: height };
  18499. this.generateMipmaps = false;
  18500. this.flipY = false;
  18501. this.unpackAlignment = 1;
  18502. }
  18503. }
  18504. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18505. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18506. class Skeleton {
  18507. constructor( bones = [], boneInverses = [] ) {
  18508. this.uuid = generateUUID();
  18509. this.bones = bones.slice( 0 );
  18510. this.boneInverses = boneInverses;
  18511. this.boneMatrices = null;
  18512. this.boneTexture = null;
  18513. this.boneTextureSize = 0;
  18514. this.frame = - 1;
  18515. this.init();
  18516. }
  18517. init() {
  18518. const bones = this.bones;
  18519. const boneInverses = this.boneInverses;
  18520. this.boneMatrices = new Float32Array( bones.length * 16 );
  18521. // calculate inverse bone matrices if necessary
  18522. if ( boneInverses.length === 0 ) {
  18523. this.calculateInverses();
  18524. } else {
  18525. // handle special case
  18526. if ( bones.length !== boneInverses.length ) {
  18527. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18528. this.boneInverses = [];
  18529. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18530. this.boneInverses.push( new Matrix4() );
  18531. }
  18532. }
  18533. }
  18534. }
  18535. calculateInverses() {
  18536. this.boneInverses.length = 0;
  18537. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18538. const inverse = new Matrix4();
  18539. if ( this.bones[ i ] ) {
  18540. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18541. }
  18542. this.boneInverses.push( inverse );
  18543. }
  18544. }
  18545. pose() {
  18546. // recover the bind-time world matrices
  18547. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18548. const bone = this.bones[ i ];
  18549. if ( bone ) {
  18550. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18551. }
  18552. }
  18553. // compute the local matrices, positions, rotations and scales
  18554. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18555. const bone = this.bones[ i ];
  18556. if ( bone ) {
  18557. if ( bone.parent && bone.parent.isBone ) {
  18558. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18559. bone.matrix.multiply( bone.matrixWorld );
  18560. } else {
  18561. bone.matrix.copy( bone.matrixWorld );
  18562. }
  18563. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18564. }
  18565. }
  18566. }
  18567. update() {
  18568. const bones = this.bones;
  18569. const boneInverses = this.boneInverses;
  18570. const boneMatrices = this.boneMatrices;
  18571. const boneTexture = this.boneTexture;
  18572. // flatten bone matrices to array
  18573. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18574. // compute the offset between the current and the original transform
  18575. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18576. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18577. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18578. }
  18579. if ( boneTexture !== null ) {
  18580. boneTexture.needsUpdate = true;
  18581. }
  18582. }
  18583. clone() {
  18584. return new Skeleton( this.bones, this.boneInverses );
  18585. }
  18586. computeBoneTexture() {
  18587. // layout (1 matrix = 4 pixels)
  18588. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18589. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18590. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18591. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18592. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18593. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18594. size = ceilPowerOfTwo( size );
  18595. size = Math.max( size, 4 );
  18596. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18597. boneMatrices.set( this.boneMatrices ); // copy current values
  18598. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18599. boneTexture.needsUpdate = true;
  18600. this.boneMatrices = boneMatrices;
  18601. this.boneTexture = boneTexture;
  18602. this.boneTextureSize = size;
  18603. return this;
  18604. }
  18605. getBoneByName( name ) {
  18606. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18607. const bone = this.bones[ i ];
  18608. if ( bone.name === name ) {
  18609. return bone;
  18610. }
  18611. }
  18612. return undefined;
  18613. }
  18614. dispose( ) {
  18615. if ( this.boneTexture !== null ) {
  18616. this.boneTexture.dispose();
  18617. this.boneTexture = null;
  18618. }
  18619. }
  18620. fromJSON( json, bones ) {
  18621. this.uuid = json.uuid;
  18622. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18623. const uuid = json.bones[ i ];
  18624. let bone = bones[ uuid ];
  18625. if ( bone === undefined ) {
  18626. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18627. bone = new Bone();
  18628. }
  18629. this.bones.push( bone );
  18630. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18631. }
  18632. this.init();
  18633. return this;
  18634. }
  18635. toJSON() {
  18636. const data = {
  18637. metadata: {
  18638. version: 4.5,
  18639. type: 'Skeleton',
  18640. generator: 'Skeleton.toJSON'
  18641. },
  18642. bones: [],
  18643. boneInverses: []
  18644. };
  18645. data.uuid = this.uuid;
  18646. const bones = this.bones;
  18647. const boneInverses = this.boneInverses;
  18648. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18649. const bone = bones[ i ];
  18650. data.bones.push( bone.uuid );
  18651. const boneInverse = boneInverses[ i ];
  18652. data.boneInverses.push( boneInverse.toArray() );
  18653. }
  18654. return data;
  18655. }
  18656. }
  18657. class InstancedBufferAttribute extends BufferAttribute {
  18658. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18659. super( array, itemSize, normalized );
  18660. this.isInstancedBufferAttribute = true;
  18661. this.meshPerAttribute = meshPerAttribute;
  18662. }
  18663. copy( source ) {
  18664. super.copy( source );
  18665. this.meshPerAttribute = source.meshPerAttribute;
  18666. return this;
  18667. }
  18668. toJSON() {
  18669. const data = super.toJSON();
  18670. data.meshPerAttribute = this.meshPerAttribute;
  18671. data.isInstancedBufferAttribute = true;
  18672. return data;
  18673. }
  18674. }
  18675. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18676. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18677. const _instanceIntersects = [];
  18678. const _box3 = /*@__PURE__*/ new Box3();
  18679. const _identity = /*@__PURE__*/ new Matrix4();
  18680. const _mesh = /*@__PURE__*/ new Mesh();
  18681. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18682. class InstancedMesh extends Mesh {
  18683. constructor( geometry, material, count ) {
  18684. super( geometry, material );
  18685. this.isInstancedMesh = true;
  18686. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18687. this.instanceColor = null;
  18688. this.count = count;
  18689. this.boundingBox = null;
  18690. this.boundingSphere = null;
  18691. for ( let i = 0; i < count; i ++ ) {
  18692. this.setMatrixAt( i, _identity );
  18693. }
  18694. }
  18695. computeBoundingBox() {
  18696. const geometry = this.geometry;
  18697. const count = this.count;
  18698. if ( this.boundingBox === null ) {
  18699. this.boundingBox = new Box3();
  18700. }
  18701. if ( geometry.boundingBox === null ) {
  18702. geometry.computeBoundingBox();
  18703. }
  18704. this.boundingBox.makeEmpty();
  18705. for ( let i = 0; i < count; i ++ ) {
  18706. this.getMatrixAt( i, _instanceLocalMatrix );
  18707. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18708. this.boundingBox.union( _box3 );
  18709. }
  18710. }
  18711. computeBoundingSphere() {
  18712. const geometry = this.geometry;
  18713. const count = this.count;
  18714. if ( this.boundingSphere === null ) {
  18715. this.boundingSphere = new Sphere();
  18716. }
  18717. if ( geometry.boundingSphere === null ) {
  18718. geometry.computeBoundingSphere();
  18719. }
  18720. this.boundingSphere.makeEmpty();
  18721. for ( let i = 0; i < count; i ++ ) {
  18722. this.getMatrixAt( i, _instanceLocalMatrix );
  18723. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18724. this.boundingSphere.union( _sphere$2 );
  18725. }
  18726. }
  18727. copy( source, recursive ) {
  18728. super.copy( source, recursive );
  18729. this.instanceMatrix.copy( source.instanceMatrix );
  18730. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18731. this.count = source.count;
  18732. return this;
  18733. }
  18734. getColorAt( index, color ) {
  18735. color.fromArray( this.instanceColor.array, index * 3 );
  18736. }
  18737. getMatrixAt( index, matrix ) {
  18738. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18739. }
  18740. raycast( raycaster, intersects ) {
  18741. const matrixWorld = this.matrixWorld;
  18742. const raycastTimes = this.count;
  18743. _mesh.geometry = this.geometry;
  18744. _mesh.material = this.material;
  18745. if ( _mesh.material === undefined ) return;
  18746. // test with bounding sphere first
  18747. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18748. _sphere$2.copy( this.boundingSphere );
  18749. _sphere$2.applyMatrix4( matrixWorld );
  18750. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  18751. // now test each instance
  18752. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18753. // calculate the world matrix for each instance
  18754. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18755. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18756. // the mesh represents this single instance
  18757. _mesh.matrixWorld = _instanceWorldMatrix;
  18758. _mesh.raycast( raycaster, _instanceIntersects );
  18759. // process the result of raycast
  18760. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18761. const intersect = _instanceIntersects[ i ];
  18762. intersect.instanceId = instanceId;
  18763. intersect.object = this;
  18764. intersects.push( intersect );
  18765. }
  18766. _instanceIntersects.length = 0;
  18767. }
  18768. }
  18769. setColorAt( index, color ) {
  18770. if ( this.instanceColor === null ) {
  18771. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18772. }
  18773. color.toArray( this.instanceColor.array, index * 3 );
  18774. }
  18775. setMatrixAt( index, matrix ) {
  18776. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18777. }
  18778. updateMorphTargets() {
  18779. }
  18780. dispose() {
  18781. this.dispatchEvent( { type: 'dispose' } );
  18782. }
  18783. }
  18784. class LineBasicMaterial extends Material {
  18785. constructor( parameters ) {
  18786. super();
  18787. this.isLineBasicMaterial = true;
  18788. this.type = 'LineBasicMaterial';
  18789. this.color = new Color( 0xffffff );
  18790. this.map = null;
  18791. this.linewidth = 1;
  18792. this.linecap = 'round';
  18793. this.linejoin = 'round';
  18794. this.fog = true;
  18795. this.setValues( parameters );
  18796. }
  18797. copy( source ) {
  18798. super.copy( source );
  18799. this.color.copy( source.color );
  18800. this.map = source.map;
  18801. this.linewidth = source.linewidth;
  18802. this.linecap = source.linecap;
  18803. this.linejoin = source.linejoin;
  18804. this.fog = source.fog;
  18805. return this;
  18806. }
  18807. }
  18808. const _start$1 = /*@__PURE__*/ new Vector3();
  18809. const _end$1 = /*@__PURE__*/ new Vector3();
  18810. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18811. const _ray$1 = /*@__PURE__*/ new Ray();
  18812. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18813. class Line extends Object3D {
  18814. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18815. super();
  18816. this.isLine = true;
  18817. this.type = 'Line';
  18818. this.geometry = geometry;
  18819. this.material = material;
  18820. this.updateMorphTargets();
  18821. }
  18822. copy( source, recursive ) {
  18823. super.copy( source, recursive );
  18824. this.material = source.material;
  18825. this.geometry = source.geometry;
  18826. return this;
  18827. }
  18828. computeLineDistances() {
  18829. const geometry = this.geometry;
  18830. // we assume non-indexed geometry
  18831. if ( geometry.index === null ) {
  18832. const positionAttribute = geometry.attributes.position;
  18833. const lineDistances = [ 0 ];
  18834. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18835. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18836. _end$1.fromBufferAttribute( positionAttribute, i );
  18837. lineDistances[ i ] = lineDistances[ i - 1 ];
  18838. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18839. }
  18840. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18841. } else {
  18842. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18843. }
  18844. return this;
  18845. }
  18846. raycast( raycaster, intersects ) {
  18847. const geometry = this.geometry;
  18848. const matrixWorld = this.matrixWorld;
  18849. const threshold = raycaster.params.Line.threshold;
  18850. const drawRange = geometry.drawRange;
  18851. // Checking boundingSphere distance to ray
  18852. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18853. _sphere$1.copy( geometry.boundingSphere );
  18854. _sphere$1.applyMatrix4( matrixWorld );
  18855. _sphere$1.radius += threshold;
  18856. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18857. //
  18858. _inverseMatrix$1.copy( matrixWorld ).invert();
  18859. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18860. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18861. const localThresholdSq = localThreshold * localThreshold;
  18862. const vStart = new Vector3();
  18863. const vEnd = new Vector3();
  18864. const interSegment = new Vector3();
  18865. const interRay = new Vector3();
  18866. const step = this.isLineSegments ? 2 : 1;
  18867. const index = geometry.index;
  18868. const attributes = geometry.attributes;
  18869. const positionAttribute = attributes.position;
  18870. if ( index !== null ) {
  18871. const start = Math.max( 0, drawRange.start );
  18872. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18873. for ( let i = start, l = end - 1; i < l; i += step ) {
  18874. const a = index.getX( i );
  18875. const b = index.getX( i + 1 );
  18876. vStart.fromBufferAttribute( positionAttribute, a );
  18877. vEnd.fromBufferAttribute( positionAttribute, b );
  18878. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18879. if ( distSq > localThresholdSq ) continue;
  18880. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18881. const distance = raycaster.ray.origin.distanceTo( interRay );
  18882. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18883. intersects.push( {
  18884. distance: distance,
  18885. // What do we want? intersection point on the ray or on the segment??
  18886. // point: raycaster.ray.at( distance ),
  18887. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18888. index: i,
  18889. face: null,
  18890. faceIndex: null,
  18891. object: this
  18892. } );
  18893. }
  18894. } else {
  18895. const start = Math.max( 0, drawRange.start );
  18896. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18897. for ( let i = start, l = end - 1; i < l; i += step ) {
  18898. vStart.fromBufferAttribute( positionAttribute, i );
  18899. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18900. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18901. if ( distSq > localThresholdSq ) continue;
  18902. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18903. const distance = raycaster.ray.origin.distanceTo( interRay );
  18904. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18905. intersects.push( {
  18906. distance: distance,
  18907. // What do we want? intersection point on the ray or on the segment??
  18908. // point: raycaster.ray.at( distance ),
  18909. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18910. index: i,
  18911. face: null,
  18912. faceIndex: null,
  18913. object: this
  18914. } );
  18915. }
  18916. }
  18917. }
  18918. updateMorphTargets() {
  18919. const geometry = this.geometry;
  18920. const morphAttributes = geometry.morphAttributes;
  18921. const keys = Object.keys( morphAttributes );
  18922. if ( keys.length > 0 ) {
  18923. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18924. if ( morphAttribute !== undefined ) {
  18925. this.morphTargetInfluences = [];
  18926. this.morphTargetDictionary = {};
  18927. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18928. const name = morphAttribute[ m ].name || String( m );
  18929. this.morphTargetInfluences.push( 0 );
  18930. this.morphTargetDictionary[ name ] = m;
  18931. }
  18932. }
  18933. }
  18934. }
  18935. }
  18936. const _start = /*@__PURE__*/ new Vector3();
  18937. const _end = /*@__PURE__*/ new Vector3();
  18938. class LineSegments extends Line {
  18939. constructor( geometry, material ) {
  18940. super( geometry, material );
  18941. this.isLineSegments = true;
  18942. this.type = 'LineSegments';
  18943. }
  18944. computeLineDistances() {
  18945. const geometry = this.geometry;
  18946. // we assume non-indexed geometry
  18947. if ( geometry.index === null ) {
  18948. const positionAttribute = geometry.attributes.position;
  18949. const lineDistances = [];
  18950. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18951. _start.fromBufferAttribute( positionAttribute, i );
  18952. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18953. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18954. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18955. }
  18956. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18957. } else {
  18958. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18959. }
  18960. return this;
  18961. }
  18962. }
  18963. class LineLoop extends Line {
  18964. constructor( geometry, material ) {
  18965. super( geometry, material );
  18966. this.isLineLoop = true;
  18967. this.type = 'LineLoop';
  18968. }
  18969. }
  18970. class PointsMaterial extends Material {
  18971. constructor( parameters ) {
  18972. super();
  18973. this.isPointsMaterial = true;
  18974. this.type = 'PointsMaterial';
  18975. this.color = new Color( 0xffffff );
  18976. this.map = null;
  18977. this.alphaMap = null;
  18978. this.size = 1;
  18979. this.sizeAttenuation = true;
  18980. this.fog = true;
  18981. this.setValues( parameters );
  18982. }
  18983. copy( source ) {
  18984. super.copy( source );
  18985. this.color.copy( source.color );
  18986. this.map = source.map;
  18987. this.alphaMap = source.alphaMap;
  18988. this.size = source.size;
  18989. this.sizeAttenuation = source.sizeAttenuation;
  18990. this.fog = source.fog;
  18991. return this;
  18992. }
  18993. }
  18994. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18995. const _ray = /*@__PURE__*/ new Ray();
  18996. const _sphere = /*@__PURE__*/ new Sphere();
  18997. const _position$2 = /*@__PURE__*/ new Vector3();
  18998. class Points extends Object3D {
  18999. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  19000. super();
  19001. this.isPoints = true;
  19002. this.type = 'Points';
  19003. this.geometry = geometry;
  19004. this.material = material;
  19005. this.updateMorphTargets();
  19006. }
  19007. copy( source, recursive ) {
  19008. super.copy( source, recursive );
  19009. this.material = source.material;
  19010. this.geometry = source.geometry;
  19011. return this;
  19012. }
  19013. raycast( raycaster, intersects ) {
  19014. const geometry = this.geometry;
  19015. const matrixWorld = this.matrixWorld;
  19016. const threshold = raycaster.params.Points.threshold;
  19017. const drawRange = geometry.drawRange;
  19018. // Checking boundingSphere distance to ray
  19019. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19020. _sphere.copy( geometry.boundingSphere );
  19021. _sphere.applyMatrix4( matrixWorld );
  19022. _sphere.radius += threshold;
  19023. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  19024. //
  19025. _inverseMatrix.copy( matrixWorld ).invert();
  19026. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  19027. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19028. const localThresholdSq = localThreshold * localThreshold;
  19029. const index = geometry.index;
  19030. const attributes = geometry.attributes;
  19031. const positionAttribute = attributes.position;
  19032. if ( index !== null ) {
  19033. const start = Math.max( 0, drawRange.start );
  19034. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  19035. for ( let i = start, il = end; i < il; i ++ ) {
  19036. const a = index.getX( i );
  19037. _position$2.fromBufferAttribute( positionAttribute, a );
  19038. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19039. }
  19040. } else {
  19041. const start = Math.max( 0, drawRange.start );
  19042. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  19043. for ( let i = start, l = end; i < l; i ++ ) {
  19044. _position$2.fromBufferAttribute( positionAttribute, i );
  19045. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19046. }
  19047. }
  19048. }
  19049. updateMorphTargets() {
  19050. const geometry = this.geometry;
  19051. const morphAttributes = geometry.morphAttributes;
  19052. const keys = Object.keys( morphAttributes );
  19053. if ( keys.length > 0 ) {
  19054. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  19055. if ( morphAttribute !== undefined ) {
  19056. this.morphTargetInfluences = [];
  19057. this.morphTargetDictionary = {};
  19058. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  19059. const name = morphAttribute[ m ].name || String( m );
  19060. this.morphTargetInfluences.push( 0 );
  19061. this.morphTargetDictionary[ name ] = m;
  19062. }
  19063. }
  19064. }
  19065. }
  19066. }
  19067. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  19068. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  19069. if ( rayPointDistanceSq < localThresholdSq ) {
  19070. const intersectPoint = new Vector3();
  19071. _ray.closestPointToPoint( point, intersectPoint );
  19072. intersectPoint.applyMatrix4( matrixWorld );
  19073. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19074. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19075. intersects.push( {
  19076. distance: distance,
  19077. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19078. point: intersectPoint,
  19079. index: index,
  19080. face: null,
  19081. object: object
  19082. } );
  19083. }
  19084. }
  19085. class VideoTexture extends Texture {
  19086. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19087. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19088. this.isVideoTexture = true;
  19089. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  19090. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  19091. this.generateMipmaps = false;
  19092. const scope = this;
  19093. function updateVideo() {
  19094. scope.needsUpdate = true;
  19095. video.requestVideoFrameCallback( updateVideo );
  19096. }
  19097. if ( 'requestVideoFrameCallback' in video ) {
  19098. video.requestVideoFrameCallback( updateVideo );
  19099. }
  19100. }
  19101. clone() {
  19102. return new this.constructor( this.image ).copy( this );
  19103. }
  19104. update() {
  19105. const video = this.image;
  19106. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  19107. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  19108. this.needsUpdate = true;
  19109. }
  19110. }
  19111. }
  19112. class FramebufferTexture extends Texture {
  19113. constructor( width, height, format ) {
  19114. super( { width, height } );
  19115. this.isFramebufferTexture = true;
  19116. this.format = format;
  19117. this.magFilter = NearestFilter;
  19118. this.minFilter = NearestFilter;
  19119. this.generateMipmaps = false;
  19120. this.needsUpdate = true;
  19121. }
  19122. }
  19123. class CompressedTexture extends Texture {
  19124. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  19125. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19126. this.isCompressedTexture = true;
  19127. this.image = { width: width, height: height };
  19128. this.mipmaps = mipmaps;
  19129. // no flipping for cube textures
  19130. // (also flipping doesn't work for compressed textures )
  19131. this.flipY = false;
  19132. // can't generate mipmaps for compressed textures
  19133. // mips must be embedded in DDS files
  19134. this.generateMipmaps = false;
  19135. }
  19136. }
  19137. class CompressedArrayTexture extends CompressedTexture {
  19138. constructor( mipmaps, width, height, depth, format, type ) {
  19139. super( mipmaps, width, height, format, type );
  19140. this.isCompressedArrayTexture = true;
  19141. this.image.depth = depth;
  19142. this.wrapR = ClampToEdgeWrapping;
  19143. }
  19144. }
  19145. class CanvasTexture extends Texture {
  19146. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19147. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19148. this.isCanvasTexture = true;
  19149. this.needsUpdate = true;
  19150. }
  19151. }
  19152. /**
  19153. * Extensible curve object.
  19154. *
  19155. * Some common of curve methods:
  19156. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19157. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19158. * .getPoints(), .getSpacedPoints()
  19159. * .getLength()
  19160. * .updateArcLengths()
  19161. *
  19162. * This following curves inherit from THREE.Curve:
  19163. *
  19164. * -- 2D curves --
  19165. * THREE.ArcCurve
  19166. * THREE.CubicBezierCurve
  19167. * THREE.EllipseCurve
  19168. * THREE.LineCurve
  19169. * THREE.QuadraticBezierCurve
  19170. * THREE.SplineCurve
  19171. *
  19172. * -- 3D curves --
  19173. * THREE.CatmullRomCurve3
  19174. * THREE.CubicBezierCurve3
  19175. * THREE.LineCurve3
  19176. * THREE.QuadraticBezierCurve3
  19177. *
  19178. * A series of curves can be represented as a THREE.CurvePath.
  19179. *
  19180. **/
  19181. class Curve {
  19182. constructor() {
  19183. this.type = 'Curve';
  19184. this.arcLengthDivisions = 200;
  19185. }
  19186. // Virtual base class method to overwrite and implement in subclasses
  19187. // - t [0 .. 1]
  19188. getPoint( /* t, optionalTarget */ ) {
  19189. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19190. return null;
  19191. }
  19192. // Get point at relative position in curve according to arc length
  19193. // - u [0 .. 1]
  19194. getPointAt( u, optionalTarget ) {
  19195. const t = this.getUtoTmapping( u );
  19196. return this.getPoint( t, optionalTarget );
  19197. }
  19198. // Get sequence of points using getPoint( t )
  19199. getPoints( divisions = 5 ) {
  19200. const points = [];
  19201. for ( let d = 0; d <= divisions; d ++ ) {
  19202. points.push( this.getPoint( d / divisions ) );
  19203. }
  19204. return points;
  19205. }
  19206. // Get sequence of points using getPointAt( u )
  19207. getSpacedPoints( divisions = 5 ) {
  19208. const points = [];
  19209. for ( let d = 0; d <= divisions; d ++ ) {
  19210. points.push( this.getPointAt( d / divisions ) );
  19211. }
  19212. return points;
  19213. }
  19214. // Get total curve arc length
  19215. getLength() {
  19216. const lengths = this.getLengths();
  19217. return lengths[ lengths.length - 1 ];
  19218. }
  19219. // Get list of cumulative segment lengths
  19220. getLengths( divisions = this.arcLengthDivisions ) {
  19221. if ( this.cacheArcLengths &&
  19222. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19223. ! this.needsUpdate ) {
  19224. return this.cacheArcLengths;
  19225. }
  19226. this.needsUpdate = false;
  19227. const cache = [];
  19228. let current, last = this.getPoint( 0 );
  19229. let sum = 0;
  19230. cache.push( 0 );
  19231. for ( let p = 1; p <= divisions; p ++ ) {
  19232. current = this.getPoint( p / divisions );
  19233. sum += current.distanceTo( last );
  19234. cache.push( sum );
  19235. last = current;
  19236. }
  19237. this.cacheArcLengths = cache;
  19238. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19239. }
  19240. updateArcLengths() {
  19241. this.needsUpdate = true;
  19242. this.getLengths();
  19243. }
  19244. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19245. getUtoTmapping( u, distance ) {
  19246. const arcLengths = this.getLengths();
  19247. let i = 0;
  19248. const il = arcLengths.length;
  19249. let targetArcLength; // The targeted u distance value to get
  19250. if ( distance ) {
  19251. targetArcLength = distance;
  19252. } else {
  19253. targetArcLength = u * arcLengths[ il - 1 ];
  19254. }
  19255. // binary search for the index with largest value smaller than target u distance
  19256. let low = 0, high = il - 1, comparison;
  19257. while ( low <= high ) {
  19258. 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
  19259. comparison = arcLengths[ i ] - targetArcLength;
  19260. if ( comparison < 0 ) {
  19261. low = i + 1;
  19262. } else if ( comparison > 0 ) {
  19263. high = i - 1;
  19264. } else {
  19265. high = i;
  19266. break;
  19267. // DONE
  19268. }
  19269. }
  19270. i = high;
  19271. if ( arcLengths[ i ] === targetArcLength ) {
  19272. return i / ( il - 1 );
  19273. }
  19274. // we could get finer grain at lengths, or use simple interpolation between two points
  19275. const lengthBefore = arcLengths[ i ];
  19276. const lengthAfter = arcLengths[ i + 1 ];
  19277. const segmentLength = lengthAfter - lengthBefore;
  19278. // determine where we are between the 'before' and 'after' points
  19279. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19280. // add that fractional amount to t
  19281. const t = ( i + segmentFraction ) / ( il - 1 );
  19282. return t;
  19283. }
  19284. // Returns a unit vector tangent at t
  19285. // In case any sub curve does not implement its tangent derivation,
  19286. // 2 points a small delta apart will be used to find its gradient
  19287. // which seems to give a reasonable approximation
  19288. getTangent( t, optionalTarget ) {
  19289. const delta = 0.0001;
  19290. let t1 = t - delta;
  19291. let t2 = t + delta;
  19292. // Capping in case of danger
  19293. if ( t1 < 0 ) t1 = 0;
  19294. if ( t2 > 1 ) t2 = 1;
  19295. const pt1 = this.getPoint( t1 );
  19296. const pt2 = this.getPoint( t2 );
  19297. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19298. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19299. return tangent;
  19300. }
  19301. getTangentAt( u, optionalTarget ) {
  19302. const t = this.getUtoTmapping( u );
  19303. return this.getTangent( t, optionalTarget );
  19304. }
  19305. computeFrenetFrames( segments, closed ) {
  19306. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19307. const normal = new Vector3();
  19308. const tangents = [];
  19309. const normals = [];
  19310. const binormals = [];
  19311. const vec = new Vector3();
  19312. const mat = new Matrix4();
  19313. // compute the tangent vectors for each segment on the curve
  19314. for ( let i = 0; i <= segments; i ++ ) {
  19315. const u = i / segments;
  19316. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19317. }
  19318. // select an initial normal vector perpendicular to the first tangent vector,
  19319. // and in the direction of the minimum tangent xyz component
  19320. normals[ 0 ] = new Vector3();
  19321. binormals[ 0 ] = new Vector3();
  19322. let min = Number.MAX_VALUE;
  19323. const tx = Math.abs( tangents[ 0 ].x );
  19324. const ty = Math.abs( tangents[ 0 ].y );
  19325. const tz = Math.abs( tangents[ 0 ].z );
  19326. if ( tx <= min ) {
  19327. min = tx;
  19328. normal.set( 1, 0, 0 );
  19329. }
  19330. if ( ty <= min ) {
  19331. min = ty;
  19332. normal.set( 0, 1, 0 );
  19333. }
  19334. if ( tz <= min ) {
  19335. normal.set( 0, 0, 1 );
  19336. }
  19337. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19338. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19339. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19340. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19341. for ( let i = 1; i <= segments; i ++ ) {
  19342. normals[ i ] = normals[ i - 1 ].clone();
  19343. binormals[ i ] = binormals[ i - 1 ].clone();
  19344. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19345. if ( vec.length() > Number.EPSILON ) {
  19346. vec.normalize();
  19347. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19348. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19349. }
  19350. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19351. }
  19352. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19353. if ( closed === true ) {
  19354. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19355. theta /= segments;
  19356. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19357. theta = - theta;
  19358. }
  19359. for ( let i = 1; i <= segments; i ++ ) {
  19360. // twist a little...
  19361. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19362. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19363. }
  19364. }
  19365. return {
  19366. tangents: tangents,
  19367. normals: normals,
  19368. binormals: binormals
  19369. };
  19370. }
  19371. clone() {
  19372. return new this.constructor().copy( this );
  19373. }
  19374. copy( source ) {
  19375. this.arcLengthDivisions = source.arcLengthDivisions;
  19376. return this;
  19377. }
  19378. toJSON() {
  19379. const data = {
  19380. metadata: {
  19381. version: 4.5,
  19382. type: 'Curve',
  19383. generator: 'Curve.toJSON'
  19384. }
  19385. };
  19386. data.arcLengthDivisions = this.arcLengthDivisions;
  19387. data.type = this.type;
  19388. return data;
  19389. }
  19390. fromJSON( json ) {
  19391. this.arcLengthDivisions = json.arcLengthDivisions;
  19392. return this;
  19393. }
  19394. }
  19395. class EllipseCurve extends Curve {
  19396. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19397. super();
  19398. this.isEllipseCurve = true;
  19399. this.type = 'EllipseCurve';
  19400. this.aX = aX;
  19401. this.aY = aY;
  19402. this.xRadius = xRadius;
  19403. this.yRadius = yRadius;
  19404. this.aStartAngle = aStartAngle;
  19405. this.aEndAngle = aEndAngle;
  19406. this.aClockwise = aClockwise;
  19407. this.aRotation = aRotation;
  19408. }
  19409. getPoint( t, optionalTarget ) {
  19410. const point = optionalTarget || new Vector2();
  19411. const twoPi = Math.PI * 2;
  19412. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19413. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19414. // ensures that deltaAngle is 0 .. 2 PI
  19415. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19416. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19417. if ( deltaAngle < Number.EPSILON ) {
  19418. if ( samePoints ) {
  19419. deltaAngle = 0;
  19420. } else {
  19421. deltaAngle = twoPi;
  19422. }
  19423. }
  19424. if ( this.aClockwise === true && ! samePoints ) {
  19425. if ( deltaAngle === twoPi ) {
  19426. deltaAngle = - twoPi;
  19427. } else {
  19428. deltaAngle = deltaAngle - twoPi;
  19429. }
  19430. }
  19431. const angle = this.aStartAngle + t * deltaAngle;
  19432. let x = this.aX + this.xRadius * Math.cos( angle );
  19433. let y = this.aY + this.yRadius * Math.sin( angle );
  19434. if ( this.aRotation !== 0 ) {
  19435. const cos = Math.cos( this.aRotation );
  19436. const sin = Math.sin( this.aRotation );
  19437. const tx = x - this.aX;
  19438. const ty = y - this.aY;
  19439. // Rotate the point about the center of the ellipse.
  19440. x = tx * cos - ty * sin + this.aX;
  19441. y = tx * sin + ty * cos + this.aY;
  19442. }
  19443. return point.set( x, y );
  19444. }
  19445. copy( source ) {
  19446. super.copy( source );
  19447. this.aX = source.aX;
  19448. this.aY = source.aY;
  19449. this.xRadius = source.xRadius;
  19450. this.yRadius = source.yRadius;
  19451. this.aStartAngle = source.aStartAngle;
  19452. this.aEndAngle = source.aEndAngle;
  19453. this.aClockwise = source.aClockwise;
  19454. this.aRotation = source.aRotation;
  19455. return this;
  19456. }
  19457. toJSON() {
  19458. const data = super.toJSON();
  19459. data.aX = this.aX;
  19460. data.aY = this.aY;
  19461. data.xRadius = this.xRadius;
  19462. data.yRadius = this.yRadius;
  19463. data.aStartAngle = this.aStartAngle;
  19464. data.aEndAngle = this.aEndAngle;
  19465. data.aClockwise = this.aClockwise;
  19466. data.aRotation = this.aRotation;
  19467. return data;
  19468. }
  19469. fromJSON( json ) {
  19470. super.fromJSON( json );
  19471. this.aX = json.aX;
  19472. this.aY = json.aY;
  19473. this.xRadius = json.xRadius;
  19474. this.yRadius = json.yRadius;
  19475. this.aStartAngle = json.aStartAngle;
  19476. this.aEndAngle = json.aEndAngle;
  19477. this.aClockwise = json.aClockwise;
  19478. this.aRotation = json.aRotation;
  19479. return this;
  19480. }
  19481. }
  19482. class ArcCurve extends EllipseCurve {
  19483. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19484. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19485. this.isArcCurve = true;
  19486. this.type = 'ArcCurve';
  19487. }
  19488. }
  19489. /**
  19490. * Centripetal CatmullRom Curve - which is useful for avoiding
  19491. * cusps and self-intersections in non-uniform catmull rom curves.
  19492. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19493. *
  19494. * curve.type accepts centripetal(default), chordal and catmullrom
  19495. * curve.tension is used for catmullrom which defaults to 0.5
  19496. */
  19497. /*
  19498. Based on an optimized c++ solution in
  19499. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19500. - http://ideone.com/NoEbVM
  19501. This CubicPoly class could be used for reusing some variables and calculations,
  19502. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19503. which can be placed in CurveUtils.
  19504. */
  19505. function CubicPoly() {
  19506. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19507. /*
  19508. * Compute coefficients for a cubic polynomial
  19509. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19510. * such that
  19511. * p(0) = x0, p(1) = x1
  19512. * and
  19513. * p'(0) = t0, p'(1) = t1.
  19514. */
  19515. function init( x0, x1, t0, t1 ) {
  19516. c0 = x0;
  19517. c1 = t0;
  19518. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19519. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19520. }
  19521. return {
  19522. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19523. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19524. },
  19525. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19526. // compute tangents when parameterized in [t1,t2]
  19527. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19528. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19529. // rescale tangents for parametrization in [0,1]
  19530. t1 *= dt1;
  19531. t2 *= dt1;
  19532. init( x1, x2, t1, t2 );
  19533. },
  19534. calc: function ( t ) {
  19535. const t2 = t * t;
  19536. const t3 = t2 * t;
  19537. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19538. }
  19539. };
  19540. }
  19541. //
  19542. const tmp = /*@__PURE__*/ new Vector3();
  19543. const px = /*@__PURE__*/ new CubicPoly();
  19544. const py = /*@__PURE__*/ new CubicPoly();
  19545. const pz = /*@__PURE__*/ new CubicPoly();
  19546. class CatmullRomCurve3 extends Curve {
  19547. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19548. super();
  19549. this.isCatmullRomCurve3 = true;
  19550. this.type = 'CatmullRomCurve3';
  19551. this.points = points;
  19552. this.closed = closed;
  19553. this.curveType = curveType;
  19554. this.tension = tension;
  19555. }
  19556. getPoint( t, optionalTarget = new Vector3() ) {
  19557. const point = optionalTarget;
  19558. const points = this.points;
  19559. const l = points.length;
  19560. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19561. let intPoint = Math.floor( p );
  19562. let weight = p - intPoint;
  19563. if ( this.closed ) {
  19564. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19565. } else if ( weight === 0 && intPoint === l - 1 ) {
  19566. intPoint = l - 2;
  19567. weight = 1;
  19568. }
  19569. let p0, p3; // 4 points (p1 & p2 defined below)
  19570. if ( this.closed || intPoint > 0 ) {
  19571. p0 = points[ ( intPoint - 1 ) % l ];
  19572. } else {
  19573. // extrapolate first point
  19574. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19575. p0 = tmp;
  19576. }
  19577. const p1 = points[ intPoint % l ];
  19578. const p2 = points[ ( intPoint + 1 ) % l ];
  19579. if ( this.closed || intPoint + 2 < l ) {
  19580. p3 = points[ ( intPoint + 2 ) % l ];
  19581. } else {
  19582. // extrapolate last point
  19583. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19584. p3 = tmp;
  19585. }
  19586. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19587. // init Centripetal / Chordal Catmull-Rom
  19588. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19589. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19590. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19591. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19592. // safety check for repeated points
  19593. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19594. if ( dt0 < 1e-4 ) dt0 = dt1;
  19595. if ( dt2 < 1e-4 ) dt2 = dt1;
  19596. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19597. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19598. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19599. } else if ( this.curveType === 'catmullrom' ) {
  19600. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19601. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19602. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19603. }
  19604. point.set(
  19605. px.calc( weight ),
  19606. py.calc( weight ),
  19607. pz.calc( weight )
  19608. );
  19609. return point;
  19610. }
  19611. copy( source ) {
  19612. super.copy( source );
  19613. this.points = [];
  19614. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19615. const point = source.points[ i ];
  19616. this.points.push( point.clone() );
  19617. }
  19618. this.closed = source.closed;
  19619. this.curveType = source.curveType;
  19620. this.tension = source.tension;
  19621. return this;
  19622. }
  19623. toJSON() {
  19624. const data = super.toJSON();
  19625. data.points = [];
  19626. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19627. const point = this.points[ i ];
  19628. data.points.push( point.toArray() );
  19629. }
  19630. data.closed = this.closed;
  19631. data.curveType = this.curveType;
  19632. data.tension = this.tension;
  19633. return data;
  19634. }
  19635. fromJSON( json ) {
  19636. super.fromJSON( json );
  19637. this.points = [];
  19638. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19639. const point = json.points[ i ];
  19640. this.points.push( new Vector3().fromArray( point ) );
  19641. }
  19642. this.closed = json.closed;
  19643. this.curveType = json.curveType;
  19644. this.tension = json.tension;
  19645. return this;
  19646. }
  19647. }
  19648. /**
  19649. * Bezier Curves formulas obtained from
  19650. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19651. */
  19652. function CatmullRom( t, p0, p1, p2, p3 ) {
  19653. const v0 = ( p2 - p0 ) * 0.5;
  19654. const v1 = ( p3 - p1 ) * 0.5;
  19655. const t2 = t * t;
  19656. const t3 = t * t2;
  19657. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19658. }
  19659. //
  19660. function QuadraticBezierP0( t, p ) {
  19661. const k = 1 - t;
  19662. return k * k * p;
  19663. }
  19664. function QuadraticBezierP1( t, p ) {
  19665. return 2 * ( 1 - t ) * t * p;
  19666. }
  19667. function QuadraticBezierP2( t, p ) {
  19668. return t * t * p;
  19669. }
  19670. function QuadraticBezier( t, p0, p1, p2 ) {
  19671. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19672. QuadraticBezierP2( t, p2 );
  19673. }
  19674. //
  19675. function CubicBezierP0( t, p ) {
  19676. const k = 1 - t;
  19677. return k * k * k * p;
  19678. }
  19679. function CubicBezierP1( t, p ) {
  19680. const k = 1 - t;
  19681. return 3 * k * k * t * p;
  19682. }
  19683. function CubicBezierP2( t, p ) {
  19684. return 3 * ( 1 - t ) * t * t * p;
  19685. }
  19686. function CubicBezierP3( t, p ) {
  19687. return t * t * t * p;
  19688. }
  19689. function CubicBezier( t, p0, p1, p2, p3 ) {
  19690. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19691. CubicBezierP3( t, p3 );
  19692. }
  19693. class CubicBezierCurve extends Curve {
  19694. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19695. super();
  19696. this.isCubicBezierCurve = true;
  19697. this.type = 'CubicBezierCurve';
  19698. this.v0 = v0;
  19699. this.v1 = v1;
  19700. this.v2 = v2;
  19701. this.v3 = v3;
  19702. }
  19703. getPoint( t, optionalTarget = new Vector2() ) {
  19704. const point = optionalTarget;
  19705. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19706. point.set(
  19707. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19708. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19709. );
  19710. return point;
  19711. }
  19712. copy( source ) {
  19713. super.copy( source );
  19714. this.v0.copy( source.v0 );
  19715. this.v1.copy( source.v1 );
  19716. this.v2.copy( source.v2 );
  19717. this.v3.copy( source.v3 );
  19718. return this;
  19719. }
  19720. toJSON() {
  19721. const data = super.toJSON();
  19722. data.v0 = this.v0.toArray();
  19723. data.v1 = this.v1.toArray();
  19724. data.v2 = this.v2.toArray();
  19725. data.v3 = this.v3.toArray();
  19726. return data;
  19727. }
  19728. fromJSON( json ) {
  19729. super.fromJSON( json );
  19730. this.v0.fromArray( json.v0 );
  19731. this.v1.fromArray( json.v1 );
  19732. this.v2.fromArray( json.v2 );
  19733. this.v3.fromArray( json.v3 );
  19734. return this;
  19735. }
  19736. }
  19737. class CubicBezierCurve3 extends Curve {
  19738. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19739. super();
  19740. this.isCubicBezierCurve3 = true;
  19741. this.type = 'CubicBezierCurve3';
  19742. this.v0 = v0;
  19743. this.v1 = v1;
  19744. this.v2 = v2;
  19745. this.v3 = v3;
  19746. }
  19747. getPoint( t, optionalTarget = new Vector3() ) {
  19748. const point = optionalTarget;
  19749. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19750. point.set(
  19751. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19752. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19753. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19754. );
  19755. return point;
  19756. }
  19757. copy( source ) {
  19758. super.copy( source );
  19759. this.v0.copy( source.v0 );
  19760. this.v1.copy( source.v1 );
  19761. this.v2.copy( source.v2 );
  19762. this.v3.copy( source.v3 );
  19763. return this;
  19764. }
  19765. toJSON() {
  19766. const data = super.toJSON();
  19767. data.v0 = this.v0.toArray();
  19768. data.v1 = this.v1.toArray();
  19769. data.v2 = this.v2.toArray();
  19770. data.v3 = this.v3.toArray();
  19771. return data;
  19772. }
  19773. fromJSON( json ) {
  19774. super.fromJSON( json );
  19775. this.v0.fromArray( json.v0 );
  19776. this.v1.fromArray( json.v1 );
  19777. this.v2.fromArray( json.v2 );
  19778. this.v3.fromArray( json.v3 );
  19779. return this;
  19780. }
  19781. }
  19782. class LineCurve extends Curve {
  19783. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19784. super();
  19785. this.isLineCurve = true;
  19786. this.type = 'LineCurve';
  19787. this.v1 = v1;
  19788. this.v2 = v2;
  19789. }
  19790. getPoint( t, optionalTarget = new Vector2() ) {
  19791. const point = optionalTarget;
  19792. if ( t === 1 ) {
  19793. point.copy( this.v2 );
  19794. } else {
  19795. point.copy( this.v2 ).sub( this.v1 );
  19796. point.multiplyScalar( t ).add( this.v1 );
  19797. }
  19798. return point;
  19799. }
  19800. // Line curve is linear, so we can overwrite default getPointAt
  19801. getPointAt( u, optionalTarget ) {
  19802. return this.getPoint( u, optionalTarget );
  19803. }
  19804. getTangent( t, optionalTarget = new Vector2() ) {
  19805. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19806. }
  19807. getTangentAt( u, optionalTarget ) {
  19808. return this.getTangent( u, optionalTarget );
  19809. }
  19810. copy( source ) {
  19811. super.copy( source );
  19812. this.v1.copy( source.v1 );
  19813. this.v2.copy( source.v2 );
  19814. return this;
  19815. }
  19816. toJSON() {
  19817. const data = super.toJSON();
  19818. data.v1 = this.v1.toArray();
  19819. data.v2 = this.v2.toArray();
  19820. return data;
  19821. }
  19822. fromJSON( json ) {
  19823. super.fromJSON( json );
  19824. this.v1.fromArray( json.v1 );
  19825. this.v2.fromArray( json.v2 );
  19826. return this;
  19827. }
  19828. }
  19829. class LineCurve3 extends Curve {
  19830. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19831. super();
  19832. this.isLineCurve3 = true;
  19833. this.type = 'LineCurve3';
  19834. this.v1 = v1;
  19835. this.v2 = v2;
  19836. }
  19837. getPoint( t, optionalTarget = new Vector3() ) {
  19838. const point = optionalTarget;
  19839. if ( t === 1 ) {
  19840. point.copy( this.v2 );
  19841. } else {
  19842. point.copy( this.v2 ).sub( this.v1 );
  19843. point.multiplyScalar( t ).add( this.v1 );
  19844. }
  19845. return point;
  19846. }
  19847. // Line curve is linear, so we can overwrite default getPointAt
  19848. getPointAt( u, optionalTarget ) {
  19849. return this.getPoint( u, optionalTarget );
  19850. }
  19851. getTangent( t, optionalTarget = new Vector3() ) {
  19852. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19853. }
  19854. getTangentAt( u, optionalTarget ) {
  19855. return this.getTangent( u, optionalTarget );
  19856. }
  19857. copy( source ) {
  19858. super.copy( source );
  19859. this.v1.copy( source.v1 );
  19860. this.v2.copy( source.v2 );
  19861. return this;
  19862. }
  19863. toJSON() {
  19864. const data = super.toJSON();
  19865. data.v1 = this.v1.toArray();
  19866. data.v2 = this.v2.toArray();
  19867. return data;
  19868. }
  19869. fromJSON( json ) {
  19870. super.fromJSON( json );
  19871. this.v1.fromArray( json.v1 );
  19872. this.v2.fromArray( json.v2 );
  19873. return this;
  19874. }
  19875. }
  19876. class QuadraticBezierCurve extends Curve {
  19877. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19878. super();
  19879. this.isQuadraticBezierCurve = true;
  19880. this.type = 'QuadraticBezierCurve';
  19881. this.v0 = v0;
  19882. this.v1 = v1;
  19883. this.v2 = v2;
  19884. }
  19885. getPoint( t, optionalTarget = new Vector2() ) {
  19886. const point = optionalTarget;
  19887. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19888. point.set(
  19889. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19890. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19891. );
  19892. return point;
  19893. }
  19894. copy( source ) {
  19895. super.copy( source );
  19896. this.v0.copy( source.v0 );
  19897. this.v1.copy( source.v1 );
  19898. this.v2.copy( source.v2 );
  19899. return this;
  19900. }
  19901. toJSON() {
  19902. const data = super.toJSON();
  19903. data.v0 = this.v0.toArray();
  19904. data.v1 = this.v1.toArray();
  19905. data.v2 = this.v2.toArray();
  19906. return data;
  19907. }
  19908. fromJSON( json ) {
  19909. super.fromJSON( json );
  19910. this.v0.fromArray( json.v0 );
  19911. this.v1.fromArray( json.v1 );
  19912. this.v2.fromArray( json.v2 );
  19913. return this;
  19914. }
  19915. }
  19916. class QuadraticBezierCurve3 extends Curve {
  19917. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19918. super();
  19919. this.isQuadraticBezierCurve3 = true;
  19920. this.type = 'QuadraticBezierCurve3';
  19921. this.v0 = v0;
  19922. this.v1 = v1;
  19923. this.v2 = v2;
  19924. }
  19925. getPoint( t, optionalTarget = new Vector3() ) {
  19926. const point = optionalTarget;
  19927. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19928. point.set(
  19929. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19930. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19931. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19932. );
  19933. return point;
  19934. }
  19935. copy( source ) {
  19936. super.copy( source );
  19937. this.v0.copy( source.v0 );
  19938. this.v1.copy( source.v1 );
  19939. this.v2.copy( source.v2 );
  19940. return this;
  19941. }
  19942. toJSON() {
  19943. const data = super.toJSON();
  19944. data.v0 = this.v0.toArray();
  19945. data.v1 = this.v1.toArray();
  19946. data.v2 = this.v2.toArray();
  19947. return data;
  19948. }
  19949. fromJSON( json ) {
  19950. super.fromJSON( json );
  19951. this.v0.fromArray( json.v0 );
  19952. this.v1.fromArray( json.v1 );
  19953. this.v2.fromArray( json.v2 );
  19954. return this;
  19955. }
  19956. }
  19957. class SplineCurve extends Curve {
  19958. constructor( points = [] ) {
  19959. super();
  19960. this.isSplineCurve = true;
  19961. this.type = 'SplineCurve';
  19962. this.points = points;
  19963. }
  19964. getPoint( t, optionalTarget = new Vector2() ) {
  19965. const point = optionalTarget;
  19966. const points = this.points;
  19967. const p = ( points.length - 1 ) * t;
  19968. const intPoint = Math.floor( p );
  19969. const weight = p - intPoint;
  19970. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19971. const p1 = points[ intPoint ];
  19972. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19973. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19974. point.set(
  19975. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19976. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19977. );
  19978. return point;
  19979. }
  19980. copy( source ) {
  19981. super.copy( source );
  19982. this.points = [];
  19983. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19984. const point = source.points[ i ];
  19985. this.points.push( point.clone() );
  19986. }
  19987. return this;
  19988. }
  19989. toJSON() {
  19990. const data = super.toJSON();
  19991. data.points = [];
  19992. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19993. const point = this.points[ i ];
  19994. data.points.push( point.toArray() );
  19995. }
  19996. return data;
  19997. }
  19998. fromJSON( json ) {
  19999. super.fromJSON( json );
  20000. this.points = [];
  20001. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20002. const point = json.points[ i ];
  20003. this.points.push( new Vector2().fromArray( point ) );
  20004. }
  20005. return this;
  20006. }
  20007. }
  20008. var Curves = /*#__PURE__*/Object.freeze({
  20009. __proto__: null,
  20010. ArcCurve: ArcCurve,
  20011. CatmullRomCurve3: CatmullRomCurve3,
  20012. CubicBezierCurve: CubicBezierCurve,
  20013. CubicBezierCurve3: CubicBezierCurve3,
  20014. EllipseCurve: EllipseCurve,
  20015. LineCurve: LineCurve,
  20016. LineCurve3: LineCurve3,
  20017. QuadraticBezierCurve: QuadraticBezierCurve,
  20018. QuadraticBezierCurve3: QuadraticBezierCurve3,
  20019. SplineCurve: SplineCurve
  20020. });
  20021. /**************************************************************
  20022. * Curved Path - a curve path is simply a array of connected
  20023. * curves, but retains the api of a curve
  20024. **************************************************************/
  20025. class CurvePath extends Curve {
  20026. constructor() {
  20027. super();
  20028. this.type = 'CurvePath';
  20029. this.curves = [];
  20030. this.autoClose = false; // Automatically closes the path
  20031. }
  20032. add( curve ) {
  20033. this.curves.push( curve );
  20034. }
  20035. closePath() {
  20036. // Add a line curve if start and end of lines are not connected
  20037. const startPoint = this.curves[ 0 ].getPoint( 0 );
  20038. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20039. if ( ! startPoint.equals( endPoint ) ) {
  20040. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20041. }
  20042. }
  20043. // To get accurate point with reference to
  20044. // entire path distance at time t,
  20045. // following has to be done:
  20046. // 1. Length of each sub path have to be known
  20047. // 2. Locate and identify type of curve
  20048. // 3. Get t for the curve
  20049. // 4. Return curve.getPointAt(t')
  20050. getPoint( t, optionalTarget ) {
  20051. const d = t * this.getLength();
  20052. const curveLengths = this.getCurveLengths();
  20053. let i = 0;
  20054. // To think about boundaries points.
  20055. while ( i < curveLengths.length ) {
  20056. if ( curveLengths[ i ] >= d ) {
  20057. const diff = curveLengths[ i ] - d;
  20058. const curve = this.curves[ i ];
  20059. const segmentLength = curve.getLength();
  20060. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20061. return curve.getPointAt( u, optionalTarget );
  20062. }
  20063. i ++;
  20064. }
  20065. return null;
  20066. // loop where sum != 0, sum > d , sum+1 <d
  20067. }
  20068. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20069. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20070. // getPoint() depends on getLength
  20071. getLength() {
  20072. const lens = this.getCurveLengths();
  20073. return lens[ lens.length - 1 ];
  20074. }
  20075. // cacheLengths must be recalculated.
  20076. updateArcLengths() {
  20077. this.needsUpdate = true;
  20078. this.cacheLengths = null;
  20079. this.getCurveLengths();
  20080. }
  20081. // Compute lengths and cache them
  20082. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20083. getCurveLengths() {
  20084. // We use cache values if curves and cache array are same length
  20085. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20086. return this.cacheLengths;
  20087. }
  20088. // Get length of sub-curve
  20089. // Push sums into cached array
  20090. const lengths = [];
  20091. let sums = 0;
  20092. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20093. sums += this.curves[ i ].getLength();
  20094. lengths.push( sums );
  20095. }
  20096. this.cacheLengths = lengths;
  20097. return lengths;
  20098. }
  20099. getSpacedPoints( divisions = 40 ) {
  20100. const points = [];
  20101. for ( let i = 0; i <= divisions; i ++ ) {
  20102. points.push( this.getPoint( i / divisions ) );
  20103. }
  20104. if ( this.autoClose ) {
  20105. points.push( points[ 0 ] );
  20106. }
  20107. return points;
  20108. }
  20109. getPoints( divisions = 12 ) {
  20110. const points = [];
  20111. let last;
  20112. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20113. const curve = curves[ i ];
  20114. const resolution = curve.isEllipseCurve ? divisions * 2
  20115. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  20116. : curve.isSplineCurve ? divisions * curve.points.length
  20117. : divisions;
  20118. const pts = curve.getPoints( resolution );
  20119. for ( let j = 0; j < pts.length; j ++ ) {
  20120. const point = pts[ j ];
  20121. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20122. points.push( point );
  20123. last = point;
  20124. }
  20125. }
  20126. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20127. points.push( points[ 0 ] );
  20128. }
  20129. return points;
  20130. }
  20131. copy( source ) {
  20132. super.copy( source );
  20133. this.curves = [];
  20134. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  20135. const curve = source.curves[ i ];
  20136. this.curves.push( curve.clone() );
  20137. }
  20138. this.autoClose = source.autoClose;
  20139. return this;
  20140. }
  20141. toJSON() {
  20142. const data = super.toJSON();
  20143. data.autoClose = this.autoClose;
  20144. data.curves = [];
  20145. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20146. const curve = this.curves[ i ];
  20147. data.curves.push( curve.toJSON() );
  20148. }
  20149. return data;
  20150. }
  20151. fromJSON( json ) {
  20152. super.fromJSON( json );
  20153. this.autoClose = json.autoClose;
  20154. this.curves = [];
  20155. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  20156. const curve = json.curves[ i ];
  20157. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  20158. }
  20159. return this;
  20160. }
  20161. }
  20162. class Path extends CurvePath {
  20163. constructor( points ) {
  20164. super();
  20165. this.type = 'Path';
  20166. this.currentPoint = new Vector2();
  20167. if ( points ) {
  20168. this.setFromPoints( points );
  20169. }
  20170. }
  20171. setFromPoints( points ) {
  20172. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  20173. for ( let i = 1, l = points.length; i < l; i ++ ) {
  20174. this.lineTo( points[ i ].x, points[ i ].y );
  20175. }
  20176. return this;
  20177. }
  20178. moveTo( x, y ) {
  20179. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20180. return this;
  20181. }
  20182. lineTo( x, y ) {
  20183. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20184. this.curves.push( curve );
  20185. this.currentPoint.set( x, y );
  20186. return this;
  20187. }
  20188. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  20189. const curve = new QuadraticBezierCurve(
  20190. this.currentPoint.clone(),
  20191. new Vector2( aCPx, aCPy ),
  20192. new Vector2( aX, aY )
  20193. );
  20194. this.curves.push( curve );
  20195. this.currentPoint.set( aX, aY );
  20196. return this;
  20197. }
  20198. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20199. const curve = new CubicBezierCurve(
  20200. this.currentPoint.clone(),
  20201. new Vector2( aCP1x, aCP1y ),
  20202. new Vector2( aCP2x, aCP2y ),
  20203. new Vector2( aX, aY )
  20204. );
  20205. this.curves.push( curve );
  20206. this.currentPoint.set( aX, aY );
  20207. return this;
  20208. }
  20209. splineThru( pts /*Array of Vector*/ ) {
  20210. const npts = [ this.currentPoint.clone() ].concat( pts );
  20211. const curve = new SplineCurve( npts );
  20212. this.curves.push( curve );
  20213. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20214. return this;
  20215. }
  20216. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20217. const x0 = this.currentPoint.x;
  20218. const y0 = this.currentPoint.y;
  20219. this.absarc( aX + x0, aY + y0, aRadius,
  20220. aStartAngle, aEndAngle, aClockwise );
  20221. return this;
  20222. }
  20223. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20224. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20225. return this;
  20226. }
  20227. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20228. const x0 = this.currentPoint.x;
  20229. const y0 = this.currentPoint.y;
  20230. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20231. return this;
  20232. }
  20233. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20234. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20235. if ( this.curves.length > 0 ) {
  20236. // if a previous curve is present, attempt to join
  20237. const firstPoint = curve.getPoint( 0 );
  20238. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20239. this.lineTo( firstPoint.x, firstPoint.y );
  20240. }
  20241. }
  20242. this.curves.push( curve );
  20243. const lastPoint = curve.getPoint( 1 );
  20244. this.currentPoint.copy( lastPoint );
  20245. return this;
  20246. }
  20247. copy( source ) {
  20248. super.copy( source );
  20249. this.currentPoint.copy( source.currentPoint );
  20250. return this;
  20251. }
  20252. toJSON() {
  20253. const data = super.toJSON();
  20254. data.currentPoint = this.currentPoint.toArray();
  20255. return data;
  20256. }
  20257. fromJSON( json ) {
  20258. super.fromJSON( json );
  20259. this.currentPoint.fromArray( json.currentPoint );
  20260. return this;
  20261. }
  20262. }
  20263. class LatheGeometry extends BufferGeometry {
  20264. 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 ) {
  20265. super();
  20266. this.type = 'LatheGeometry';
  20267. this.parameters = {
  20268. points: points,
  20269. segments: segments,
  20270. phiStart: phiStart,
  20271. phiLength: phiLength
  20272. };
  20273. segments = Math.floor( segments );
  20274. // clamp phiLength so it's in range of [ 0, 2PI ]
  20275. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20276. // buffers
  20277. const indices = [];
  20278. const vertices = [];
  20279. const uvs = [];
  20280. const initNormals = [];
  20281. const normals = [];
  20282. // helper variables
  20283. const inverseSegments = 1.0 / segments;
  20284. const vertex = new Vector3();
  20285. const uv = new Vector2();
  20286. const normal = new Vector3();
  20287. const curNormal = new Vector3();
  20288. const prevNormal = new Vector3();
  20289. let dx = 0;
  20290. let dy = 0;
  20291. // pre-compute normals for initial "meridian"
  20292. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20293. switch ( j ) {
  20294. case 0: // special handling for 1st vertex on path
  20295. dx = points[ j + 1 ].x - points[ j ].x;
  20296. dy = points[ j + 1 ].y - points[ j ].y;
  20297. normal.x = dy * 1.0;
  20298. normal.y = - dx;
  20299. normal.z = dy * 0.0;
  20300. prevNormal.copy( normal );
  20301. normal.normalize();
  20302. initNormals.push( normal.x, normal.y, normal.z );
  20303. break;
  20304. case ( points.length - 1 ): // special handling for last Vertex on path
  20305. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20306. break;
  20307. default: // default handling for all vertices in between
  20308. dx = points[ j + 1 ].x - points[ j ].x;
  20309. dy = points[ j + 1 ].y - points[ j ].y;
  20310. normal.x = dy * 1.0;
  20311. normal.y = - dx;
  20312. normal.z = dy * 0.0;
  20313. curNormal.copy( normal );
  20314. normal.x += prevNormal.x;
  20315. normal.y += prevNormal.y;
  20316. normal.z += prevNormal.z;
  20317. normal.normalize();
  20318. initNormals.push( normal.x, normal.y, normal.z );
  20319. prevNormal.copy( curNormal );
  20320. }
  20321. }
  20322. // generate vertices, uvs and normals
  20323. for ( let i = 0; i <= segments; i ++ ) {
  20324. const phi = phiStart + i * inverseSegments * phiLength;
  20325. const sin = Math.sin( phi );
  20326. const cos = Math.cos( phi );
  20327. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20328. // vertex
  20329. vertex.x = points[ j ].x * sin;
  20330. vertex.y = points[ j ].y;
  20331. vertex.z = points[ j ].x * cos;
  20332. vertices.push( vertex.x, vertex.y, vertex.z );
  20333. // uv
  20334. uv.x = i / segments;
  20335. uv.y = j / ( points.length - 1 );
  20336. uvs.push( uv.x, uv.y );
  20337. // normal
  20338. const x = initNormals[ 3 * j + 0 ] * sin;
  20339. const y = initNormals[ 3 * j + 1 ];
  20340. const z = initNormals[ 3 * j + 0 ] * cos;
  20341. normals.push( x, y, z );
  20342. }
  20343. }
  20344. // indices
  20345. for ( let i = 0; i < segments; i ++ ) {
  20346. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20347. const base = j + i * points.length;
  20348. const a = base;
  20349. const b = base + points.length;
  20350. const c = base + points.length + 1;
  20351. const d = base + 1;
  20352. // faces
  20353. indices.push( a, b, d );
  20354. indices.push( c, d, b );
  20355. }
  20356. }
  20357. // build geometry
  20358. this.setIndex( indices );
  20359. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20360. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20361. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20362. }
  20363. copy( source ) {
  20364. super.copy( source );
  20365. this.parameters = Object.assign( {}, source.parameters );
  20366. return this;
  20367. }
  20368. static fromJSON( data ) {
  20369. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20370. }
  20371. }
  20372. class CapsuleGeometry extends LatheGeometry {
  20373. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20374. const path = new Path();
  20375. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20376. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20377. super( path.getPoints( capSegments ), radialSegments );
  20378. this.type = 'CapsuleGeometry';
  20379. this.parameters = {
  20380. radius: radius,
  20381. height: length,
  20382. capSegments: capSegments,
  20383. radialSegments: radialSegments,
  20384. };
  20385. }
  20386. static fromJSON( data ) {
  20387. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20388. }
  20389. }
  20390. class CircleGeometry extends BufferGeometry {
  20391. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20392. super();
  20393. this.type = 'CircleGeometry';
  20394. this.parameters = {
  20395. radius: radius,
  20396. segments: segments,
  20397. thetaStart: thetaStart,
  20398. thetaLength: thetaLength
  20399. };
  20400. segments = Math.max( 3, segments );
  20401. // buffers
  20402. const indices = [];
  20403. const vertices = [];
  20404. const normals = [];
  20405. const uvs = [];
  20406. // helper variables
  20407. const vertex = new Vector3();
  20408. const uv = new Vector2();
  20409. // center point
  20410. vertices.push( 0, 0, 0 );
  20411. normals.push( 0, 0, 1 );
  20412. uvs.push( 0.5, 0.5 );
  20413. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20414. const segment = thetaStart + s / segments * thetaLength;
  20415. // vertex
  20416. vertex.x = radius * Math.cos( segment );
  20417. vertex.y = radius * Math.sin( segment );
  20418. vertices.push( vertex.x, vertex.y, vertex.z );
  20419. // normal
  20420. normals.push( 0, 0, 1 );
  20421. // uvs
  20422. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20423. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20424. uvs.push( uv.x, uv.y );
  20425. }
  20426. // indices
  20427. for ( let i = 1; i <= segments; i ++ ) {
  20428. indices.push( i, i + 1, 0 );
  20429. }
  20430. // build geometry
  20431. this.setIndex( indices );
  20432. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20433. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20434. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20435. }
  20436. copy( source ) {
  20437. super.copy( source );
  20438. this.parameters = Object.assign( {}, source.parameters );
  20439. return this;
  20440. }
  20441. static fromJSON( data ) {
  20442. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20443. }
  20444. }
  20445. class CylinderGeometry extends BufferGeometry {
  20446. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20447. super();
  20448. this.type = 'CylinderGeometry';
  20449. this.parameters = {
  20450. radiusTop: radiusTop,
  20451. radiusBottom: radiusBottom,
  20452. height: height,
  20453. radialSegments: radialSegments,
  20454. heightSegments: heightSegments,
  20455. openEnded: openEnded,
  20456. thetaStart: thetaStart,
  20457. thetaLength: thetaLength
  20458. };
  20459. const scope = this;
  20460. radialSegments = Math.floor( radialSegments );
  20461. heightSegments = Math.floor( heightSegments );
  20462. // buffers
  20463. const indices = [];
  20464. const vertices = [];
  20465. const normals = [];
  20466. const uvs = [];
  20467. // helper variables
  20468. let index = 0;
  20469. const indexArray = [];
  20470. const halfHeight = height / 2;
  20471. let groupStart = 0;
  20472. // generate geometry
  20473. generateTorso();
  20474. if ( openEnded === false ) {
  20475. if ( radiusTop > 0 ) generateCap( true );
  20476. if ( radiusBottom > 0 ) generateCap( false );
  20477. }
  20478. // build geometry
  20479. this.setIndex( indices );
  20480. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20481. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20482. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20483. function generateTorso() {
  20484. const normal = new Vector3();
  20485. const vertex = new Vector3();
  20486. let groupCount = 0;
  20487. // this will be used to calculate the normal
  20488. const slope = ( radiusBottom - radiusTop ) / height;
  20489. // generate vertices, normals and uvs
  20490. for ( let y = 0; y <= heightSegments; y ++ ) {
  20491. const indexRow = [];
  20492. const v = y / heightSegments;
  20493. // calculate the radius of the current row
  20494. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20495. for ( let x = 0; x <= radialSegments; x ++ ) {
  20496. const u = x / radialSegments;
  20497. const theta = u * thetaLength + thetaStart;
  20498. const sinTheta = Math.sin( theta );
  20499. const cosTheta = Math.cos( theta );
  20500. // vertex
  20501. vertex.x = radius * sinTheta;
  20502. vertex.y = - v * height + halfHeight;
  20503. vertex.z = radius * cosTheta;
  20504. vertices.push( vertex.x, vertex.y, vertex.z );
  20505. // normal
  20506. normal.set( sinTheta, slope, cosTheta ).normalize();
  20507. normals.push( normal.x, normal.y, normal.z );
  20508. // uv
  20509. uvs.push( u, 1 - v );
  20510. // save index of vertex in respective row
  20511. indexRow.push( index ++ );
  20512. }
  20513. // now save vertices of the row in our index array
  20514. indexArray.push( indexRow );
  20515. }
  20516. // generate indices
  20517. for ( let x = 0; x < radialSegments; x ++ ) {
  20518. for ( let y = 0; y < heightSegments; y ++ ) {
  20519. // we use the index array to access the correct indices
  20520. const a = indexArray[ y ][ x ];
  20521. const b = indexArray[ y + 1 ][ x ];
  20522. const c = indexArray[ y + 1 ][ x + 1 ];
  20523. const d = indexArray[ y ][ x + 1 ];
  20524. // faces
  20525. indices.push( a, b, d );
  20526. indices.push( b, c, d );
  20527. // update group counter
  20528. groupCount += 6;
  20529. }
  20530. }
  20531. // add a group to the geometry. this will ensure multi material support
  20532. scope.addGroup( groupStart, groupCount, 0 );
  20533. // calculate new start value for groups
  20534. groupStart += groupCount;
  20535. }
  20536. function generateCap( top ) {
  20537. // save the index of the first center vertex
  20538. const centerIndexStart = index;
  20539. const uv = new Vector2();
  20540. const vertex = new Vector3();
  20541. let groupCount = 0;
  20542. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20543. const sign = ( top === true ) ? 1 : - 1;
  20544. // first we generate the center vertex data of the cap.
  20545. // because the geometry needs one set of uvs per face,
  20546. // we must generate a center vertex per face/segment
  20547. for ( let x = 1; x <= radialSegments; x ++ ) {
  20548. // vertex
  20549. vertices.push( 0, halfHeight * sign, 0 );
  20550. // normal
  20551. normals.push( 0, sign, 0 );
  20552. // uv
  20553. uvs.push( 0.5, 0.5 );
  20554. // increase index
  20555. index ++;
  20556. }
  20557. // save the index of the last center vertex
  20558. const centerIndexEnd = index;
  20559. // now we generate the surrounding vertices, normals and uvs
  20560. for ( let x = 0; x <= radialSegments; x ++ ) {
  20561. const u = x / radialSegments;
  20562. const theta = u * thetaLength + thetaStart;
  20563. const cosTheta = Math.cos( theta );
  20564. const sinTheta = Math.sin( theta );
  20565. // vertex
  20566. vertex.x = radius * sinTheta;
  20567. vertex.y = halfHeight * sign;
  20568. vertex.z = radius * cosTheta;
  20569. vertices.push( vertex.x, vertex.y, vertex.z );
  20570. // normal
  20571. normals.push( 0, sign, 0 );
  20572. // uv
  20573. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20574. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20575. uvs.push( uv.x, uv.y );
  20576. // increase index
  20577. index ++;
  20578. }
  20579. // generate indices
  20580. for ( let x = 0; x < radialSegments; x ++ ) {
  20581. const c = centerIndexStart + x;
  20582. const i = centerIndexEnd + x;
  20583. if ( top === true ) {
  20584. // face top
  20585. indices.push( i, i + 1, c );
  20586. } else {
  20587. // face bottom
  20588. indices.push( i + 1, i, c );
  20589. }
  20590. groupCount += 3;
  20591. }
  20592. // add a group to the geometry. this will ensure multi material support
  20593. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20594. // calculate new start value for groups
  20595. groupStart += groupCount;
  20596. }
  20597. }
  20598. copy( source ) {
  20599. super.copy( source );
  20600. this.parameters = Object.assign( {}, source.parameters );
  20601. return this;
  20602. }
  20603. static fromJSON( data ) {
  20604. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20605. }
  20606. }
  20607. class ConeGeometry extends CylinderGeometry {
  20608. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20609. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20610. this.type = 'ConeGeometry';
  20611. this.parameters = {
  20612. radius: radius,
  20613. height: height,
  20614. radialSegments: radialSegments,
  20615. heightSegments: heightSegments,
  20616. openEnded: openEnded,
  20617. thetaStart: thetaStart,
  20618. thetaLength: thetaLength
  20619. };
  20620. }
  20621. static fromJSON( data ) {
  20622. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20623. }
  20624. }
  20625. class PolyhedronGeometry extends BufferGeometry {
  20626. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20627. super();
  20628. this.type = 'PolyhedronGeometry';
  20629. this.parameters = {
  20630. vertices: vertices,
  20631. indices: indices,
  20632. radius: radius,
  20633. detail: detail
  20634. };
  20635. // default buffer data
  20636. const vertexBuffer = [];
  20637. const uvBuffer = [];
  20638. // the subdivision creates the vertex buffer data
  20639. subdivide( detail );
  20640. // all vertices should lie on a conceptual sphere with a given radius
  20641. applyRadius( radius );
  20642. // finally, create the uv data
  20643. generateUVs();
  20644. // build non-indexed geometry
  20645. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20646. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20647. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20648. if ( detail === 0 ) {
  20649. this.computeVertexNormals(); // flat normals
  20650. } else {
  20651. this.normalizeNormals(); // smooth normals
  20652. }
  20653. // helper functions
  20654. function subdivide( detail ) {
  20655. const a = new Vector3();
  20656. const b = new Vector3();
  20657. const c = new Vector3();
  20658. // iterate over all faces and apply a subdivision with the given detail value
  20659. for ( let i = 0; i < indices.length; i += 3 ) {
  20660. // get the vertices of the face
  20661. getVertexByIndex( indices[ i + 0 ], a );
  20662. getVertexByIndex( indices[ i + 1 ], b );
  20663. getVertexByIndex( indices[ i + 2 ], c );
  20664. // perform subdivision
  20665. subdivideFace( a, b, c, detail );
  20666. }
  20667. }
  20668. function subdivideFace( a, b, c, detail ) {
  20669. const cols = detail + 1;
  20670. // we use this multidimensional array as a data structure for creating the subdivision
  20671. const v = [];
  20672. // construct all of the vertices for this subdivision
  20673. for ( let i = 0; i <= cols; i ++ ) {
  20674. v[ i ] = [];
  20675. const aj = a.clone().lerp( c, i / cols );
  20676. const bj = b.clone().lerp( c, i / cols );
  20677. const rows = cols - i;
  20678. for ( let j = 0; j <= rows; j ++ ) {
  20679. if ( j === 0 && i === cols ) {
  20680. v[ i ][ j ] = aj;
  20681. } else {
  20682. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20683. }
  20684. }
  20685. }
  20686. // construct all of the faces
  20687. for ( let i = 0; i < cols; i ++ ) {
  20688. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20689. const k = Math.floor( j / 2 );
  20690. if ( j % 2 === 0 ) {
  20691. pushVertex( v[ i ][ k + 1 ] );
  20692. pushVertex( v[ i + 1 ][ k ] );
  20693. pushVertex( v[ i ][ k ] );
  20694. } else {
  20695. pushVertex( v[ i ][ k + 1 ] );
  20696. pushVertex( v[ i + 1 ][ k + 1 ] );
  20697. pushVertex( v[ i + 1 ][ k ] );
  20698. }
  20699. }
  20700. }
  20701. }
  20702. function applyRadius( radius ) {
  20703. const vertex = new Vector3();
  20704. // iterate over the entire buffer and apply the radius to each vertex
  20705. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20706. vertex.x = vertexBuffer[ i + 0 ];
  20707. vertex.y = vertexBuffer[ i + 1 ];
  20708. vertex.z = vertexBuffer[ i + 2 ];
  20709. vertex.normalize().multiplyScalar( radius );
  20710. vertexBuffer[ i + 0 ] = vertex.x;
  20711. vertexBuffer[ i + 1 ] = vertex.y;
  20712. vertexBuffer[ i + 2 ] = vertex.z;
  20713. }
  20714. }
  20715. function generateUVs() {
  20716. const vertex = new Vector3();
  20717. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20718. vertex.x = vertexBuffer[ i + 0 ];
  20719. vertex.y = vertexBuffer[ i + 1 ];
  20720. vertex.z = vertexBuffer[ i + 2 ];
  20721. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20722. const v = inclination( vertex ) / Math.PI + 0.5;
  20723. uvBuffer.push( u, 1 - v );
  20724. }
  20725. correctUVs();
  20726. correctSeam();
  20727. }
  20728. function correctSeam() {
  20729. // handle case when face straddles the seam, see #3269
  20730. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20731. // uv data of a single face
  20732. const x0 = uvBuffer[ i + 0 ];
  20733. const x1 = uvBuffer[ i + 2 ];
  20734. const x2 = uvBuffer[ i + 4 ];
  20735. const max = Math.max( x0, x1, x2 );
  20736. const min = Math.min( x0, x1, x2 );
  20737. // 0.9 is somewhat arbitrary
  20738. if ( max > 0.9 && min < 0.1 ) {
  20739. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20740. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20741. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20742. }
  20743. }
  20744. }
  20745. function pushVertex( vertex ) {
  20746. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20747. }
  20748. function getVertexByIndex( index, vertex ) {
  20749. const stride = index * 3;
  20750. vertex.x = vertices[ stride + 0 ];
  20751. vertex.y = vertices[ stride + 1 ];
  20752. vertex.z = vertices[ stride + 2 ];
  20753. }
  20754. function correctUVs() {
  20755. const a = new Vector3();
  20756. const b = new Vector3();
  20757. const c = new Vector3();
  20758. const centroid = new Vector3();
  20759. const uvA = new Vector2();
  20760. const uvB = new Vector2();
  20761. const uvC = new Vector2();
  20762. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20763. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20764. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20765. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20766. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20767. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20768. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20769. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20770. const azi = azimuth( centroid );
  20771. correctUV( uvA, j + 0, a, azi );
  20772. correctUV( uvB, j + 2, b, azi );
  20773. correctUV( uvC, j + 4, c, azi );
  20774. }
  20775. }
  20776. function correctUV( uv, stride, vector, azimuth ) {
  20777. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20778. uvBuffer[ stride ] = uv.x - 1;
  20779. }
  20780. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20781. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20782. }
  20783. }
  20784. // Angle around the Y axis, counter-clockwise when looking from above.
  20785. function azimuth( vector ) {
  20786. return Math.atan2( vector.z, - vector.x );
  20787. }
  20788. // Angle above the XZ plane.
  20789. function inclination( vector ) {
  20790. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20791. }
  20792. }
  20793. copy( source ) {
  20794. super.copy( source );
  20795. this.parameters = Object.assign( {}, source.parameters );
  20796. return this;
  20797. }
  20798. static fromJSON( data ) {
  20799. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20800. }
  20801. }
  20802. class DodecahedronGeometry extends PolyhedronGeometry {
  20803. constructor( radius = 1, detail = 0 ) {
  20804. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20805. const r = 1 / t;
  20806. const vertices = [
  20807. // (±1, ±1, ±1)
  20808. - 1, - 1, - 1, - 1, - 1, 1,
  20809. - 1, 1, - 1, - 1, 1, 1,
  20810. 1, - 1, - 1, 1, - 1, 1,
  20811. 1, 1, - 1, 1, 1, 1,
  20812. // (0, ±1/φ, ±φ)
  20813. 0, - r, - t, 0, - r, t,
  20814. 0, r, - t, 0, r, t,
  20815. // (±1/φ, ±φ, 0)
  20816. - r, - t, 0, - r, t, 0,
  20817. r, - t, 0, r, t, 0,
  20818. // (±φ, 0, ±1/φ)
  20819. - t, 0, - r, t, 0, - r,
  20820. - t, 0, r, t, 0, r
  20821. ];
  20822. const indices = [
  20823. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20824. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20825. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20826. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20827. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20828. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20829. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20830. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20831. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20832. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20833. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20834. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20835. ];
  20836. super( vertices, indices, radius, detail );
  20837. this.type = 'DodecahedronGeometry';
  20838. this.parameters = {
  20839. radius: radius,
  20840. detail: detail
  20841. };
  20842. }
  20843. static fromJSON( data ) {
  20844. return new DodecahedronGeometry( data.radius, data.detail );
  20845. }
  20846. }
  20847. const _v0 = /*@__PURE__*/ new Vector3();
  20848. const _v1$1 = /*@__PURE__*/ new Vector3();
  20849. const _normal = /*@__PURE__*/ new Vector3();
  20850. const _triangle = /*@__PURE__*/ new Triangle();
  20851. class EdgesGeometry extends BufferGeometry {
  20852. constructor( geometry = null, thresholdAngle = 1 ) {
  20853. super();
  20854. this.type = 'EdgesGeometry';
  20855. this.parameters = {
  20856. geometry: geometry,
  20857. thresholdAngle: thresholdAngle
  20858. };
  20859. if ( geometry !== null ) {
  20860. const precisionPoints = 4;
  20861. const precision = Math.pow( 10, precisionPoints );
  20862. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20863. const indexAttr = geometry.getIndex();
  20864. const positionAttr = geometry.getAttribute( 'position' );
  20865. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20866. const indexArr = [ 0, 0, 0 ];
  20867. const vertKeys = [ 'a', 'b', 'c' ];
  20868. const hashes = new Array( 3 );
  20869. const edgeData = {};
  20870. const vertices = [];
  20871. for ( let i = 0; i < indexCount; i += 3 ) {
  20872. if ( indexAttr ) {
  20873. indexArr[ 0 ] = indexAttr.getX( i );
  20874. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20875. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20876. } else {
  20877. indexArr[ 0 ] = i;
  20878. indexArr[ 1 ] = i + 1;
  20879. indexArr[ 2 ] = i + 2;
  20880. }
  20881. const { a, b, c } = _triangle;
  20882. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20883. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20884. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20885. _triangle.getNormal( _normal );
  20886. // create hashes for the edge from the vertices
  20887. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20888. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20889. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20890. // skip degenerate triangles
  20891. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20892. continue;
  20893. }
  20894. // iterate over every edge
  20895. for ( let j = 0; j < 3; j ++ ) {
  20896. // get the first and next vertex making up the edge
  20897. const jNext = ( j + 1 ) % 3;
  20898. const vecHash0 = hashes[ j ];
  20899. const vecHash1 = hashes[ jNext ];
  20900. const v0 = _triangle[ vertKeys[ j ] ];
  20901. const v1 = _triangle[ vertKeys[ jNext ] ];
  20902. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20903. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20904. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20905. // if we found a sibling edge add it into the vertex array if
  20906. // it meets the angle threshold and delete the edge from the map.
  20907. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20908. vertices.push( v0.x, v0.y, v0.z );
  20909. vertices.push( v1.x, v1.y, v1.z );
  20910. }
  20911. edgeData[ reverseHash ] = null;
  20912. } else if ( ! ( hash in edgeData ) ) {
  20913. // if we've already got an edge here then skip adding a new one
  20914. edgeData[ hash ] = {
  20915. index0: indexArr[ j ],
  20916. index1: indexArr[ jNext ],
  20917. normal: _normal.clone(),
  20918. };
  20919. }
  20920. }
  20921. }
  20922. // iterate over all remaining, unmatched edges and add them to the vertex array
  20923. for ( const key in edgeData ) {
  20924. if ( edgeData[ key ] ) {
  20925. const { index0, index1 } = edgeData[ key ];
  20926. _v0.fromBufferAttribute( positionAttr, index0 );
  20927. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20928. vertices.push( _v0.x, _v0.y, _v0.z );
  20929. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20930. }
  20931. }
  20932. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20933. }
  20934. }
  20935. copy( source ) {
  20936. super.copy( source );
  20937. this.parameters = Object.assign( {}, source.parameters );
  20938. return this;
  20939. }
  20940. }
  20941. class Shape extends Path {
  20942. constructor( points ) {
  20943. super( points );
  20944. this.uuid = generateUUID();
  20945. this.type = 'Shape';
  20946. this.holes = [];
  20947. }
  20948. getPointsHoles( divisions ) {
  20949. const holesPts = [];
  20950. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20951. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20952. }
  20953. return holesPts;
  20954. }
  20955. // get points of shape and holes (keypoints based on segments parameter)
  20956. extractPoints( divisions ) {
  20957. return {
  20958. shape: this.getPoints( divisions ),
  20959. holes: this.getPointsHoles( divisions )
  20960. };
  20961. }
  20962. copy( source ) {
  20963. super.copy( source );
  20964. this.holes = [];
  20965. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20966. const hole = source.holes[ i ];
  20967. this.holes.push( hole.clone() );
  20968. }
  20969. return this;
  20970. }
  20971. toJSON() {
  20972. const data = super.toJSON();
  20973. data.uuid = this.uuid;
  20974. data.holes = [];
  20975. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20976. const hole = this.holes[ i ];
  20977. data.holes.push( hole.toJSON() );
  20978. }
  20979. return data;
  20980. }
  20981. fromJSON( json ) {
  20982. super.fromJSON( json );
  20983. this.uuid = json.uuid;
  20984. this.holes = [];
  20985. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20986. const hole = json.holes[ i ];
  20987. this.holes.push( new Path().fromJSON( hole ) );
  20988. }
  20989. return this;
  20990. }
  20991. }
  20992. /**
  20993. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20994. */
  20995. const Earcut = {
  20996. triangulate: function ( data, holeIndices, dim = 2 ) {
  20997. const hasHoles = holeIndices && holeIndices.length;
  20998. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20999. let outerNode = linkedList( data, 0, outerLen, dim, true );
  21000. const triangles = [];
  21001. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  21002. let minX, minY, maxX, maxY, x, y, invSize;
  21003. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  21004. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  21005. if ( data.length > 80 * dim ) {
  21006. minX = maxX = data[ 0 ];
  21007. minY = maxY = data[ 1 ];
  21008. for ( let i = dim; i < outerLen; i += dim ) {
  21009. x = data[ i ];
  21010. y = data[ i + 1 ];
  21011. if ( x < minX ) minX = x;
  21012. if ( y < minY ) minY = y;
  21013. if ( x > maxX ) maxX = x;
  21014. if ( y > maxY ) maxY = y;
  21015. }
  21016. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  21017. invSize = Math.max( maxX - minX, maxY - minY );
  21018. invSize = invSize !== 0 ? 32767 / invSize : 0;
  21019. }
  21020. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  21021. return triangles;
  21022. }
  21023. };
  21024. // create a circular doubly linked list from polygon points in the specified winding order
  21025. function linkedList( data, start, end, dim, clockwise ) {
  21026. let i, last;
  21027. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  21028. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21029. } else {
  21030. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21031. }
  21032. if ( last && equals( last, last.next ) ) {
  21033. removeNode( last );
  21034. last = last.next;
  21035. }
  21036. return last;
  21037. }
  21038. // eliminate colinear or duplicate points
  21039. function filterPoints( start, end ) {
  21040. if ( ! start ) return start;
  21041. if ( ! end ) end = start;
  21042. let p = start,
  21043. again;
  21044. do {
  21045. again = false;
  21046. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  21047. removeNode( p );
  21048. p = end = p.prev;
  21049. if ( p === p.next ) break;
  21050. again = true;
  21051. } else {
  21052. p = p.next;
  21053. }
  21054. } while ( again || p !== end );
  21055. return end;
  21056. }
  21057. // main ear slicing loop which triangulates a polygon (given as a linked list)
  21058. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  21059. if ( ! ear ) return;
  21060. // interlink polygon nodes in z-order
  21061. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  21062. let stop = ear,
  21063. prev, next;
  21064. // iterate through ears, slicing them one by one
  21065. while ( ear.prev !== ear.next ) {
  21066. prev = ear.prev;
  21067. next = ear.next;
  21068. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  21069. // cut off the triangle
  21070. triangles.push( prev.i / dim | 0 );
  21071. triangles.push( ear.i / dim | 0 );
  21072. triangles.push( next.i / dim | 0 );
  21073. removeNode( ear );
  21074. // skipping the next vertex leads to less sliver triangles
  21075. ear = next.next;
  21076. stop = next.next;
  21077. continue;
  21078. }
  21079. ear = next;
  21080. // if we looped through the whole remaining polygon and can't find any more ears
  21081. if ( ear === stop ) {
  21082. // try filtering points and slicing again
  21083. if ( ! pass ) {
  21084. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  21085. // if this didn't work, try curing all small self-intersections locally
  21086. } else if ( pass === 1 ) {
  21087. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  21088. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  21089. // as a last resort, try splitting the remaining polygon into two
  21090. } else if ( pass === 2 ) {
  21091. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  21092. }
  21093. break;
  21094. }
  21095. }
  21096. }
  21097. // check whether a polygon node forms a valid ear with adjacent nodes
  21098. function isEar( ear ) {
  21099. const a = ear.prev,
  21100. b = ear,
  21101. c = ear.next;
  21102. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21103. // now make sure we don't have other points inside the potential ear
  21104. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21105. // triangle bbox; min & max are calculated like this for speed
  21106. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21107. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21108. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21109. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21110. let p = c.next;
  21111. while ( p !== a ) {
  21112. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  21113. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  21114. area( p.prev, p, p.next ) >= 0 ) return false;
  21115. p = p.next;
  21116. }
  21117. return true;
  21118. }
  21119. function isEarHashed( ear, minX, minY, invSize ) {
  21120. const a = ear.prev,
  21121. b = ear,
  21122. c = ear.next;
  21123. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21124. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21125. // triangle bbox; min & max are calculated like this for speed
  21126. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21127. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21128. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21129. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21130. // z-order range for the current triangle bbox;
  21131. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  21132. maxZ = zOrder( x1, y1, minX, minY, invSize );
  21133. let p = ear.prevZ,
  21134. n = ear.nextZ;
  21135. // look for points inside the triangle in both directions
  21136. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  21137. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21138. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21139. p = p.prevZ;
  21140. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21141. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21142. n = n.nextZ;
  21143. }
  21144. // look for remaining points in decreasing z-order
  21145. while ( p && p.z >= minZ ) {
  21146. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21147. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21148. p = p.prevZ;
  21149. }
  21150. // look for remaining points in increasing z-order
  21151. while ( n && n.z <= maxZ ) {
  21152. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21153. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21154. n = n.nextZ;
  21155. }
  21156. return true;
  21157. }
  21158. // go through all polygon nodes and cure small local self-intersections
  21159. function cureLocalIntersections( start, triangles, dim ) {
  21160. let p = start;
  21161. do {
  21162. const a = p.prev,
  21163. b = p.next.next;
  21164. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21165. triangles.push( a.i / dim | 0 );
  21166. triangles.push( p.i / dim | 0 );
  21167. triangles.push( b.i / dim | 0 );
  21168. // remove two nodes involved
  21169. removeNode( p );
  21170. removeNode( p.next );
  21171. p = start = b;
  21172. }
  21173. p = p.next;
  21174. } while ( p !== start );
  21175. return filterPoints( p );
  21176. }
  21177. // try splitting polygon into two and triangulate them independently
  21178. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21179. // look for a valid diagonal that divides the polygon into two
  21180. let a = start;
  21181. do {
  21182. let b = a.next.next;
  21183. while ( b !== a.prev ) {
  21184. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21185. // split the polygon in two by the diagonal
  21186. let c = splitPolygon( a, b );
  21187. // filter colinear points around the cuts
  21188. a = filterPoints( a, a.next );
  21189. c = filterPoints( c, c.next );
  21190. // run earcut on each half
  21191. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  21192. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  21193. return;
  21194. }
  21195. b = b.next;
  21196. }
  21197. a = a.next;
  21198. } while ( a !== start );
  21199. }
  21200. // link every hole into the outer loop, producing a single-ring polygon without holes
  21201. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21202. const queue = [];
  21203. let i, len, start, end, list;
  21204. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21205. start = holeIndices[ i ] * dim;
  21206. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21207. list = linkedList( data, start, end, dim, false );
  21208. if ( list === list.next ) list.steiner = true;
  21209. queue.push( getLeftmost( list ) );
  21210. }
  21211. queue.sort( compareX );
  21212. // process holes from left to right
  21213. for ( i = 0; i < queue.length; i ++ ) {
  21214. outerNode = eliminateHole( queue[ i ], outerNode );
  21215. }
  21216. return outerNode;
  21217. }
  21218. function compareX( a, b ) {
  21219. return a.x - b.x;
  21220. }
  21221. // find a bridge between vertices that connects hole with an outer ring and link it
  21222. function eliminateHole( hole, outerNode ) {
  21223. const bridge = findHoleBridge( hole, outerNode );
  21224. if ( ! bridge ) {
  21225. return outerNode;
  21226. }
  21227. const bridgeReverse = splitPolygon( bridge, hole );
  21228. // filter collinear points around the cuts
  21229. filterPoints( bridgeReverse, bridgeReverse.next );
  21230. return filterPoints( bridge, bridge.next );
  21231. }
  21232. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21233. function findHoleBridge( hole, outerNode ) {
  21234. let p = outerNode,
  21235. qx = - Infinity,
  21236. m;
  21237. const hx = hole.x, hy = hole.y;
  21238. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21239. // segment's endpoint with lesser x will be potential connection point
  21240. do {
  21241. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21242. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21243. if ( x <= hx && x > qx ) {
  21244. qx = x;
  21245. m = p.x < p.next.x ? p : p.next;
  21246. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21247. }
  21248. }
  21249. p = p.next;
  21250. } while ( p !== outerNode );
  21251. if ( ! m ) return null;
  21252. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21253. // if there are no points found, we have a valid connection;
  21254. // otherwise choose the point of the minimum angle with the ray as connection point
  21255. const stop = m,
  21256. mx = m.x,
  21257. my = m.y;
  21258. let tanMin = Infinity, tan;
  21259. p = m;
  21260. do {
  21261. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21262. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21263. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21264. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21265. m = p;
  21266. tanMin = tan;
  21267. }
  21268. }
  21269. p = p.next;
  21270. } while ( p !== stop );
  21271. return m;
  21272. }
  21273. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21274. function sectorContainsSector( m, p ) {
  21275. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21276. }
  21277. // interlink polygon nodes in z-order
  21278. function indexCurve( start, minX, minY, invSize ) {
  21279. let p = start;
  21280. do {
  21281. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21282. p.prevZ = p.prev;
  21283. p.nextZ = p.next;
  21284. p = p.next;
  21285. } while ( p !== start );
  21286. p.prevZ.nextZ = null;
  21287. p.prevZ = null;
  21288. sortLinked( p );
  21289. }
  21290. // Simon Tatham's linked list merge sort algorithm
  21291. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21292. function sortLinked( list ) {
  21293. let i, p, q, e, tail, numMerges, pSize, qSize,
  21294. inSize = 1;
  21295. do {
  21296. p = list;
  21297. list = null;
  21298. tail = null;
  21299. numMerges = 0;
  21300. while ( p ) {
  21301. numMerges ++;
  21302. q = p;
  21303. pSize = 0;
  21304. for ( i = 0; i < inSize; i ++ ) {
  21305. pSize ++;
  21306. q = q.nextZ;
  21307. if ( ! q ) break;
  21308. }
  21309. qSize = inSize;
  21310. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21311. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21312. e = p;
  21313. p = p.nextZ;
  21314. pSize --;
  21315. } else {
  21316. e = q;
  21317. q = q.nextZ;
  21318. qSize --;
  21319. }
  21320. if ( tail ) tail.nextZ = e;
  21321. else list = e;
  21322. e.prevZ = tail;
  21323. tail = e;
  21324. }
  21325. p = q;
  21326. }
  21327. tail.nextZ = null;
  21328. inSize *= 2;
  21329. } while ( numMerges > 1 );
  21330. return list;
  21331. }
  21332. // z-order of a point given coords and inverse of the longer side of data bbox
  21333. function zOrder( x, y, minX, minY, invSize ) {
  21334. // coords are transformed into non-negative 15-bit integer range
  21335. x = ( x - minX ) * invSize | 0;
  21336. y = ( y - minY ) * invSize | 0;
  21337. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21338. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21339. x = ( x | ( x << 2 ) ) & 0x33333333;
  21340. x = ( x | ( x << 1 ) ) & 0x55555555;
  21341. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21342. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21343. y = ( y | ( y << 2 ) ) & 0x33333333;
  21344. y = ( y | ( y << 1 ) ) & 0x55555555;
  21345. return x | ( y << 1 );
  21346. }
  21347. // find the leftmost node of a polygon ring
  21348. function getLeftmost( start ) {
  21349. let p = start,
  21350. leftmost = start;
  21351. do {
  21352. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21353. p = p.next;
  21354. } while ( p !== start );
  21355. return leftmost;
  21356. }
  21357. // check if a point lies within a convex triangle
  21358. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21359. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21360. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21361. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21362. }
  21363. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21364. function isValidDiagonal( a, b ) {
  21365. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21366. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21367. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21368. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21369. }
  21370. // signed area of a triangle
  21371. function area( p, q, r ) {
  21372. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21373. }
  21374. // check if two points are equal
  21375. function equals( p1, p2 ) {
  21376. return p1.x === p2.x && p1.y === p2.y;
  21377. }
  21378. // check if two segments intersect
  21379. function intersects( p1, q1, p2, q2 ) {
  21380. const o1 = sign( area( p1, q1, p2 ) );
  21381. const o2 = sign( area( p1, q1, q2 ) );
  21382. const o3 = sign( area( p2, q2, p1 ) );
  21383. const o4 = sign( area( p2, q2, q1 ) );
  21384. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21385. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21386. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21387. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21388. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21389. return false;
  21390. }
  21391. // for collinear points p, q, r, check if point q lies on segment pr
  21392. function onSegment( p, q, r ) {
  21393. 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 );
  21394. }
  21395. function sign( num ) {
  21396. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21397. }
  21398. // check if a polygon diagonal intersects any polygon segments
  21399. function intersectsPolygon( a, b ) {
  21400. let p = a;
  21401. do {
  21402. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21403. intersects( p, p.next, a, b ) ) return true;
  21404. p = p.next;
  21405. } while ( p !== a );
  21406. return false;
  21407. }
  21408. // check if a polygon diagonal is locally inside the polygon
  21409. function locallyInside( a, b ) {
  21410. return area( a.prev, a, a.next ) < 0 ?
  21411. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21412. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21413. }
  21414. // check if the middle point of a polygon diagonal is inside the polygon
  21415. function middleInside( a, b ) {
  21416. let p = a,
  21417. inside = false;
  21418. const px = ( a.x + b.x ) / 2,
  21419. py = ( a.y + b.y ) / 2;
  21420. do {
  21421. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21422. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21423. inside = ! inside;
  21424. p = p.next;
  21425. } while ( p !== a );
  21426. return inside;
  21427. }
  21428. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21429. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21430. function splitPolygon( a, b ) {
  21431. const a2 = new Node( a.i, a.x, a.y ),
  21432. b2 = new Node( b.i, b.x, b.y ),
  21433. an = a.next,
  21434. bp = b.prev;
  21435. a.next = b;
  21436. b.prev = a;
  21437. a2.next = an;
  21438. an.prev = a2;
  21439. b2.next = a2;
  21440. a2.prev = b2;
  21441. bp.next = b2;
  21442. b2.prev = bp;
  21443. return b2;
  21444. }
  21445. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21446. function insertNode( i, x, y, last ) {
  21447. const p = new Node( i, x, y );
  21448. if ( ! last ) {
  21449. p.prev = p;
  21450. p.next = p;
  21451. } else {
  21452. p.next = last.next;
  21453. p.prev = last;
  21454. last.next.prev = p;
  21455. last.next = p;
  21456. }
  21457. return p;
  21458. }
  21459. function removeNode( p ) {
  21460. p.next.prev = p.prev;
  21461. p.prev.next = p.next;
  21462. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21463. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21464. }
  21465. function Node( i, x, y ) {
  21466. // vertex index in coordinates array
  21467. this.i = i;
  21468. // vertex coordinates
  21469. this.x = x;
  21470. this.y = y;
  21471. // previous and next vertex nodes in a polygon ring
  21472. this.prev = null;
  21473. this.next = null;
  21474. // z-order curve value
  21475. this.z = 0;
  21476. // previous and next nodes in z-order
  21477. this.prevZ = null;
  21478. this.nextZ = null;
  21479. // indicates whether this is a steiner point
  21480. this.steiner = false;
  21481. }
  21482. function signedArea( data, start, end, dim ) {
  21483. let sum = 0;
  21484. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21485. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21486. j = i;
  21487. }
  21488. return sum;
  21489. }
  21490. class ShapeUtils {
  21491. // calculate area of the contour polygon
  21492. static area( contour ) {
  21493. const n = contour.length;
  21494. let a = 0.0;
  21495. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21496. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21497. }
  21498. return a * 0.5;
  21499. }
  21500. static isClockWise( pts ) {
  21501. return ShapeUtils.area( pts ) < 0;
  21502. }
  21503. static triangulateShape( contour, holes ) {
  21504. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21505. const holeIndices = []; // array of hole indices
  21506. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21507. removeDupEndPts( contour );
  21508. addContour( vertices, contour );
  21509. //
  21510. let holeIndex = contour.length;
  21511. holes.forEach( removeDupEndPts );
  21512. for ( let i = 0; i < holes.length; i ++ ) {
  21513. holeIndices.push( holeIndex );
  21514. holeIndex += holes[ i ].length;
  21515. addContour( vertices, holes[ i ] );
  21516. }
  21517. //
  21518. const triangles = Earcut.triangulate( vertices, holeIndices );
  21519. //
  21520. for ( let i = 0; i < triangles.length; i += 3 ) {
  21521. faces.push( triangles.slice( i, i + 3 ) );
  21522. }
  21523. return faces;
  21524. }
  21525. }
  21526. function removeDupEndPts( points ) {
  21527. const l = points.length;
  21528. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21529. points.pop();
  21530. }
  21531. }
  21532. function addContour( vertices, contour ) {
  21533. for ( let i = 0; i < contour.length; i ++ ) {
  21534. vertices.push( contour[ i ].x );
  21535. vertices.push( contour[ i ].y );
  21536. }
  21537. }
  21538. /**
  21539. * Creates extruded geometry from a path shape.
  21540. *
  21541. * parameters = {
  21542. *
  21543. * curveSegments: <int>, // number of points on the curves
  21544. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21545. * depth: <float>, // Depth to extrude the shape
  21546. *
  21547. * bevelEnabled: <bool>, // turn on bevel
  21548. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21549. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21550. * bevelOffset: <float>, // how far from shape outline does bevel start
  21551. * bevelSegments: <int>, // number of bevel layers
  21552. *
  21553. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21554. *
  21555. * UVGenerator: <Object> // object that provides UV generator functions
  21556. *
  21557. * }
  21558. */
  21559. class ExtrudeGeometry extends BufferGeometry {
  21560. 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 = {} ) {
  21561. super();
  21562. this.type = 'ExtrudeGeometry';
  21563. this.parameters = {
  21564. shapes: shapes,
  21565. options: options
  21566. };
  21567. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21568. const scope = this;
  21569. const verticesArray = [];
  21570. const uvArray = [];
  21571. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21572. const shape = shapes[ i ];
  21573. addShape( shape );
  21574. }
  21575. // build geometry
  21576. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21577. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21578. this.computeVertexNormals();
  21579. // functions
  21580. function addShape( shape ) {
  21581. const placeholder = [];
  21582. // options
  21583. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21584. const steps = options.steps !== undefined ? options.steps : 1;
  21585. const depth = options.depth !== undefined ? options.depth : 1;
  21586. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21587. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21588. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21589. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21590. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21591. const extrudePath = options.extrudePath;
  21592. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21593. //
  21594. let extrudePts, extrudeByPath = false;
  21595. let splineTube, binormal, normal, position2;
  21596. if ( extrudePath ) {
  21597. extrudePts = extrudePath.getSpacedPoints( steps );
  21598. extrudeByPath = true;
  21599. bevelEnabled = false; // bevels not supported for path extrusion
  21600. // SETUP TNB variables
  21601. // TODO1 - have a .isClosed in spline?
  21602. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21603. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21604. binormal = new Vector3();
  21605. normal = new Vector3();
  21606. position2 = new Vector3();
  21607. }
  21608. // Safeguards if bevels are not enabled
  21609. if ( ! bevelEnabled ) {
  21610. bevelSegments = 0;
  21611. bevelThickness = 0;
  21612. bevelSize = 0;
  21613. bevelOffset = 0;
  21614. }
  21615. // Variables initialization
  21616. const shapePoints = shape.extractPoints( curveSegments );
  21617. let vertices = shapePoints.shape;
  21618. const holes = shapePoints.holes;
  21619. const reverse = ! ShapeUtils.isClockWise( vertices );
  21620. if ( reverse ) {
  21621. vertices = vertices.reverse();
  21622. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21623. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21624. const ahole = holes[ h ];
  21625. if ( ShapeUtils.isClockWise( ahole ) ) {
  21626. holes[ h ] = ahole.reverse();
  21627. }
  21628. }
  21629. }
  21630. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21631. /* Vertices */
  21632. const contour = vertices; // vertices has all points but contour has only points of circumference
  21633. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21634. const ahole = holes[ h ];
  21635. vertices = vertices.concat( ahole );
  21636. }
  21637. function scalePt2( pt, vec, size ) {
  21638. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21639. return pt.clone().addScaledVector( vec, size );
  21640. }
  21641. const vlen = vertices.length, flen = faces.length;
  21642. // Find directions for point movement
  21643. function getBevelVec( inPt, inPrev, inNext ) {
  21644. // computes for inPt the corresponding point inPt' on a new contour
  21645. // shifted by 1 unit (length of normalized vector) to the left
  21646. // if we walk along contour clockwise, this new contour is outside the old one
  21647. //
  21648. // inPt' is the intersection of the two lines parallel to the two
  21649. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21650. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21651. // good reading for geometry algorithms (here: line-line intersection)
  21652. // http://geomalgorithms.com/a05-_intersect-1.html
  21653. const v_prev_x = inPt.x - inPrev.x,
  21654. v_prev_y = inPt.y - inPrev.y;
  21655. const v_next_x = inNext.x - inPt.x,
  21656. v_next_y = inNext.y - inPt.y;
  21657. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21658. // check for collinear edges
  21659. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21660. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21661. // not collinear
  21662. // length of vectors for normalizing
  21663. const v_prev_len = Math.sqrt( v_prev_lensq );
  21664. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21665. // shift adjacent points by unit vectors to the left
  21666. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21667. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21668. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21669. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21670. // scaling factor for v_prev to intersection point
  21671. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21672. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21673. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21674. // vector from inPt to intersection point
  21675. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21676. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21677. // Don't normalize!, otherwise sharp corners become ugly
  21678. // but prevent crazy spikes
  21679. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21680. if ( v_trans_lensq <= 2 ) {
  21681. return new Vector2( v_trans_x, v_trans_y );
  21682. } else {
  21683. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21684. }
  21685. } else {
  21686. // handle special case of collinear edges
  21687. let direction_eq = false; // assumes: opposite
  21688. if ( v_prev_x > Number.EPSILON ) {
  21689. if ( v_next_x > Number.EPSILON ) {
  21690. direction_eq = true;
  21691. }
  21692. } else {
  21693. if ( v_prev_x < - Number.EPSILON ) {
  21694. if ( v_next_x < - Number.EPSILON ) {
  21695. direction_eq = true;
  21696. }
  21697. } else {
  21698. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21699. direction_eq = true;
  21700. }
  21701. }
  21702. }
  21703. if ( direction_eq ) {
  21704. // console.log("Warning: lines are a straight sequence");
  21705. v_trans_x = - v_prev_y;
  21706. v_trans_y = v_prev_x;
  21707. shrink_by = Math.sqrt( v_prev_lensq );
  21708. } else {
  21709. // console.log("Warning: lines are a straight spike");
  21710. v_trans_x = v_prev_x;
  21711. v_trans_y = v_prev_y;
  21712. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21713. }
  21714. }
  21715. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21716. }
  21717. const contourMovements = [];
  21718. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21719. if ( j === il ) j = 0;
  21720. if ( k === il ) k = 0;
  21721. // (j)---(i)---(k)
  21722. // console.log('i,j,k', i, j , k)
  21723. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21724. }
  21725. const holesMovements = [];
  21726. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21727. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21728. const ahole = holes[ h ];
  21729. oneHoleMovements = [];
  21730. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21731. if ( j === il ) j = 0;
  21732. if ( k === il ) k = 0;
  21733. // (j)---(i)---(k)
  21734. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21735. }
  21736. holesMovements.push( oneHoleMovements );
  21737. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21738. }
  21739. // Loop bevelSegments, 1 for the front, 1 for the back
  21740. for ( let b = 0; b < bevelSegments; b ++ ) {
  21741. //for ( b = bevelSegments; b > 0; b -- ) {
  21742. const t = b / bevelSegments;
  21743. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21744. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21745. // contract shape
  21746. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21747. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21748. v( vert.x, vert.y, - z );
  21749. }
  21750. // expand holes
  21751. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21752. const ahole = holes[ h ];
  21753. oneHoleMovements = holesMovements[ h ];
  21754. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21755. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21756. v( vert.x, vert.y, - z );
  21757. }
  21758. }
  21759. }
  21760. const bs = bevelSize + bevelOffset;
  21761. // Back facing vertices
  21762. for ( let i = 0; i < vlen; i ++ ) {
  21763. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21764. if ( ! extrudeByPath ) {
  21765. v( vert.x, vert.y, 0 );
  21766. } else {
  21767. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21768. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21769. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21770. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21771. v( position2.x, position2.y, position2.z );
  21772. }
  21773. }
  21774. // Add stepped vertices...
  21775. // Including front facing vertices
  21776. for ( let s = 1; s <= steps; s ++ ) {
  21777. for ( let i = 0; i < vlen; i ++ ) {
  21778. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21779. if ( ! extrudeByPath ) {
  21780. v( vert.x, vert.y, depth / steps * s );
  21781. } else {
  21782. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21783. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21784. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21785. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21786. v( position2.x, position2.y, position2.z );
  21787. }
  21788. }
  21789. }
  21790. // Add bevel segments planes
  21791. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21792. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21793. const t = b / bevelSegments;
  21794. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21795. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21796. // contract shape
  21797. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21798. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21799. v( vert.x, vert.y, depth + z );
  21800. }
  21801. // expand holes
  21802. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21803. const ahole = holes[ h ];
  21804. oneHoleMovements = holesMovements[ h ];
  21805. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21806. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21807. if ( ! extrudeByPath ) {
  21808. v( vert.x, vert.y, depth + z );
  21809. } else {
  21810. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21811. }
  21812. }
  21813. }
  21814. }
  21815. /* Faces */
  21816. // Top and bottom faces
  21817. buildLidFaces();
  21818. // Sides faces
  21819. buildSideFaces();
  21820. ///// Internal functions
  21821. function buildLidFaces() {
  21822. const start = verticesArray.length / 3;
  21823. if ( bevelEnabled ) {
  21824. let layer = 0; // steps + 1
  21825. let offset = vlen * layer;
  21826. // Bottom faces
  21827. for ( let i = 0; i < flen; i ++ ) {
  21828. const face = faces[ i ];
  21829. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21830. }
  21831. layer = steps + bevelSegments * 2;
  21832. offset = vlen * layer;
  21833. // Top faces
  21834. for ( let i = 0; i < flen; i ++ ) {
  21835. const face = faces[ i ];
  21836. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21837. }
  21838. } else {
  21839. // Bottom faces
  21840. for ( let i = 0; i < flen; i ++ ) {
  21841. const face = faces[ i ];
  21842. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21843. }
  21844. // Top faces
  21845. for ( let i = 0; i < flen; i ++ ) {
  21846. const face = faces[ i ];
  21847. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21848. }
  21849. }
  21850. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21851. }
  21852. // Create faces for the z-sides of the shape
  21853. function buildSideFaces() {
  21854. const start = verticesArray.length / 3;
  21855. let layeroffset = 0;
  21856. sidewalls( contour, layeroffset );
  21857. layeroffset += contour.length;
  21858. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21859. const ahole = holes[ h ];
  21860. sidewalls( ahole, layeroffset );
  21861. //, true
  21862. layeroffset += ahole.length;
  21863. }
  21864. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21865. }
  21866. function sidewalls( contour, layeroffset ) {
  21867. let i = contour.length;
  21868. while ( -- i >= 0 ) {
  21869. const j = i;
  21870. let k = i - 1;
  21871. if ( k < 0 ) k = contour.length - 1;
  21872. //console.log('b', i,j, i-1, k,vertices.length);
  21873. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21874. const slen1 = vlen * s;
  21875. const slen2 = vlen * ( s + 1 );
  21876. const a = layeroffset + j + slen1,
  21877. b = layeroffset + k + slen1,
  21878. c = layeroffset + k + slen2,
  21879. d = layeroffset + j + slen2;
  21880. f4( a, b, c, d );
  21881. }
  21882. }
  21883. }
  21884. function v( x, y, z ) {
  21885. placeholder.push( x );
  21886. placeholder.push( y );
  21887. placeholder.push( z );
  21888. }
  21889. function f3( a, b, c ) {
  21890. addVertex( a );
  21891. addVertex( b );
  21892. addVertex( c );
  21893. const nextIndex = verticesArray.length / 3;
  21894. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21895. addUV( uvs[ 0 ] );
  21896. addUV( uvs[ 1 ] );
  21897. addUV( uvs[ 2 ] );
  21898. }
  21899. function f4( a, b, c, d ) {
  21900. addVertex( a );
  21901. addVertex( b );
  21902. addVertex( d );
  21903. addVertex( b );
  21904. addVertex( c );
  21905. addVertex( d );
  21906. const nextIndex = verticesArray.length / 3;
  21907. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21908. addUV( uvs[ 0 ] );
  21909. addUV( uvs[ 1 ] );
  21910. addUV( uvs[ 3 ] );
  21911. addUV( uvs[ 1 ] );
  21912. addUV( uvs[ 2 ] );
  21913. addUV( uvs[ 3 ] );
  21914. }
  21915. function addVertex( index ) {
  21916. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21917. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21918. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21919. }
  21920. function addUV( vector2 ) {
  21921. uvArray.push( vector2.x );
  21922. uvArray.push( vector2.y );
  21923. }
  21924. }
  21925. }
  21926. copy( source ) {
  21927. super.copy( source );
  21928. this.parameters = Object.assign( {}, source.parameters );
  21929. return this;
  21930. }
  21931. toJSON() {
  21932. const data = super.toJSON();
  21933. const shapes = this.parameters.shapes;
  21934. const options = this.parameters.options;
  21935. return toJSON$1( shapes, options, data );
  21936. }
  21937. static fromJSON( data, shapes ) {
  21938. const geometryShapes = [];
  21939. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21940. const shape = shapes[ data.shapes[ j ] ];
  21941. geometryShapes.push( shape );
  21942. }
  21943. const extrudePath = data.options.extrudePath;
  21944. if ( extrudePath !== undefined ) {
  21945. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21946. }
  21947. return new ExtrudeGeometry( geometryShapes, data.options );
  21948. }
  21949. }
  21950. const WorldUVGenerator = {
  21951. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21952. const a_x = vertices[ indexA * 3 ];
  21953. const a_y = vertices[ indexA * 3 + 1 ];
  21954. const b_x = vertices[ indexB * 3 ];
  21955. const b_y = vertices[ indexB * 3 + 1 ];
  21956. const c_x = vertices[ indexC * 3 ];
  21957. const c_y = vertices[ indexC * 3 + 1 ];
  21958. return [
  21959. new Vector2( a_x, a_y ),
  21960. new Vector2( b_x, b_y ),
  21961. new Vector2( c_x, c_y )
  21962. ];
  21963. },
  21964. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21965. const a_x = vertices[ indexA * 3 ];
  21966. const a_y = vertices[ indexA * 3 + 1 ];
  21967. const a_z = vertices[ indexA * 3 + 2 ];
  21968. const b_x = vertices[ indexB * 3 ];
  21969. const b_y = vertices[ indexB * 3 + 1 ];
  21970. const b_z = vertices[ indexB * 3 + 2 ];
  21971. const c_x = vertices[ indexC * 3 ];
  21972. const c_y = vertices[ indexC * 3 + 1 ];
  21973. const c_z = vertices[ indexC * 3 + 2 ];
  21974. const d_x = vertices[ indexD * 3 ];
  21975. const d_y = vertices[ indexD * 3 + 1 ];
  21976. const d_z = vertices[ indexD * 3 + 2 ];
  21977. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21978. return [
  21979. new Vector2( a_x, 1 - a_z ),
  21980. new Vector2( b_x, 1 - b_z ),
  21981. new Vector2( c_x, 1 - c_z ),
  21982. new Vector2( d_x, 1 - d_z )
  21983. ];
  21984. } else {
  21985. return [
  21986. new Vector2( a_y, 1 - a_z ),
  21987. new Vector2( b_y, 1 - b_z ),
  21988. new Vector2( c_y, 1 - c_z ),
  21989. new Vector2( d_y, 1 - d_z )
  21990. ];
  21991. }
  21992. }
  21993. };
  21994. function toJSON$1( shapes, options, data ) {
  21995. data.shapes = [];
  21996. if ( Array.isArray( shapes ) ) {
  21997. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21998. const shape = shapes[ i ];
  21999. data.shapes.push( shape.uuid );
  22000. }
  22001. } else {
  22002. data.shapes.push( shapes.uuid );
  22003. }
  22004. data.options = Object.assign( {}, options );
  22005. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  22006. return data;
  22007. }
  22008. class IcosahedronGeometry extends PolyhedronGeometry {
  22009. constructor( radius = 1, detail = 0 ) {
  22010. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22011. const vertices = [
  22012. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22013. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22014. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22015. ];
  22016. const indices = [
  22017. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22018. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22019. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22020. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22021. ];
  22022. super( vertices, indices, radius, detail );
  22023. this.type = 'IcosahedronGeometry';
  22024. this.parameters = {
  22025. radius: radius,
  22026. detail: detail
  22027. };
  22028. }
  22029. static fromJSON( data ) {
  22030. return new IcosahedronGeometry( data.radius, data.detail );
  22031. }
  22032. }
  22033. class OctahedronGeometry extends PolyhedronGeometry {
  22034. constructor( radius = 1, detail = 0 ) {
  22035. const vertices = [
  22036. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  22037. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22038. ];
  22039. const indices = [
  22040. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  22041. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  22042. 1, 3, 4, 1, 4, 2
  22043. ];
  22044. super( vertices, indices, radius, detail );
  22045. this.type = 'OctahedronGeometry';
  22046. this.parameters = {
  22047. radius: radius,
  22048. detail: detail
  22049. };
  22050. }
  22051. static fromJSON( data ) {
  22052. return new OctahedronGeometry( data.radius, data.detail );
  22053. }
  22054. }
  22055. class RingGeometry extends BufferGeometry {
  22056. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22057. super();
  22058. this.type = 'RingGeometry';
  22059. this.parameters = {
  22060. innerRadius: innerRadius,
  22061. outerRadius: outerRadius,
  22062. thetaSegments: thetaSegments,
  22063. phiSegments: phiSegments,
  22064. thetaStart: thetaStart,
  22065. thetaLength: thetaLength
  22066. };
  22067. thetaSegments = Math.max( 3, thetaSegments );
  22068. phiSegments = Math.max( 1, phiSegments );
  22069. // buffers
  22070. const indices = [];
  22071. const vertices = [];
  22072. const normals = [];
  22073. const uvs = [];
  22074. // some helper variables
  22075. let radius = innerRadius;
  22076. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22077. const vertex = new Vector3();
  22078. const uv = new Vector2();
  22079. // generate vertices, normals and uvs
  22080. for ( let j = 0; j <= phiSegments; j ++ ) {
  22081. for ( let i = 0; i <= thetaSegments; i ++ ) {
  22082. // values are generate from the inside of the ring to the outside
  22083. const segment = thetaStart + i / thetaSegments * thetaLength;
  22084. // vertex
  22085. vertex.x = radius * Math.cos( segment );
  22086. vertex.y = radius * Math.sin( segment );
  22087. vertices.push( vertex.x, vertex.y, vertex.z );
  22088. // normal
  22089. normals.push( 0, 0, 1 );
  22090. // uv
  22091. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22092. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22093. uvs.push( uv.x, uv.y );
  22094. }
  22095. // increase the radius for next row of vertices
  22096. radius += radiusStep;
  22097. }
  22098. // indices
  22099. for ( let j = 0; j < phiSegments; j ++ ) {
  22100. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  22101. for ( let i = 0; i < thetaSegments; i ++ ) {
  22102. const segment = i + thetaSegmentLevel;
  22103. const a = segment;
  22104. const b = segment + thetaSegments + 1;
  22105. const c = segment + thetaSegments + 2;
  22106. const d = segment + 1;
  22107. // faces
  22108. indices.push( a, b, d );
  22109. indices.push( b, c, d );
  22110. }
  22111. }
  22112. // build geometry
  22113. this.setIndex( indices );
  22114. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22115. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22116. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22117. }
  22118. copy( source ) {
  22119. super.copy( source );
  22120. this.parameters = Object.assign( {}, source.parameters );
  22121. return this;
  22122. }
  22123. static fromJSON( data ) {
  22124. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  22125. }
  22126. }
  22127. class ShapeGeometry extends BufferGeometry {
  22128. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  22129. super();
  22130. this.type = 'ShapeGeometry';
  22131. this.parameters = {
  22132. shapes: shapes,
  22133. curveSegments: curveSegments
  22134. };
  22135. // buffers
  22136. const indices = [];
  22137. const vertices = [];
  22138. const normals = [];
  22139. const uvs = [];
  22140. // helper variables
  22141. let groupStart = 0;
  22142. let groupCount = 0;
  22143. // allow single and array values for "shapes" parameter
  22144. if ( Array.isArray( shapes ) === false ) {
  22145. addShape( shapes );
  22146. } else {
  22147. for ( let i = 0; i < shapes.length; i ++ ) {
  22148. addShape( shapes[ i ] );
  22149. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  22150. groupStart += groupCount;
  22151. groupCount = 0;
  22152. }
  22153. }
  22154. // build geometry
  22155. this.setIndex( indices );
  22156. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22157. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22158. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22159. // helper functions
  22160. function addShape( shape ) {
  22161. const indexOffset = vertices.length / 3;
  22162. const points = shape.extractPoints( curveSegments );
  22163. let shapeVertices = points.shape;
  22164. const shapeHoles = points.holes;
  22165. // check direction of vertices
  22166. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  22167. shapeVertices = shapeVertices.reverse();
  22168. }
  22169. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22170. const shapeHole = shapeHoles[ i ];
  22171. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  22172. shapeHoles[ i ] = shapeHole.reverse();
  22173. }
  22174. }
  22175. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  22176. // join vertices of inner and outer paths to a single array
  22177. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22178. const shapeHole = shapeHoles[ i ];
  22179. shapeVertices = shapeVertices.concat( shapeHole );
  22180. }
  22181. // vertices, normals, uvs
  22182. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  22183. const vertex = shapeVertices[ i ];
  22184. vertices.push( vertex.x, vertex.y, 0 );
  22185. normals.push( 0, 0, 1 );
  22186. uvs.push( vertex.x, vertex.y ); // world uvs
  22187. }
  22188. // indices
  22189. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  22190. const face = faces[ i ];
  22191. const a = face[ 0 ] + indexOffset;
  22192. const b = face[ 1 ] + indexOffset;
  22193. const c = face[ 2 ] + indexOffset;
  22194. indices.push( a, b, c );
  22195. groupCount += 3;
  22196. }
  22197. }
  22198. }
  22199. copy( source ) {
  22200. super.copy( source );
  22201. this.parameters = Object.assign( {}, source.parameters );
  22202. return this;
  22203. }
  22204. toJSON() {
  22205. const data = super.toJSON();
  22206. const shapes = this.parameters.shapes;
  22207. return toJSON( shapes, data );
  22208. }
  22209. static fromJSON( data, shapes ) {
  22210. const geometryShapes = [];
  22211. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22212. const shape = shapes[ data.shapes[ j ] ];
  22213. geometryShapes.push( shape );
  22214. }
  22215. return new ShapeGeometry( geometryShapes, data.curveSegments );
  22216. }
  22217. }
  22218. function toJSON( shapes, data ) {
  22219. data.shapes = [];
  22220. if ( Array.isArray( shapes ) ) {
  22221. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22222. const shape = shapes[ i ];
  22223. data.shapes.push( shape.uuid );
  22224. }
  22225. } else {
  22226. data.shapes.push( shapes.uuid );
  22227. }
  22228. return data;
  22229. }
  22230. class SphereGeometry extends BufferGeometry {
  22231. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  22232. super();
  22233. this.type = 'SphereGeometry';
  22234. this.parameters = {
  22235. radius: radius,
  22236. widthSegments: widthSegments,
  22237. heightSegments: heightSegments,
  22238. phiStart: phiStart,
  22239. phiLength: phiLength,
  22240. thetaStart: thetaStart,
  22241. thetaLength: thetaLength
  22242. };
  22243. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  22244. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  22245. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22246. let index = 0;
  22247. const grid = [];
  22248. const vertex = new Vector3();
  22249. const normal = new Vector3();
  22250. // buffers
  22251. const indices = [];
  22252. const vertices = [];
  22253. const normals = [];
  22254. const uvs = [];
  22255. // generate vertices, normals and uvs
  22256. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22257. const verticesRow = [];
  22258. const v = iy / heightSegments;
  22259. // special case for the poles
  22260. let uOffset = 0;
  22261. if ( iy === 0 && thetaStart === 0 ) {
  22262. uOffset = 0.5 / widthSegments;
  22263. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22264. uOffset = - 0.5 / widthSegments;
  22265. }
  22266. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22267. const u = ix / widthSegments;
  22268. // vertex
  22269. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22270. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22271. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22272. vertices.push( vertex.x, vertex.y, vertex.z );
  22273. // normal
  22274. normal.copy( vertex ).normalize();
  22275. normals.push( normal.x, normal.y, normal.z );
  22276. // uv
  22277. uvs.push( u + uOffset, 1 - v );
  22278. verticesRow.push( index ++ );
  22279. }
  22280. grid.push( verticesRow );
  22281. }
  22282. // indices
  22283. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22284. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22285. const a = grid[ iy ][ ix + 1 ];
  22286. const b = grid[ iy ][ ix ];
  22287. const c = grid[ iy + 1 ][ ix ];
  22288. const d = grid[ iy + 1 ][ ix + 1 ];
  22289. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22290. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22291. }
  22292. }
  22293. // build geometry
  22294. this.setIndex( indices );
  22295. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22296. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22297. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22298. }
  22299. copy( source ) {
  22300. super.copy( source );
  22301. this.parameters = Object.assign( {}, source.parameters );
  22302. return this;
  22303. }
  22304. static fromJSON( data ) {
  22305. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22306. }
  22307. }
  22308. class TetrahedronGeometry extends PolyhedronGeometry {
  22309. constructor( radius = 1, detail = 0 ) {
  22310. const vertices = [
  22311. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22312. ];
  22313. const indices = [
  22314. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22315. ];
  22316. super( vertices, indices, radius, detail );
  22317. this.type = 'TetrahedronGeometry';
  22318. this.parameters = {
  22319. radius: radius,
  22320. detail: detail
  22321. };
  22322. }
  22323. static fromJSON( data ) {
  22324. return new TetrahedronGeometry( data.radius, data.detail );
  22325. }
  22326. }
  22327. class TorusGeometry extends BufferGeometry {
  22328. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22329. super();
  22330. this.type = 'TorusGeometry';
  22331. this.parameters = {
  22332. radius: radius,
  22333. tube: tube,
  22334. radialSegments: radialSegments,
  22335. tubularSegments: tubularSegments,
  22336. arc: arc
  22337. };
  22338. radialSegments = Math.floor( radialSegments );
  22339. tubularSegments = Math.floor( tubularSegments );
  22340. // buffers
  22341. const indices = [];
  22342. const vertices = [];
  22343. const normals = [];
  22344. const uvs = [];
  22345. // helper variables
  22346. const center = new Vector3();
  22347. const vertex = new Vector3();
  22348. const normal = new Vector3();
  22349. // generate vertices, normals and uvs
  22350. for ( let j = 0; j <= radialSegments; j ++ ) {
  22351. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22352. const u = i / tubularSegments * arc;
  22353. const v = j / radialSegments * Math.PI * 2;
  22354. // vertex
  22355. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22356. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22357. vertex.z = tube * Math.sin( v );
  22358. vertices.push( vertex.x, vertex.y, vertex.z );
  22359. // normal
  22360. center.x = radius * Math.cos( u );
  22361. center.y = radius * Math.sin( u );
  22362. normal.subVectors( vertex, center ).normalize();
  22363. normals.push( normal.x, normal.y, normal.z );
  22364. // uv
  22365. uvs.push( i / tubularSegments );
  22366. uvs.push( j / radialSegments );
  22367. }
  22368. }
  22369. // generate indices
  22370. for ( let j = 1; j <= radialSegments; j ++ ) {
  22371. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22372. // indices
  22373. const a = ( tubularSegments + 1 ) * j + i - 1;
  22374. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22375. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22376. const d = ( tubularSegments + 1 ) * j + i;
  22377. // faces
  22378. indices.push( a, b, d );
  22379. indices.push( b, c, d );
  22380. }
  22381. }
  22382. // build geometry
  22383. this.setIndex( indices );
  22384. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22385. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22386. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22387. }
  22388. copy( source ) {
  22389. super.copy( source );
  22390. this.parameters = Object.assign( {}, source.parameters );
  22391. return this;
  22392. }
  22393. static fromJSON( data ) {
  22394. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22395. }
  22396. }
  22397. class TorusKnotGeometry extends BufferGeometry {
  22398. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22399. super();
  22400. this.type = 'TorusKnotGeometry';
  22401. this.parameters = {
  22402. radius: radius,
  22403. tube: tube,
  22404. tubularSegments: tubularSegments,
  22405. radialSegments: radialSegments,
  22406. p: p,
  22407. q: q
  22408. };
  22409. tubularSegments = Math.floor( tubularSegments );
  22410. radialSegments = Math.floor( radialSegments );
  22411. // buffers
  22412. const indices = [];
  22413. const vertices = [];
  22414. const normals = [];
  22415. const uvs = [];
  22416. // helper variables
  22417. const vertex = new Vector3();
  22418. const normal = new Vector3();
  22419. const P1 = new Vector3();
  22420. const P2 = new Vector3();
  22421. const B = new Vector3();
  22422. const T = new Vector3();
  22423. const N = new Vector3();
  22424. // generate vertices, normals and uvs
  22425. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22426. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22427. const u = i / tubularSegments * p * Math.PI * 2;
  22428. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22429. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22430. calculatePositionOnCurve( u, p, q, radius, P1 );
  22431. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22432. // calculate orthonormal basis
  22433. T.subVectors( P2, P1 );
  22434. N.addVectors( P2, P1 );
  22435. B.crossVectors( T, N );
  22436. N.crossVectors( B, T );
  22437. // normalize B, N. T can be ignored, we don't use it
  22438. B.normalize();
  22439. N.normalize();
  22440. for ( let j = 0; j <= radialSegments; ++ j ) {
  22441. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22442. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22443. const v = j / radialSegments * Math.PI * 2;
  22444. const cx = - tube * Math.cos( v );
  22445. const cy = tube * Math.sin( v );
  22446. // now calculate the final vertex position.
  22447. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22448. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22449. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22450. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22451. vertices.push( vertex.x, vertex.y, vertex.z );
  22452. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22453. normal.subVectors( vertex, P1 ).normalize();
  22454. normals.push( normal.x, normal.y, normal.z );
  22455. // uv
  22456. uvs.push( i / tubularSegments );
  22457. uvs.push( j / radialSegments );
  22458. }
  22459. }
  22460. // generate indices
  22461. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22462. for ( let i = 1; i <= radialSegments; i ++ ) {
  22463. // indices
  22464. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22465. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22466. const c = ( radialSegments + 1 ) * j + i;
  22467. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22468. // faces
  22469. indices.push( a, b, d );
  22470. indices.push( b, c, d );
  22471. }
  22472. }
  22473. // build geometry
  22474. this.setIndex( indices );
  22475. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22476. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22477. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22478. // this function calculates the current position on the torus curve
  22479. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22480. const cu = Math.cos( u );
  22481. const su = Math.sin( u );
  22482. const quOverP = q / p * u;
  22483. const cs = Math.cos( quOverP );
  22484. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22485. position.y = radius * ( 2 + cs ) * su * 0.5;
  22486. position.z = radius * Math.sin( quOverP ) * 0.5;
  22487. }
  22488. }
  22489. copy( source ) {
  22490. super.copy( source );
  22491. this.parameters = Object.assign( {}, source.parameters );
  22492. return this;
  22493. }
  22494. static fromJSON( data ) {
  22495. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22496. }
  22497. }
  22498. class TubeGeometry extends BufferGeometry {
  22499. 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 ) {
  22500. super();
  22501. this.type = 'TubeGeometry';
  22502. this.parameters = {
  22503. path: path,
  22504. tubularSegments: tubularSegments,
  22505. radius: radius,
  22506. radialSegments: radialSegments,
  22507. closed: closed
  22508. };
  22509. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22510. // expose internals
  22511. this.tangents = frames.tangents;
  22512. this.normals = frames.normals;
  22513. this.binormals = frames.binormals;
  22514. // helper variables
  22515. const vertex = new Vector3();
  22516. const normal = new Vector3();
  22517. const uv = new Vector2();
  22518. let P = new Vector3();
  22519. // buffer
  22520. const vertices = [];
  22521. const normals = [];
  22522. const uvs = [];
  22523. const indices = [];
  22524. // create buffer data
  22525. generateBufferData();
  22526. // build geometry
  22527. this.setIndex( indices );
  22528. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22529. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22530. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22531. // functions
  22532. function generateBufferData() {
  22533. for ( let i = 0; i < tubularSegments; i ++ ) {
  22534. generateSegment( i );
  22535. }
  22536. // if the geometry is not closed, generate the last row of vertices and normals
  22537. // at the regular position on the given path
  22538. //
  22539. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22540. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22541. // uvs are generated in a separate function.
  22542. // this makes it easy compute correct values for closed geometries
  22543. generateUVs();
  22544. // finally create faces
  22545. generateIndices();
  22546. }
  22547. function generateSegment( i ) {
  22548. // we use getPointAt to sample evenly distributed points from the given path
  22549. P = path.getPointAt( i / tubularSegments, P );
  22550. // retrieve corresponding normal and binormal
  22551. const N = frames.normals[ i ];
  22552. const B = frames.binormals[ i ];
  22553. // generate normals and vertices for the current segment
  22554. for ( let j = 0; j <= radialSegments; j ++ ) {
  22555. const v = j / radialSegments * Math.PI * 2;
  22556. const sin = Math.sin( v );
  22557. const cos = - Math.cos( v );
  22558. // normal
  22559. normal.x = ( cos * N.x + sin * B.x );
  22560. normal.y = ( cos * N.y + sin * B.y );
  22561. normal.z = ( cos * N.z + sin * B.z );
  22562. normal.normalize();
  22563. normals.push( normal.x, normal.y, normal.z );
  22564. // vertex
  22565. vertex.x = P.x + radius * normal.x;
  22566. vertex.y = P.y + radius * normal.y;
  22567. vertex.z = P.z + radius * normal.z;
  22568. vertices.push( vertex.x, vertex.y, vertex.z );
  22569. }
  22570. }
  22571. function generateIndices() {
  22572. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22573. for ( let i = 1; i <= radialSegments; i ++ ) {
  22574. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22575. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22576. const c = ( radialSegments + 1 ) * j + i;
  22577. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22578. // faces
  22579. indices.push( a, b, d );
  22580. indices.push( b, c, d );
  22581. }
  22582. }
  22583. }
  22584. function generateUVs() {
  22585. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22586. for ( let j = 0; j <= radialSegments; j ++ ) {
  22587. uv.x = i / tubularSegments;
  22588. uv.y = j / radialSegments;
  22589. uvs.push( uv.x, uv.y );
  22590. }
  22591. }
  22592. }
  22593. }
  22594. copy( source ) {
  22595. super.copy( source );
  22596. this.parameters = Object.assign( {}, source.parameters );
  22597. return this;
  22598. }
  22599. toJSON() {
  22600. const data = super.toJSON();
  22601. data.path = this.parameters.path.toJSON();
  22602. return data;
  22603. }
  22604. static fromJSON( data ) {
  22605. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22606. // User defined curves or instances of CurvePath will not be deserialized.
  22607. return new TubeGeometry(
  22608. new Curves[ data.path.type ]().fromJSON( data.path ),
  22609. data.tubularSegments,
  22610. data.radius,
  22611. data.radialSegments,
  22612. data.closed
  22613. );
  22614. }
  22615. }
  22616. class WireframeGeometry extends BufferGeometry {
  22617. constructor( geometry = null ) {
  22618. super();
  22619. this.type = 'WireframeGeometry';
  22620. this.parameters = {
  22621. geometry: geometry
  22622. };
  22623. if ( geometry !== null ) {
  22624. // buffer
  22625. const vertices = [];
  22626. const edges = new Set();
  22627. // helper variables
  22628. const start = new Vector3();
  22629. const end = new Vector3();
  22630. if ( geometry.index !== null ) {
  22631. // indexed BufferGeometry
  22632. const position = geometry.attributes.position;
  22633. const indices = geometry.index;
  22634. let groups = geometry.groups;
  22635. if ( groups.length === 0 ) {
  22636. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22637. }
  22638. // create a data structure that contains all edges without duplicates
  22639. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22640. const group = groups[ o ];
  22641. const groupStart = group.start;
  22642. const groupCount = group.count;
  22643. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22644. for ( let j = 0; j < 3; j ++ ) {
  22645. const index1 = indices.getX( i + j );
  22646. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22647. start.fromBufferAttribute( position, index1 );
  22648. end.fromBufferAttribute( position, index2 );
  22649. if ( isUniqueEdge( start, end, edges ) === true ) {
  22650. vertices.push( start.x, start.y, start.z );
  22651. vertices.push( end.x, end.y, end.z );
  22652. }
  22653. }
  22654. }
  22655. }
  22656. } else {
  22657. // non-indexed BufferGeometry
  22658. const position = geometry.attributes.position;
  22659. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22660. for ( let j = 0; j < 3; j ++ ) {
  22661. // three edges per triangle, an edge is represented as (index1, index2)
  22662. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22663. const index1 = 3 * i + j;
  22664. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22665. start.fromBufferAttribute( position, index1 );
  22666. end.fromBufferAttribute( position, index2 );
  22667. if ( isUniqueEdge( start, end, edges ) === true ) {
  22668. vertices.push( start.x, start.y, start.z );
  22669. vertices.push( end.x, end.y, end.z );
  22670. }
  22671. }
  22672. }
  22673. }
  22674. // build geometry
  22675. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22676. }
  22677. }
  22678. copy( source ) {
  22679. super.copy( source );
  22680. this.parameters = Object.assign( {}, source.parameters );
  22681. return this;
  22682. }
  22683. }
  22684. function isUniqueEdge( start, end, edges ) {
  22685. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22686. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22687. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22688. return false;
  22689. } else {
  22690. edges.add( hash1 );
  22691. edges.add( hash2 );
  22692. return true;
  22693. }
  22694. }
  22695. var Geometries = /*#__PURE__*/Object.freeze({
  22696. __proto__: null,
  22697. BoxGeometry: BoxGeometry,
  22698. CapsuleGeometry: CapsuleGeometry,
  22699. CircleGeometry: CircleGeometry,
  22700. ConeGeometry: ConeGeometry,
  22701. CylinderGeometry: CylinderGeometry,
  22702. DodecahedronGeometry: DodecahedronGeometry,
  22703. EdgesGeometry: EdgesGeometry,
  22704. ExtrudeGeometry: ExtrudeGeometry,
  22705. IcosahedronGeometry: IcosahedronGeometry,
  22706. LatheGeometry: LatheGeometry,
  22707. OctahedronGeometry: OctahedronGeometry,
  22708. PlaneGeometry: PlaneGeometry,
  22709. PolyhedronGeometry: PolyhedronGeometry,
  22710. RingGeometry: RingGeometry,
  22711. ShapeGeometry: ShapeGeometry,
  22712. SphereGeometry: SphereGeometry,
  22713. TetrahedronGeometry: TetrahedronGeometry,
  22714. TorusGeometry: TorusGeometry,
  22715. TorusKnotGeometry: TorusKnotGeometry,
  22716. TubeGeometry: TubeGeometry,
  22717. WireframeGeometry: WireframeGeometry
  22718. });
  22719. class ShadowMaterial extends Material {
  22720. constructor( parameters ) {
  22721. super();
  22722. this.isShadowMaterial = true;
  22723. this.type = 'ShadowMaterial';
  22724. this.color = new Color( 0x000000 );
  22725. this.transparent = true;
  22726. this.fog = true;
  22727. this.setValues( parameters );
  22728. }
  22729. copy( source ) {
  22730. super.copy( source );
  22731. this.color.copy( source.color );
  22732. this.fog = source.fog;
  22733. return this;
  22734. }
  22735. }
  22736. class RawShaderMaterial extends ShaderMaterial {
  22737. constructor( parameters ) {
  22738. super( parameters );
  22739. this.isRawShaderMaterial = true;
  22740. this.type = 'RawShaderMaterial';
  22741. }
  22742. }
  22743. class MeshStandardMaterial extends Material {
  22744. constructor( parameters ) {
  22745. super();
  22746. this.isMeshStandardMaterial = true;
  22747. this.defines = { 'STANDARD': '' };
  22748. this.type = 'MeshStandardMaterial';
  22749. this.color = new Color( 0xffffff ); // diffuse
  22750. this.roughness = 1.0;
  22751. this.metalness = 0.0;
  22752. this.map = null;
  22753. this.lightMap = null;
  22754. this.lightMapIntensity = 1.0;
  22755. this.aoMap = null;
  22756. this.aoMapIntensity = 1.0;
  22757. this.emissive = new Color( 0x000000 );
  22758. this.emissiveIntensity = 1.0;
  22759. this.emissiveMap = null;
  22760. this.bumpMap = null;
  22761. this.bumpScale = 1;
  22762. this.normalMap = null;
  22763. this.normalMapType = TangentSpaceNormalMap;
  22764. this.normalScale = new Vector2( 1, 1 );
  22765. this.displacementMap = null;
  22766. this.displacementScale = 1;
  22767. this.displacementBias = 0;
  22768. this.roughnessMap = null;
  22769. this.metalnessMap = null;
  22770. this.alphaMap = null;
  22771. this.envMap = null;
  22772. this.envMapIntensity = 1.0;
  22773. this.wireframe = false;
  22774. this.wireframeLinewidth = 1;
  22775. this.wireframeLinecap = 'round';
  22776. this.wireframeLinejoin = 'round';
  22777. this.flatShading = false;
  22778. this.fog = true;
  22779. this.setValues( parameters );
  22780. }
  22781. copy( source ) {
  22782. super.copy( source );
  22783. this.defines = { 'STANDARD': '' };
  22784. this.color.copy( source.color );
  22785. this.roughness = source.roughness;
  22786. this.metalness = source.metalness;
  22787. this.map = source.map;
  22788. this.lightMap = source.lightMap;
  22789. this.lightMapIntensity = source.lightMapIntensity;
  22790. this.aoMap = source.aoMap;
  22791. this.aoMapIntensity = source.aoMapIntensity;
  22792. this.emissive.copy( source.emissive );
  22793. this.emissiveMap = source.emissiveMap;
  22794. this.emissiveIntensity = source.emissiveIntensity;
  22795. this.bumpMap = source.bumpMap;
  22796. this.bumpScale = source.bumpScale;
  22797. this.normalMap = source.normalMap;
  22798. this.normalMapType = source.normalMapType;
  22799. this.normalScale.copy( source.normalScale );
  22800. this.displacementMap = source.displacementMap;
  22801. this.displacementScale = source.displacementScale;
  22802. this.displacementBias = source.displacementBias;
  22803. this.roughnessMap = source.roughnessMap;
  22804. this.metalnessMap = source.metalnessMap;
  22805. this.alphaMap = source.alphaMap;
  22806. this.envMap = source.envMap;
  22807. this.envMapIntensity = source.envMapIntensity;
  22808. this.wireframe = source.wireframe;
  22809. this.wireframeLinewidth = source.wireframeLinewidth;
  22810. this.wireframeLinecap = source.wireframeLinecap;
  22811. this.wireframeLinejoin = source.wireframeLinejoin;
  22812. this.flatShading = source.flatShading;
  22813. this.fog = source.fog;
  22814. return this;
  22815. }
  22816. }
  22817. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22818. constructor( parameters ) {
  22819. super();
  22820. this.isMeshPhysicalMaterial = true;
  22821. this.defines = {
  22822. 'STANDARD': '',
  22823. 'PHYSICAL': ''
  22824. };
  22825. this.type = 'MeshPhysicalMaterial';
  22826. this.clearcoatMap = null;
  22827. this.clearcoatRoughness = 0.0;
  22828. this.clearcoatRoughnessMap = null;
  22829. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22830. this.clearcoatNormalMap = null;
  22831. this.ior = 1.5;
  22832. Object.defineProperty( this, 'reflectivity', {
  22833. get: function () {
  22834. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22835. },
  22836. set: function ( reflectivity ) {
  22837. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22838. }
  22839. } );
  22840. this.iridescenceMap = null;
  22841. this.iridescenceIOR = 1.3;
  22842. this.iridescenceThicknessRange = [ 100, 400 ];
  22843. this.iridescenceThicknessMap = null;
  22844. this.sheenColor = new Color( 0x000000 );
  22845. this.sheenColorMap = null;
  22846. this.sheenRoughness = 1.0;
  22847. this.sheenRoughnessMap = null;
  22848. this.transmissionMap = null;
  22849. this.thickness = 0;
  22850. this.thicknessMap = null;
  22851. this.attenuationDistance = Infinity;
  22852. this.attenuationColor = new Color( 1, 1, 1 );
  22853. this.specularIntensity = 1.0;
  22854. this.specularIntensityMap = null;
  22855. this.specularColor = new Color( 1, 1, 1 );
  22856. this.specularColorMap = null;
  22857. this._sheen = 0.0;
  22858. this._clearcoat = 0;
  22859. this._iridescence = 0;
  22860. this._transmission = 0;
  22861. this.setValues( parameters );
  22862. }
  22863. get sheen() {
  22864. return this._sheen;
  22865. }
  22866. set sheen( value ) {
  22867. if ( this._sheen > 0 !== value > 0 ) {
  22868. this.version ++;
  22869. }
  22870. this._sheen = value;
  22871. }
  22872. get clearcoat() {
  22873. return this._clearcoat;
  22874. }
  22875. set clearcoat( value ) {
  22876. if ( this._clearcoat > 0 !== value > 0 ) {
  22877. this.version ++;
  22878. }
  22879. this._clearcoat = value;
  22880. }
  22881. get iridescence() {
  22882. return this._iridescence;
  22883. }
  22884. set iridescence( value ) {
  22885. if ( this._iridescence > 0 !== value > 0 ) {
  22886. this.version ++;
  22887. }
  22888. this._iridescence = value;
  22889. }
  22890. get transmission() {
  22891. return this._transmission;
  22892. }
  22893. set transmission( value ) {
  22894. if ( this._transmission > 0 !== value > 0 ) {
  22895. this.version ++;
  22896. }
  22897. this._transmission = value;
  22898. }
  22899. copy( source ) {
  22900. super.copy( source );
  22901. this.defines = {
  22902. 'STANDARD': '',
  22903. 'PHYSICAL': ''
  22904. };
  22905. this.clearcoat = source.clearcoat;
  22906. this.clearcoatMap = source.clearcoatMap;
  22907. this.clearcoatRoughness = source.clearcoatRoughness;
  22908. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22909. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22910. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22911. this.ior = source.ior;
  22912. this.iridescence = source.iridescence;
  22913. this.iridescenceMap = source.iridescenceMap;
  22914. this.iridescenceIOR = source.iridescenceIOR;
  22915. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22916. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22917. this.sheen = source.sheen;
  22918. this.sheenColor.copy( source.sheenColor );
  22919. this.sheenColorMap = source.sheenColorMap;
  22920. this.sheenRoughness = source.sheenRoughness;
  22921. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22922. this.transmission = source.transmission;
  22923. this.transmissionMap = source.transmissionMap;
  22924. this.thickness = source.thickness;
  22925. this.thicknessMap = source.thicknessMap;
  22926. this.attenuationDistance = source.attenuationDistance;
  22927. this.attenuationColor.copy( source.attenuationColor );
  22928. this.specularIntensity = source.specularIntensity;
  22929. this.specularIntensityMap = source.specularIntensityMap;
  22930. this.specularColor.copy( source.specularColor );
  22931. this.specularColorMap = source.specularColorMap;
  22932. return this;
  22933. }
  22934. }
  22935. class MeshPhongMaterial extends Material {
  22936. constructor( parameters ) {
  22937. super();
  22938. this.isMeshPhongMaterial = true;
  22939. this.type = 'MeshPhongMaterial';
  22940. this.color = new Color( 0xffffff ); // diffuse
  22941. this.specular = new Color( 0x111111 );
  22942. this.shininess = 30;
  22943. this.map = null;
  22944. this.lightMap = null;
  22945. this.lightMapIntensity = 1.0;
  22946. this.aoMap = null;
  22947. this.aoMapIntensity = 1.0;
  22948. this.emissive = new Color( 0x000000 );
  22949. this.emissiveIntensity = 1.0;
  22950. this.emissiveMap = null;
  22951. this.bumpMap = null;
  22952. this.bumpScale = 1;
  22953. this.normalMap = null;
  22954. this.normalMapType = TangentSpaceNormalMap;
  22955. this.normalScale = new Vector2( 1, 1 );
  22956. this.displacementMap = null;
  22957. this.displacementScale = 1;
  22958. this.displacementBias = 0;
  22959. this.specularMap = null;
  22960. this.alphaMap = null;
  22961. this.envMap = null;
  22962. this.combine = MultiplyOperation;
  22963. this.reflectivity = 1;
  22964. this.refractionRatio = 0.98;
  22965. this.wireframe = false;
  22966. this.wireframeLinewidth = 1;
  22967. this.wireframeLinecap = 'round';
  22968. this.wireframeLinejoin = 'round';
  22969. this.flatShading = false;
  22970. this.fog = true;
  22971. this.setValues( parameters );
  22972. }
  22973. copy( source ) {
  22974. super.copy( source );
  22975. this.color.copy( source.color );
  22976. this.specular.copy( source.specular );
  22977. this.shininess = source.shininess;
  22978. this.map = source.map;
  22979. this.lightMap = source.lightMap;
  22980. this.lightMapIntensity = source.lightMapIntensity;
  22981. this.aoMap = source.aoMap;
  22982. this.aoMapIntensity = source.aoMapIntensity;
  22983. this.emissive.copy( source.emissive );
  22984. this.emissiveMap = source.emissiveMap;
  22985. this.emissiveIntensity = source.emissiveIntensity;
  22986. this.bumpMap = source.bumpMap;
  22987. this.bumpScale = source.bumpScale;
  22988. this.normalMap = source.normalMap;
  22989. this.normalMapType = source.normalMapType;
  22990. this.normalScale.copy( source.normalScale );
  22991. this.displacementMap = source.displacementMap;
  22992. this.displacementScale = source.displacementScale;
  22993. this.displacementBias = source.displacementBias;
  22994. this.specularMap = source.specularMap;
  22995. this.alphaMap = source.alphaMap;
  22996. this.envMap = source.envMap;
  22997. this.combine = source.combine;
  22998. this.reflectivity = source.reflectivity;
  22999. this.refractionRatio = source.refractionRatio;
  23000. this.wireframe = source.wireframe;
  23001. this.wireframeLinewidth = source.wireframeLinewidth;
  23002. this.wireframeLinecap = source.wireframeLinecap;
  23003. this.wireframeLinejoin = source.wireframeLinejoin;
  23004. this.flatShading = source.flatShading;
  23005. this.fog = source.fog;
  23006. return this;
  23007. }
  23008. }
  23009. class MeshToonMaterial extends Material {
  23010. constructor( parameters ) {
  23011. super();
  23012. this.isMeshToonMaterial = true;
  23013. this.defines = { 'TOON': '' };
  23014. this.type = 'MeshToonMaterial';
  23015. this.color = new Color( 0xffffff );
  23016. this.map = null;
  23017. this.gradientMap = null;
  23018. this.lightMap = null;
  23019. this.lightMapIntensity = 1.0;
  23020. this.aoMap = null;
  23021. this.aoMapIntensity = 1.0;
  23022. this.emissive = new Color( 0x000000 );
  23023. this.emissiveIntensity = 1.0;
  23024. this.emissiveMap = null;
  23025. this.bumpMap = null;
  23026. this.bumpScale = 1;
  23027. this.normalMap = null;
  23028. this.normalMapType = TangentSpaceNormalMap;
  23029. this.normalScale = new Vector2( 1, 1 );
  23030. this.displacementMap = null;
  23031. this.displacementScale = 1;
  23032. this.displacementBias = 0;
  23033. this.alphaMap = null;
  23034. this.wireframe = false;
  23035. this.wireframeLinewidth = 1;
  23036. this.wireframeLinecap = 'round';
  23037. this.wireframeLinejoin = 'round';
  23038. this.fog = true;
  23039. this.setValues( parameters );
  23040. }
  23041. copy( source ) {
  23042. super.copy( source );
  23043. this.color.copy( source.color );
  23044. this.map = source.map;
  23045. this.gradientMap = source.gradientMap;
  23046. this.lightMap = source.lightMap;
  23047. this.lightMapIntensity = source.lightMapIntensity;
  23048. this.aoMap = source.aoMap;
  23049. this.aoMapIntensity = source.aoMapIntensity;
  23050. this.emissive.copy( source.emissive );
  23051. this.emissiveMap = source.emissiveMap;
  23052. this.emissiveIntensity = source.emissiveIntensity;
  23053. this.bumpMap = source.bumpMap;
  23054. this.bumpScale = source.bumpScale;
  23055. this.normalMap = source.normalMap;
  23056. this.normalMapType = source.normalMapType;
  23057. this.normalScale.copy( source.normalScale );
  23058. this.displacementMap = source.displacementMap;
  23059. this.displacementScale = source.displacementScale;
  23060. this.displacementBias = source.displacementBias;
  23061. this.alphaMap = source.alphaMap;
  23062. this.wireframe = source.wireframe;
  23063. this.wireframeLinewidth = source.wireframeLinewidth;
  23064. this.wireframeLinecap = source.wireframeLinecap;
  23065. this.wireframeLinejoin = source.wireframeLinejoin;
  23066. this.fog = source.fog;
  23067. return this;
  23068. }
  23069. }
  23070. class MeshNormalMaterial extends Material {
  23071. constructor( parameters ) {
  23072. super();
  23073. this.isMeshNormalMaterial = true;
  23074. this.type = 'MeshNormalMaterial';
  23075. this.bumpMap = null;
  23076. this.bumpScale = 1;
  23077. this.normalMap = null;
  23078. this.normalMapType = TangentSpaceNormalMap;
  23079. this.normalScale = new Vector2( 1, 1 );
  23080. this.displacementMap = null;
  23081. this.displacementScale = 1;
  23082. this.displacementBias = 0;
  23083. this.wireframe = false;
  23084. this.wireframeLinewidth = 1;
  23085. this.flatShading = false;
  23086. this.setValues( parameters );
  23087. }
  23088. copy( source ) {
  23089. super.copy( source );
  23090. this.bumpMap = source.bumpMap;
  23091. this.bumpScale = source.bumpScale;
  23092. this.normalMap = source.normalMap;
  23093. this.normalMapType = source.normalMapType;
  23094. this.normalScale.copy( source.normalScale );
  23095. this.displacementMap = source.displacementMap;
  23096. this.displacementScale = source.displacementScale;
  23097. this.displacementBias = source.displacementBias;
  23098. this.wireframe = source.wireframe;
  23099. this.wireframeLinewidth = source.wireframeLinewidth;
  23100. this.flatShading = source.flatShading;
  23101. return this;
  23102. }
  23103. }
  23104. class MeshLambertMaterial extends Material {
  23105. constructor( parameters ) {
  23106. super();
  23107. this.isMeshLambertMaterial = true;
  23108. this.type = 'MeshLambertMaterial';
  23109. this.color = new Color( 0xffffff ); // diffuse
  23110. this.map = null;
  23111. this.lightMap = null;
  23112. this.lightMapIntensity = 1.0;
  23113. this.aoMap = null;
  23114. this.aoMapIntensity = 1.0;
  23115. this.emissive = new Color( 0x000000 );
  23116. this.emissiveIntensity = 1.0;
  23117. this.emissiveMap = null;
  23118. this.bumpMap = null;
  23119. this.bumpScale = 1;
  23120. this.normalMap = null;
  23121. this.normalMapType = TangentSpaceNormalMap;
  23122. this.normalScale = new Vector2( 1, 1 );
  23123. this.displacementMap = null;
  23124. this.displacementScale = 1;
  23125. this.displacementBias = 0;
  23126. this.specularMap = null;
  23127. this.alphaMap = null;
  23128. this.envMap = null;
  23129. this.combine = MultiplyOperation;
  23130. this.reflectivity = 1;
  23131. this.refractionRatio = 0.98;
  23132. this.wireframe = false;
  23133. this.wireframeLinewidth = 1;
  23134. this.wireframeLinecap = 'round';
  23135. this.wireframeLinejoin = 'round';
  23136. this.flatShading = false;
  23137. this.fog = true;
  23138. this.setValues( parameters );
  23139. }
  23140. copy( source ) {
  23141. super.copy( source );
  23142. this.color.copy( source.color );
  23143. this.map = source.map;
  23144. this.lightMap = source.lightMap;
  23145. this.lightMapIntensity = source.lightMapIntensity;
  23146. this.aoMap = source.aoMap;
  23147. this.aoMapIntensity = source.aoMapIntensity;
  23148. this.emissive.copy( source.emissive );
  23149. this.emissiveMap = source.emissiveMap;
  23150. this.emissiveIntensity = source.emissiveIntensity;
  23151. this.bumpMap = source.bumpMap;
  23152. this.bumpScale = source.bumpScale;
  23153. this.normalMap = source.normalMap;
  23154. this.normalMapType = source.normalMapType;
  23155. this.normalScale.copy( source.normalScale );
  23156. this.displacementMap = source.displacementMap;
  23157. this.displacementScale = source.displacementScale;
  23158. this.displacementBias = source.displacementBias;
  23159. this.specularMap = source.specularMap;
  23160. this.alphaMap = source.alphaMap;
  23161. this.envMap = source.envMap;
  23162. this.combine = source.combine;
  23163. this.reflectivity = source.reflectivity;
  23164. this.refractionRatio = source.refractionRatio;
  23165. this.wireframe = source.wireframe;
  23166. this.wireframeLinewidth = source.wireframeLinewidth;
  23167. this.wireframeLinecap = source.wireframeLinecap;
  23168. this.wireframeLinejoin = source.wireframeLinejoin;
  23169. this.flatShading = source.flatShading;
  23170. this.fog = source.fog;
  23171. return this;
  23172. }
  23173. }
  23174. class MeshMatcapMaterial extends Material {
  23175. constructor( parameters ) {
  23176. super();
  23177. this.isMeshMatcapMaterial = true;
  23178. this.defines = { 'MATCAP': '' };
  23179. this.type = 'MeshMatcapMaterial';
  23180. this.color = new Color( 0xffffff ); // diffuse
  23181. this.matcap = null;
  23182. this.map = null;
  23183. this.bumpMap = null;
  23184. this.bumpScale = 1;
  23185. this.normalMap = null;
  23186. this.normalMapType = TangentSpaceNormalMap;
  23187. this.normalScale = new Vector2( 1, 1 );
  23188. this.displacementMap = null;
  23189. this.displacementScale = 1;
  23190. this.displacementBias = 0;
  23191. this.alphaMap = null;
  23192. this.flatShading = false;
  23193. this.fog = true;
  23194. this.setValues( parameters );
  23195. }
  23196. copy( source ) {
  23197. super.copy( source );
  23198. this.defines = { 'MATCAP': '' };
  23199. this.color.copy( source.color );
  23200. this.matcap = source.matcap;
  23201. this.map = source.map;
  23202. this.bumpMap = source.bumpMap;
  23203. this.bumpScale = source.bumpScale;
  23204. this.normalMap = source.normalMap;
  23205. this.normalMapType = source.normalMapType;
  23206. this.normalScale.copy( source.normalScale );
  23207. this.displacementMap = source.displacementMap;
  23208. this.displacementScale = source.displacementScale;
  23209. this.displacementBias = source.displacementBias;
  23210. this.alphaMap = source.alphaMap;
  23211. this.flatShading = source.flatShading;
  23212. this.fog = source.fog;
  23213. return this;
  23214. }
  23215. }
  23216. class LineDashedMaterial extends LineBasicMaterial {
  23217. constructor( parameters ) {
  23218. super();
  23219. this.isLineDashedMaterial = true;
  23220. this.type = 'LineDashedMaterial';
  23221. this.scale = 1;
  23222. this.dashSize = 3;
  23223. this.gapSize = 1;
  23224. this.setValues( parameters );
  23225. }
  23226. copy( source ) {
  23227. super.copy( source );
  23228. this.scale = source.scale;
  23229. this.dashSize = source.dashSize;
  23230. this.gapSize = source.gapSize;
  23231. return this;
  23232. }
  23233. }
  23234. // same as Array.prototype.slice, but also works on typed arrays
  23235. function arraySlice( array, from, to ) {
  23236. if ( isTypedArray( array ) ) {
  23237. // in ios9 array.subarray(from, undefined) will return empty array
  23238. // but array.subarray(from) or array.subarray(from, len) is correct
  23239. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  23240. }
  23241. return array.slice( from, to );
  23242. }
  23243. // converts an array to a specific type
  23244. function convertArray( array, type, forceClone ) {
  23245. if ( ! array || // let 'undefined' and 'null' pass
  23246. ! forceClone && array.constructor === type ) return array;
  23247. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23248. return new type( array ); // create typed array
  23249. }
  23250. return Array.prototype.slice.call( array ); // create Array
  23251. }
  23252. function isTypedArray( object ) {
  23253. return ArrayBuffer.isView( object ) &&
  23254. ! ( object instanceof DataView );
  23255. }
  23256. // returns an array by which times and values can be sorted
  23257. function getKeyframeOrder( times ) {
  23258. function compareTime( i, j ) {
  23259. return times[ i ] - times[ j ];
  23260. }
  23261. const n = times.length;
  23262. const result = new Array( n );
  23263. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23264. result.sort( compareTime );
  23265. return result;
  23266. }
  23267. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23268. function sortedArray( values, stride, order ) {
  23269. const nValues = values.length;
  23270. const result = new values.constructor( nValues );
  23271. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23272. const srcOffset = order[ i ] * stride;
  23273. for ( let j = 0; j !== stride; ++ j ) {
  23274. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23275. }
  23276. }
  23277. return result;
  23278. }
  23279. // function for parsing AOS keyframe formats
  23280. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23281. let i = 1, key = jsonKeys[ 0 ];
  23282. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23283. key = jsonKeys[ i ++ ];
  23284. }
  23285. if ( key === undefined ) return; // no data
  23286. let value = key[ valuePropertyName ];
  23287. if ( value === undefined ) return; // no data
  23288. if ( Array.isArray( value ) ) {
  23289. do {
  23290. value = key[ valuePropertyName ];
  23291. if ( value !== undefined ) {
  23292. times.push( key.time );
  23293. values.push.apply( values, value ); // push all elements
  23294. }
  23295. key = jsonKeys[ i ++ ];
  23296. } while ( key !== undefined );
  23297. } else if ( value.toArray !== undefined ) {
  23298. // ...assume THREE.Math-ish
  23299. do {
  23300. value = key[ valuePropertyName ];
  23301. if ( value !== undefined ) {
  23302. times.push( key.time );
  23303. value.toArray( values, values.length );
  23304. }
  23305. key = jsonKeys[ i ++ ];
  23306. } while ( key !== undefined );
  23307. } else {
  23308. // otherwise push as-is
  23309. do {
  23310. value = key[ valuePropertyName ];
  23311. if ( value !== undefined ) {
  23312. times.push( key.time );
  23313. values.push( value );
  23314. }
  23315. key = jsonKeys[ i ++ ];
  23316. } while ( key !== undefined );
  23317. }
  23318. }
  23319. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23320. const clip = sourceClip.clone();
  23321. clip.name = name;
  23322. const tracks = [];
  23323. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23324. const track = clip.tracks[ i ];
  23325. const valueSize = track.getValueSize();
  23326. const times = [];
  23327. const values = [];
  23328. for ( let j = 0; j < track.times.length; ++ j ) {
  23329. const frame = track.times[ j ] * fps;
  23330. if ( frame < startFrame || frame >= endFrame ) continue;
  23331. times.push( track.times[ j ] );
  23332. for ( let k = 0; k < valueSize; ++ k ) {
  23333. values.push( track.values[ j * valueSize + k ] );
  23334. }
  23335. }
  23336. if ( times.length === 0 ) continue;
  23337. track.times = convertArray( times, track.times.constructor );
  23338. track.values = convertArray( values, track.values.constructor );
  23339. tracks.push( track );
  23340. }
  23341. clip.tracks = tracks;
  23342. // find minimum .times value across all tracks in the trimmed clip
  23343. let minStartTime = Infinity;
  23344. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23345. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23346. minStartTime = clip.tracks[ i ].times[ 0 ];
  23347. }
  23348. }
  23349. // shift all tracks such that clip begins at t=0
  23350. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23351. clip.tracks[ i ].shift( - 1 * minStartTime );
  23352. }
  23353. clip.resetDuration();
  23354. return clip;
  23355. }
  23356. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23357. if ( fps <= 0 ) fps = 30;
  23358. const numTracks = referenceClip.tracks.length;
  23359. const referenceTime = referenceFrame / fps;
  23360. // Make each track's values relative to the values at the reference frame
  23361. for ( let i = 0; i < numTracks; ++ i ) {
  23362. const referenceTrack = referenceClip.tracks[ i ];
  23363. const referenceTrackType = referenceTrack.ValueTypeName;
  23364. // Skip this track if it's non-numeric
  23365. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23366. // Find the track in the target clip whose name and type matches the reference track
  23367. const targetTrack = targetClip.tracks.find( function ( track ) {
  23368. return track.name === referenceTrack.name
  23369. && track.ValueTypeName === referenceTrackType;
  23370. } );
  23371. if ( targetTrack === undefined ) continue;
  23372. let referenceOffset = 0;
  23373. const referenceValueSize = referenceTrack.getValueSize();
  23374. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23375. referenceOffset = referenceValueSize / 3;
  23376. }
  23377. let targetOffset = 0;
  23378. const targetValueSize = targetTrack.getValueSize();
  23379. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23380. targetOffset = targetValueSize / 3;
  23381. }
  23382. const lastIndex = referenceTrack.times.length - 1;
  23383. let referenceValue;
  23384. // Find the value to subtract out of the track
  23385. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23386. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23387. const startIndex = referenceOffset;
  23388. const endIndex = referenceValueSize - referenceOffset;
  23389. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23390. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23391. // Reference frame is after the last keyframe, so just use the last keyframe
  23392. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23393. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23394. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23395. } else {
  23396. // Interpolate to the reference value
  23397. const interpolant = referenceTrack.createInterpolant();
  23398. const startIndex = referenceOffset;
  23399. const endIndex = referenceValueSize - referenceOffset;
  23400. interpolant.evaluate( referenceTime );
  23401. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23402. }
  23403. // Conjugate the quaternion
  23404. if ( referenceTrackType === 'quaternion' ) {
  23405. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23406. referenceQuat.toArray( referenceValue );
  23407. }
  23408. // Subtract the reference value from all of the track values
  23409. const numTimes = targetTrack.times.length;
  23410. for ( let j = 0; j < numTimes; ++ j ) {
  23411. const valueStart = j * targetValueSize + targetOffset;
  23412. if ( referenceTrackType === 'quaternion' ) {
  23413. // Multiply the conjugate for quaternion track types
  23414. Quaternion.multiplyQuaternionsFlat(
  23415. targetTrack.values,
  23416. valueStart,
  23417. referenceValue,
  23418. 0,
  23419. targetTrack.values,
  23420. valueStart
  23421. );
  23422. } else {
  23423. const valueEnd = targetValueSize - targetOffset * 2;
  23424. // Subtract each value for all other numeric track types
  23425. for ( let k = 0; k < valueEnd; ++ k ) {
  23426. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23427. }
  23428. }
  23429. }
  23430. }
  23431. targetClip.blendMode = AdditiveAnimationBlendMode;
  23432. return targetClip;
  23433. }
  23434. const AnimationUtils = {
  23435. arraySlice: arraySlice,
  23436. convertArray: convertArray,
  23437. isTypedArray: isTypedArray,
  23438. getKeyframeOrder: getKeyframeOrder,
  23439. sortedArray: sortedArray,
  23440. flattenJSON: flattenJSON,
  23441. subclip: subclip,
  23442. makeClipAdditive: makeClipAdditive
  23443. };
  23444. /**
  23445. * Abstract base class of interpolants over parametric samples.
  23446. *
  23447. * The parameter domain is one dimensional, typically the time or a path
  23448. * along a curve defined by the data.
  23449. *
  23450. * The sample values can have any dimensionality and derived classes may
  23451. * apply special interpretations to the data.
  23452. *
  23453. * This class provides the interval seek in a Template Method, deferring
  23454. * the actual interpolation to derived classes.
  23455. *
  23456. * Time complexity is O(1) for linear access crossing at most two points
  23457. * and O(log N) for random access, where N is the number of positions.
  23458. *
  23459. * References:
  23460. *
  23461. * http://www.oodesign.com/template-method-pattern.html
  23462. *
  23463. */
  23464. class Interpolant {
  23465. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23466. this.parameterPositions = parameterPositions;
  23467. this._cachedIndex = 0;
  23468. this.resultBuffer = resultBuffer !== undefined ?
  23469. resultBuffer : new sampleValues.constructor( sampleSize );
  23470. this.sampleValues = sampleValues;
  23471. this.valueSize = sampleSize;
  23472. this.settings = null;
  23473. this.DefaultSettings_ = {};
  23474. }
  23475. evaluate( t ) {
  23476. const pp = this.parameterPositions;
  23477. let i1 = this._cachedIndex,
  23478. t1 = pp[ i1 ],
  23479. t0 = pp[ i1 - 1 ];
  23480. validate_interval: {
  23481. seek: {
  23482. let right;
  23483. linear_scan: {
  23484. //- See http://jsperf.com/comparison-to-undefined/3
  23485. //- slower code:
  23486. //-
  23487. //- if ( t >= t1 || t1 === undefined ) {
  23488. forward_scan: if ( ! ( t < t1 ) ) {
  23489. for ( let giveUpAt = i1 + 2; ; ) {
  23490. if ( t1 === undefined ) {
  23491. if ( t < t0 ) break forward_scan;
  23492. // after end
  23493. i1 = pp.length;
  23494. this._cachedIndex = i1;
  23495. return this.copySampleValue_( i1 - 1 );
  23496. }
  23497. if ( i1 === giveUpAt ) break; // this loop
  23498. t0 = t1;
  23499. t1 = pp[ ++ i1 ];
  23500. if ( t < t1 ) {
  23501. // we have arrived at the sought interval
  23502. break seek;
  23503. }
  23504. }
  23505. // prepare binary search on the right side of the index
  23506. right = pp.length;
  23507. break linear_scan;
  23508. }
  23509. //- slower code:
  23510. //- if ( t < t0 || t0 === undefined ) {
  23511. if ( ! ( t >= t0 ) ) {
  23512. // looping?
  23513. const t1global = pp[ 1 ];
  23514. if ( t < t1global ) {
  23515. i1 = 2; // + 1, using the scan for the details
  23516. t0 = t1global;
  23517. }
  23518. // linear reverse scan
  23519. for ( let giveUpAt = i1 - 2; ; ) {
  23520. if ( t0 === undefined ) {
  23521. // before start
  23522. this._cachedIndex = 0;
  23523. return this.copySampleValue_( 0 );
  23524. }
  23525. if ( i1 === giveUpAt ) break; // this loop
  23526. t1 = t0;
  23527. t0 = pp[ -- i1 - 1 ];
  23528. if ( t >= t0 ) {
  23529. // we have arrived at the sought interval
  23530. break seek;
  23531. }
  23532. }
  23533. // prepare binary search on the left side of the index
  23534. right = i1;
  23535. i1 = 0;
  23536. break linear_scan;
  23537. }
  23538. // the interval is valid
  23539. break validate_interval;
  23540. } // linear scan
  23541. // binary search
  23542. while ( i1 < right ) {
  23543. const mid = ( i1 + right ) >>> 1;
  23544. if ( t < pp[ mid ] ) {
  23545. right = mid;
  23546. } else {
  23547. i1 = mid + 1;
  23548. }
  23549. }
  23550. t1 = pp[ i1 ];
  23551. t0 = pp[ i1 - 1 ];
  23552. // check boundary cases, again
  23553. if ( t0 === undefined ) {
  23554. this._cachedIndex = 0;
  23555. return this.copySampleValue_( 0 );
  23556. }
  23557. if ( t1 === undefined ) {
  23558. i1 = pp.length;
  23559. this._cachedIndex = i1;
  23560. return this.copySampleValue_( i1 - 1 );
  23561. }
  23562. } // seek
  23563. this._cachedIndex = i1;
  23564. this.intervalChanged_( i1, t0, t1 );
  23565. } // validate_interval
  23566. return this.interpolate_( i1, t0, t, t1 );
  23567. }
  23568. getSettings_() {
  23569. return this.settings || this.DefaultSettings_;
  23570. }
  23571. copySampleValue_( index ) {
  23572. // copies a sample value to the result buffer
  23573. const result = this.resultBuffer,
  23574. values = this.sampleValues,
  23575. stride = this.valueSize,
  23576. offset = index * stride;
  23577. for ( let i = 0; i !== stride; ++ i ) {
  23578. result[ i ] = values[ offset + i ];
  23579. }
  23580. return result;
  23581. }
  23582. // Template methods for derived classes:
  23583. interpolate_( /* i1, t0, t, t1 */ ) {
  23584. throw new Error( 'call to abstract method' );
  23585. // implementations shall return this.resultBuffer
  23586. }
  23587. intervalChanged_( /* i1, t0, t1 */ ) {
  23588. // empty
  23589. }
  23590. }
  23591. /**
  23592. * Fast and simple cubic spline interpolant.
  23593. *
  23594. * It was derived from a Hermitian construction setting the first derivative
  23595. * at each sample position to the linear slope between neighboring positions
  23596. * over their parameter interval.
  23597. */
  23598. class CubicInterpolant extends Interpolant {
  23599. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23600. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23601. this._weightPrev = - 0;
  23602. this._offsetPrev = - 0;
  23603. this._weightNext = - 0;
  23604. this._offsetNext = - 0;
  23605. this.DefaultSettings_ = {
  23606. endingStart: ZeroCurvatureEnding,
  23607. endingEnd: ZeroCurvatureEnding
  23608. };
  23609. }
  23610. intervalChanged_( i1, t0, t1 ) {
  23611. const pp = this.parameterPositions;
  23612. let iPrev = i1 - 2,
  23613. iNext = i1 + 1,
  23614. tPrev = pp[ iPrev ],
  23615. tNext = pp[ iNext ];
  23616. if ( tPrev === undefined ) {
  23617. switch ( this.getSettings_().endingStart ) {
  23618. case ZeroSlopeEnding:
  23619. // f'(t0) = 0
  23620. iPrev = i1;
  23621. tPrev = 2 * t0 - t1;
  23622. break;
  23623. case WrapAroundEnding:
  23624. // use the other end of the curve
  23625. iPrev = pp.length - 2;
  23626. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23627. break;
  23628. default: // ZeroCurvatureEnding
  23629. // f''(t0) = 0 a.k.a. Natural Spline
  23630. iPrev = i1;
  23631. tPrev = t1;
  23632. }
  23633. }
  23634. if ( tNext === undefined ) {
  23635. switch ( this.getSettings_().endingEnd ) {
  23636. case ZeroSlopeEnding:
  23637. // f'(tN) = 0
  23638. iNext = i1;
  23639. tNext = 2 * t1 - t0;
  23640. break;
  23641. case WrapAroundEnding:
  23642. // use the other end of the curve
  23643. iNext = 1;
  23644. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23645. break;
  23646. default: // ZeroCurvatureEnding
  23647. // f''(tN) = 0, a.k.a. Natural Spline
  23648. iNext = i1 - 1;
  23649. tNext = t0;
  23650. }
  23651. }
  23652. const halfDt = ( t1 - t0 ) * 0.5,
  23653. stride = this.valueSize;
  23654. this._weightPrev = halfDt / ( t0 - tPrev );
  23655. this._weightNext = halfDt / ( tNext - t1 );
  23656. this._offsetPrev = iPrev * stride;
  23657. this._offsetNext = iNext * stride;
  23658. }
  23659. interpolate_( i1, t0, t, t1 ) {
  23660. const result = this.resultBuffer,
  23661. values = this.sampleValues,
  23662. stride = this.valueSize,
  23663. o1 = i1 * stride, o0 = o1 - stride,
  23664. oP = this._offsetPrev, oN = this._offsetNext,
  23665. wP = this._weightPrev, wN = this._weightNext,
  23666. p = ( t - t0 ) / ( t1 - t0 ),
  23667. pp = p * p,
  23668. ppp = pp * p;
  23669. // evaluate polynomials
  23670. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23671. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23672. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23673. const sN = wN * ppp - wN * pp;
  23674. // combine data linearly
  23675. for ( let i = 0; i !== stride; ++ i ) {
  23676. result[ i ] =
  23677. sP * values[ oP + i ] +
  23678. s0 * values[ o0 + i ] +
  23679. s1 * values[ o1 + i ] +
  23680. sN * values[ oN + i ];
  23681. }
  23682. return result;
  23683. }
  23684. }
  23685. class LinearInterpolant extends Interpolant {
  23686. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23687. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23688. }
  23689. interpolate_( i1, t0, t, t1 ) {
  23690. const result = this.resultBuffer,
  23691. values = this.sampleValues,
  23692. stride = this.valueSize,
  23693. offset1 = i1 * stride,
  23694. offset0 = offset1 - stride,
  23695. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23696. weight0 = 1 - weight1;
  23697. for ( let i = 0; i !== stride; ++ i ) {
  23698. result[ i ] =
  23699. values[ offset0 + i ] * weight0 +
  23700. values[ offset1 + i ] * weight1;
  23701. }
  23702. return result;
  23703. }
  23704. }
  23705. /**
  23706. *
  23707. * Interpolant that evaluates to the sample value at the position preceding
  23708. * the parameter.
  23709. */
  23710. class DiscreteInterpolant extends Interpolant {
  23711. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23712. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23713. }
  23714. interpolate_( i1 /*, t0, t, t1 */ ) {
  23715. return this.copySampleValue_( i1 - 1 );
  23716. }
  23717. }
  23718. class KeyframeTrack {
  23719. constructor( name, times, values, interpolation ) {
  23720. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23721. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23722. this.name = name;
  23723. this.times = convertArray( times, this.TimeBufferType );
  23724. this.values = convertArray( values, this.ValueBufferType );
  23725. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23726. }
  23727. // Serialization (in static context, because of constructor invocation
  23728. // and automatic invocation of .toJSON):
  23729. static toJSON( track ) {
  23730. const trackType = track.constructor;
  23731. let json;
  23732. // derived classes can define a static toJSON method
  23733. if ( trackType.toJSON !== this.toJSON ) {
  23734. json = trackType.toJSON( track );
  23735. } else {
  23736. // by default, we assume the data can be serialized as-is
  23737. json = {
  23738. 'name': track.name,
  23739. 'times': convertArray( track.times, Array ),
  23740. 'values': convertArray( track.values, Array )
  23741. };
  23742. const interpolation = track.getInterpolation();
  23743. if ( interpolation !== track.DefaultInterpolation ) {
  23744. json.interpolation = interpolation;
  23745. }
  23746. }
  23747. json.type = track.ValueTypeName; // mandatory
  23748. return json;
  23749. }
  23750. InterpolantFactoryMethodDiscrete( result ) {
  23751. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23752. }
  23753. InterpolantFactoryMethodLinear( result ) {
  23754. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23755. }
  23756. InterpolantFactoryMethodSmooth( result ) {
  23757. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23758. }
  23759. setInterpolation( interpolation ) {
  23760. let factoryMethod;
  23761. switch ( interpolation ) {
  23762. case InterpolateDiscrete:
  23763. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23764. break;
  23765. case InterpolateLinear:
  23766. factoryMethod = this.InterpolantFactoryMethodLinear;
  23767. break;
  23768. case InterpolateSmooth:
  23769. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23770. break;
  23771. }
  23772. if ( factoryMethod === undefined ) {
  23773. const message = 'unsupported interpolation for ' +
  23774. this.ValueTypeName + ' keyframe track named ' + this.name;
  23775. if ( this.createInterpolant === undefined ) {
  23776. // fall back to default, unless the default itself is messed up
  23777. if ( interpolation !== this.DefaultInterpolation ) {
  23778. this.setInterpolation( this.DefaultInterpolation );
  23779. } else {
  23780. throw new Error( message ); // fatal, in this case
  23781. }
  23782. }
  23783. console.warn( 'THREE.KeyframeTrack:', message );
  23784. return this;
  23785. }
  23786. this.createInterpolant = factoryMethod;
  23787. return this;
  23788. }
  23789. getInterpolation() {
  23790. switch ( this.createInterpolant ) {
  23791. case this.InterpolantFactoryMethodDiscrete:
  23792. return InterpolateDiscrete;
  23793. case this.InterpolantFactoryMethodLinear:
  23794. return InterpolateLinear;
  23795. case this.InterpolantFactoryMethodSmooth:
  23796. return InterpolateSmooth;
  23797. }
  23798. }
  23799. getValueSize() {
  23800. return this.values.length / this.times.length;
  23801. }
  23802. // move all keyframes either forwards or backwards in time
  23803. shift( timeOffset ) {
  23804. if ( timeOffset !== 0.0 ) {
  23805. const times = this.times;
  23806. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23807. times[ i ] += timeOffset;
  23808. }
  23809. }
  23810. return this;
  23811. }
  23812. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23813. scale( timeScale ) {
  23814. if ( timeScale !== 1.0 ) {
  23815. const times = this.times;
  23816. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23817. times[ i ] *= timeScale;
  23818. }
  23819. }
  23820. return this;
  23821. }
  23822. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23823. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23824. trim( startTime, endTime ) {
  23825. const times = this.times,
  23826. nKeys = times.length;
  23827. let from = 0,
  23828. to = nKeys - 1;
  23829. while ( from !== nKeys && times[ from ] < startTime ) {
  23830. ++ from;
  23831. }
  23832. while ( to !== - 1 && times[ to ] > endTime ) {
  23833. -- to;
  23834. }
  23835. ++ to; // inclusive -> exclusive bound
  23836. if ( from !== 0 || to !== nKeys ) {
  23837. // empty tracks are forbidden, so keep at least one keyframe
  23838. if ( from >= to ) {
  23839. to = Math.max( to, 1 );
  23840. from = to - 1;
  23841. }
  23842. const stride = this.getValueSize();
  23843. this.times = arraySlice( times, from, to );
  23844. this.values = arraySlice( this.values, from * stride, to * stride );
  23845. }
  23846. return this;
  23847. }
  23848. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23849. validate() {
  23850. let valid = true;
  23851. const valueSize = this.getValueSize();
  23852. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23853. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23854. valid = false;
  23855. }
  23856. const times = this.times,
  23857. values = this.values,
  23858. nKeys = times.length;
  23859. if ( nKeys === 0 ) {
  23860. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23861. valid = false;
  23862. }
  23863. let prevTime = null;
  23864. for ( let i = 0; i !== nKeys; i ++ ) {
  23865. const currTime = times[ i ];
  23866. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23867. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23868. valid = false;
  23869. break;
  23870. }
  23871. if ( prevTime !== null && prevTime > currTime ) {
  23872. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23873. valid = false;
  23874. break;
  23875. }
  23876. prevTime = currTime;
  23877. }
  23878. if ( values !== undefined ) {
  23879. if ( isTypedArray( values ) ) {
  23880. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23881. const value = values[ i ];
  23882. if ( isNaN( value ) ) {
  23883. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23884. valid = false;
  23885. break;
  23886. }
  23887. }
  23888. }
  23889. }
  23890. return valid;
  23891. }
  23892. // removes equivalent sequential keys as common in morph target sequences
  23893. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23894. optimize() {
  23895. // times or values may be shared with other tracks, so overwriting is unsafe
  23896. const times = arraySlice( this.times ),
  23897. values = arraySlice( this.values ),
  23898. stride = this.getValueSize(),
  23899. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23900. lastIndex = times.length - 1;
  23901. let writeIndex = 1;
  23902. for ( let i = 1; i < lastIndex; ++ i ) {
  23903. let keep = false;
  23904. const time = times[ i ];
  23905. const timeNext = times[ i + 1 ];
  23906. // remove adjacent keyframes scheduled at the same time
  23907. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23908. if ( ! smoothInterpolation ) {
  23909. // remove unnecessary keyframes same as their neighbors
  23910. const offset = i * stride,
  23911. offsetP = offset - stride,
  23912. offsetN = offset + stride;
  23913. for ( let j = 0; j !== stride; ++ j ) {
  23914. const value = values[ offset + j ];
  23915. if ( value !== values[ offsetP + j ] ||
  23916. value !== values[ offsetN + j ] ) {
  23917. keep = true;
  23918. break;
  23919. }
  23920. }
  23921. } else {
  23922. keep = true;
  23923. }
  23924. }
  23925. // in-place compaction
  23926. if ( keep ) {
  23927. if ( i !== writeIndex ) {
  23928. times[ writeIndex ] = times[ i ];
  23929. const readOffset = i * stride,
  23930. writeOffset = writeIndex * stride;
  23931. for ( let j = 0; j !== stride; ++ j ) {
  23932. values[ writeOffset + j ] = values[ readOffset + j ];
  23933. }
  23934. }
  23935. ++ writeIndex;
  23936. }
  23937. }
  23938. // flush last keyframe (compaction looks ahead)
  23939. if ( lastIndex > 0 ) {
  23940. times[ writeIndex ] = times[ lastIndex ];
  23941. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23942. values[ writeOffset + j ] = values[ readOffset + j ];
  23943. }
  23944. ++ writeIndex;
  23945. }
  23946. if ( writeIndex !== times.length ) {
  23947. this.times = arraySlice( times, 0, writeIndex );
  23948. this.values = arraySlice( values, 0, writeIndex * stride );
  23949. } else {
  23950. this.times = times;
  23951. this.values = values;
  23952. }
  23953. return this;
  23954. }
  23955. clone() {
  23956. const times = arraySlice( this.times, 0 );
  23957. const values = arraySlice( this.values, 0 );
  23958. const TypedKeyframeTrack = this.constructor;
  23959. const track = new TypedKeyframeTrack( this.name, times, values );
  23960. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23961. track.createInterpolant = this.createInterpolant;
  23962. return track;
  23963. }
  23964. }
  23965. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23966. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23967. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23968. /**
  23969. * A Track of Boolean keyframe values.
  23970. */
  23971. class BooleanKeyframeTrack extends KeyframeTrack {}
  23972. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23973. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23974. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23975. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23976. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23977. /**
  23978. * A Track of keyframe values that represent color.
  23979. */
  23980. class ColorKeyframeTrack extends KeyframeTrack {}
  23981. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23982. /**
  23983. * A Track of numeric keyframe values.
  23984. */
  23985. class NumberKeyframeTrack extends KeyframeTrack {}
  23986. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23987. /**
  23988. * Spherical linear unit quaternion interpolant.
  23989. */
  23990. class QuaternionLinearInterpolant extends Interpolant {
  23991. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23992. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23993. }
  23994. interpolate_( i1, t0, t, t1 ) {
  23995. const result = this.resultBuffer,
  23996. values = this.sampleValues,
  23997. stride = this.valueSize,
  23998. alpha = ( t - t0 ) / ( t1 - t0 );
  23999. let offset = i1 * stride;
  24000. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  24001. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24002. }
  24003. return result;
  24004. }
  24005. }
  24006. /**
  24007. * A Track of quaternion keyframe values.
  24008. */
  24009. class QuaternionKeyframeTrack extends KeyframeTrack {
  24010. InterpolantFactoryMethodLinear( result ) {
  24011. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24012. }
  24013. }
  24014. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  24015. // ValueBufferType is inherited
  24016. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24017. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24018. /**
  24019. * A Track that interpolates Strings
  24020. */
  24021. class StringKeyframeTrack extends KeyframeTrack {}
  24022. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  24023. StringKeyframeTrack.prototype.ValueBufferType = Array;
  24024. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24025. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24026. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24027. /**
  24028. * A Track of vectored keyframe values.
  24029. */
  24030. class VectorKeyframeTrack extends KeyframeTrack {}
  24031. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  24032. class AnimationClip {
  24033. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  24034. this.name = name;
  24035. this.tracks = tracks;
  24036. this.duration = duration;
  24037. this.blendMode = blendMode;
  24038. this.uuid = generateUUID();
  24039. // this means it should figure out its duration by scanning the tracks
  24040. if ( this.duration < 0 ) {
  24041. this.resetDuration();
  24042. }
  24043. }
  24044. static parse( json ) {
  24045. const tracks = [],
  24046. jsonTracks = json.tracks,
  24047. frameTime = 1.0 / ( json.fps || 1.0 );
  24048. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  24049. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  24050. }
  24051. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  24052. clip.uuid = json.uuid;
  24053. return clip;
  24054. }
  24055. static toJSON( clip ) {
  24056. const tracks = [],
  24057. clipTracks = clip.tracks;
  24058. const json = {
  24059. 'name': clip.name,
  24060. 'duration': clip.duration,
  24061. 'tracks': tracks,
  24062. 'uuid': clip.uuid,
  24063. 'blendMode': clip.blendMode
  24064. };
  24065. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  24066. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  24067. }
  24068. return json;
  24069. }
  24070. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  24071. const numMorphTargets = morphTargetSequence.length;
  24072. const tracks = [];
  24073. for ( let i = 0; i < numMorphTargets; i ++ ) {
  24074. let times = [];
  24075. let values = [];
  24076. times.push(
  24077. ( i + numMorphTargets - 1 ) % numMorphTargets,
  24078. i,
  24079. ( i + 1 ) % numMorphTargets );
  24080. values.push( 0, 1, 0 );
  24081. const order = getKeyframeOrder( times );
  24082. times = sortedArray( times, 1, order );
  24083. values = sortedArray( values, 1, order );
  24084. // if there is a key at the first frame, duplicate it as the
  24085. // last frame as well for perfect loop.
  24086. if ( ! noLoop && times[ 0 ] === 0 ) {
  24087. times.push( numMorphTargets );
  24088. values.push( values[ 0 ] );
  24089. }
  24090. tracks.push(
  24091. new NumberKeyframeTrack(
  24092. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  24093. times, values
  24094. ).scale( 1.0 / fps ) );
  24095. }
  24096. return new this( name, - 1, tracks );
  24097. }
  24098. static findByName( objectOrClipArray, name ) {
  24099. let clipArray = objectOrClipArray;
  24100. if ( ! Array.isArray( objectOrClipArray ) ) {
  24101. const o = objectOrClipArray;
  24102. clipArray = o.geometry && o.geometry.animations || o.animations;
  24103. }
  24104. for ( let i = 0; i < clipArray.length; i ++ ) {
  24105. if ( clipArray[ i ].name === name ) {
  24106. return clipArray[ i ];
  24107. }
  24108. }
  24109. return null;
  24110. }
  24111. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  24112. const animationToMorphTargets = {};
  24113. // tested with https://regex101.com/ on trick sequences
  24114. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24115. const pattern = /^([\w-]*?)([\d]+)$/;
  24116. // sort morph target names into animation groups based
  24117. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24118. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24119. const morphTarget = morphTargets[ i ];
  24120. const parts = morphTarget.name.match( pattern );
  24121. if ( parts && parts.length > 1 ) {
  24122. const name = parts[ 1 ];
  24123. let animationMorphTargets = animationToMorphTargets[ name ];
  24124. if ( ! animationMorphTargets ) {
  24125. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24126. }
  24127. animationMorphTargets.push( morphTarget );
  24128. }
  24129. }
  24130. const clips = [];
  24131. for ( const name in animationToMorphTargets ) {
  24132. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24133. }
  24134. return clips;
  24135. }
  24136. // parse the animation.hierarchy format
  24137. static parseAnimation( animation, bones ) {
  24138. if ( ! animation ) {
  24139. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24140. return null;
  24141. }
  24142. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24143. // only return track if there are actually keys.
  24144. if ( animationKeys.length !== 0 ) {
  24145. const times = [];
  24146. const values = [];
  24147. flattenJSON( animationKeys, times, values, propertyName );
  24148. // empty keys are filtered out, so check again
  24149. if ( times.length !== 0 ) {
  24150. destTracks.push( new trackType( trackName, times, values ) );
  24151. }
  24152. }
  24153. };
  24154. const tracks = [];
  24155. const clipName = animation.name || 'default';
  24156. const fps = animation.fps || 30;
  24157. const blendMode = animation.blendMode;
  24158. // automatic length determination in AnimationClip.
  24159. let duration = animation.length || - 1;
  24160. const hierarchyTracks = animation.hierarchy || [];
  24161. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24162. const animationKeys = hierarchyTracks[ h ].keys;
  24163. // skip empty tracks
  24164. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24165. // process morph targets
  24166. if ( animationKeys[ 0 ].morphTargets ) {
  24167. // figure out all morph targets used in this track
  24168. const morphTargetNames = {};
  24169. let k;
  24170. for ( k = 0; k < animationKeys.length; k ++ ) {
  24171. if ( animationKeys[ k ].morphTargets ) {
  24172. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24173. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  24174. }
  24175. }
  24176. }
  24177. // create a track for each morph target with all zero
  24178. // morphTargetInfluences except for the keys in which
  24179. // the morphTarget is named.
  24180. for ( const morphTargetName in morphTargetNames ) {
  24181. const times = [];
  24182. const values = [];
  24183. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24184. const animationKey = animationKeys[ k ];
  24185. times.push( animationKey.time );
  24186. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24187. }
  24188. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24189. }
  24190. duration = morphTargetNames.length * fps;
  24191. } else {
  24192. // ...assume skeletal animation
  24193. const boneName = '.bones[' + bones[ h ].name + ']';
  24194. addNonemptyTrack(
  24195. VectorKeyframeTrack, boneName + '.position',
  24196. animationKeys, 'pos', tracks );
  24197. addNonemptyTrack(
  24198. QuaternionKeyframeTrack, boneName + '.quaternion',
  24199. animationKeys, 'rot', tracks );
  24200. addNonemptyTrack(
  24201. VectorKeyframeTrack, boneName + '.scale',
  24202. animationKeys, 'scl', tracks );
  24203. }
  24204. }
  24205. if ( tracks.length === 0 ) {
  24206. return null;
  24207. }
  24208. const clip = new this( clipName, duration, tracks, blendMode );
  24209. return clip;
  24210. }
  24211. resetDuration() {
  24212. const tracks = this.tracks;
  24213. let duration = 0;
  24214. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24215. const track = this.tracks[ i ];
  24216. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24217. }
  24218. this.duration = duration;
  24219. return this;
  24220. }
  24221. trim() {
  24222. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24223. this.tracks[ i ].trim( 0, this.duration );
  24224. }
  24225. return this;
  24226. }
  24227. validate() {
  24228. let valid = true;
  24229. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24230. valid = valid && this.tracks[ i ].validate();
  24231. }
  24232. return valid;
  24233. }
  24234. optimize() {
  24235. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24236. this.tracks[ i ].optimize();
  24237. }
  24238. return this;
  24239. }
  24240. clone() {
  24241. const tracks = [];
  24242. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24243. tracks.push( this.tracks[ i ].clone() );
  24244. }
  24245. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24246. }
  24247. toJSON() {
  24248. return this.constructor.toJSON( this );
  24249. }
  24250. }
  24251. function getTrackTypeForValueTypeName( typeName ) {
  24252. switch ( typeName.toLowerCase() ) {
  24253. case 'scalar':
  24254. case 'double':
  24255. case 'float':
  24256. case 'number':
  24257. case 'integer':
  24258. return NumberKeyframeTrack;
  24259. case 'vector':
  24260. case 'vector2':
  24261. case 'vector3':
  24262. case 'vector4':
  24263. return VectorKeyframeTrack;
  24264. case 'color':
  24265. return ColorKeyframeTrack;
  24266. case 'quaternion':
  24267. return QuaternionKeyframeTrack;
  24268. case 'bool':
  24269. case 'boolean':
  24270. return BooleanKeyframeTrack;
  24271. case 'string':
  24272. return StringKeyframeTrack;
  24273. }
  24274. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24275. }
  24276. function parseKeyframeTrack( json ) {
  24277. if ( json.type === undefined ) {
  24278. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24279. }
  24280. const trackType = getTrackTypeForValueTypeName( json.type );
  24281. if ( json.times === undefined ) {
  24282. const times = [], values = [];
  24283. flattenJSON( json.keys, times, values, 'value' );
  24284. json.times = times;
  24285. json.values = values;
  24286. }
  24287. // derived classes can define a static parse method
  24288. if ( trackType.parse !== undefined ) {
  24289. return trackType.parse( json );
  24290. } else {
  24291. // by default, we assume a constructor compatible with the base
  24292. return new trackType( json.name, json.times, json.values, json.interpolation );
  24293. }
  24294. }
  24295. const Cache = {
  24296. enabled: false,
  24297. files: {},
  24298. add: function ( key, file ) {
  24299. if ( this.enabled === false ) return;
  24300. // console.log( 'THREE.Cache', 'Adding key:', key );
  24301. this.files[ key ] = file;
  24302. },
  24303. get: function ( key ) {
  24304. if ( this.enabled === false ) return;
  24305. // console.log( 'THREE.Cache', 'Checking key:', key );
  24306. return this.files[ key ];
  24307. },
  24308. remove: function ( key ) {
  24309. delete this.files[ key ];
  24310. },
  24311. clear: function () {
  24312. this.files = {};
  24313. }
  24314. };
  24315. class LoadingManager {
  24316. constructor( onLoad, onProgress, onError ) {
  24317. const scope = this;
  24318. let isLoading = false;
  24319. let itemsLoaded = 0;
  24320. let itemsTotal = 0;
  24321. let urlModifier = undefined;
  24322. const handlers = [];
  24323. // Refer to #5689 for the reason why we don't set .onStart
  24324. // in the constructor
  24325. this.onStart = undefined;
  24326. this.onLoad = onLoad;
  24327. this.onProgress = onProgress;
  24328. this.onError = onError;
  24329. this.itemStart = function ( url ) {
  24330. itemsTotal ++;
  24331. if ( isLoading === false ) {
  24332. if ( scope.onStart !== undefined ) {
  24333. scope.onStart( url, itemsLoaded, itemsTotal );
  24334. }
  24335. }
  24336. isLoading = true;
  24337. };
  24338. this.itemEnd = function ( url ) {
  24339. itemsLoaded ++;
  24340. if ( scope.onProgress !== undefined ) {
  24341. scope.onProgress( url, itemsLoaded, itemsTotal );
  24342. }
  24343. if ( itemsLoaded === itemsTotal ) {
  24344. isLoading = false;
  24345. if ( scope.onLoad !== undefined ) {
  24346. scope.onLoad();
  24347. }
  24348. }
  24349. };
  24350. this.itemError = function ( url ) {
  24351. if ( scope.onError !== undefined ) {
  24352. scope.onError( url );
  24353. }
  24354. };
  24355. this.resolveURL = function ( url ) {
  24356. if ( urlModifier ) {
  24357. return urlModifier( url );
  24358. }
  24359. return url;
  24360. };
  24361. this.setURLModifier = function ( transform ) {
  24362. urlModifier = transform;
  24363. return this;
  24364. };
  24365. this.addHandler = function ( regex, loader ) {
  24366. handlers.push( regex, loader );
  24367. return this;
  24368. };
  24369. this.removeHandler = function ( regex ) {
  24370. const index = handlers.indexOf( regex );
  24371. if ( index !== - 1 ) {
  24372. handlers.splice( index, 2 );
  24373. }
  24374. return this;
  24375. };
  24376. this.getHandler = function ( file ) {
  24377. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24378. const regex = handlers[ i ];
  24379. const loader = handlers[ i + 1 ];
  24380. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24381. if ( regex.test( file ) ) {
  24382. return loader;
  24383. }
  24384. }
  24385. return null;
  24386. };
  24387. }
  24388. }
  24389. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24390. class Loader {
  24391. constructor( manager ) {
  24392. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24393. this.crossOrigin = 'anonymous';
  24394. this.withCredentials = false;
  24395. this.path = '';
  24396. this.resourcePath = '';
  24397. this.requestHeader = {};
  24398. }
  24399. load( /* url, onLoad, onProgress, onError */ ) {}
  24400. loadAsync( url, onProgress ) {
  24401. const scope = this;
  24402. return new Promise( function ( resolve, reject ) {
  24403. scope.load( url, resolve, onProgress, reject );
  24404. } );
  24405. }
  24406. parse( /* data */ ) {}
  24407. setCrossOrigin( crossOrigin ) {
  24408. this.crossOrigin = crossOrigin;
  24409. return this;
  24410. }
  24411. setWithCredentials( value ) {
  24412. this.withCredentials = value;
  24413. return this;
  24414. }
  24415. setPath( path ) {
  24416. this.path = path;
  24417. return this;
  24418. }
  24419. setResourcePath( resourcePath ) {
  24420. this.resourcePath = resourcePath;
  24421. return this;
  24422. }
  24423. setRequestHeader( requestHeader ) {
  24424. this.requestHeader = requestHeader;
  24425. return this;
  24426. }
  24427. }
  24428. const loading = {};
  24429. class HttpError extends Error {
  24430. constructor( message, response ) {
  24431. super( message );
  24432. this.response = response;
  24433. }
  24434. }
  24435. class FileLoader extends Loader {
  24436. constructor( manager ) {
  24437. super( manager );
  24438. }
  24439. load( url, onLoad, onProgress, onError ) {
  24440. if ( url === undefined ) url = '';
  24441. if ( this.path !== undefined ) url = this.path + url;
  24442. url = this.manager.resolveURL( url );
  24443. const cached = Cache.get( url );
  24444. if ( cached !== undefined ) {
  24445. this.manager.itemStart( url );
  24446. setTimeout( () => {
  24447. if ( onLoad ) onLoad( cached );
  24448. this.manager.itemEnd( url );
  24449. }, 0 );
  24450. return cached;
  24451. }
  24452. // Check if request is duplicate
  24453. if ( loading[ url ] !== undefined ) {
  24454. loading[ url ].push( {
  24455. onLoad: onLoad,
  24456. onProgress: onProgress,
  24457. onError: onError
  24458. } );
  24459. return;
  24460. }
  24461. // Initialise array for duplicate requests
  24462. loading[ url ] = [];
  24463. loading[ url ].push( {
  24464. onLoad: onLoad,
  24465. onProgress: onProgress,
  24466. onError: onError,
  24467. } );
  24468. // create request
  24469. const req = new Request( url, {
  24470. headers: new Headers( this.requestHeader ),
  24471. credentials: this.withCredentials ? 'include' : 'same-origin',
  24472. // An abort controller could be added within a future PR
  24473. } );
  24474. // record states ( avoid data race )
  24475. const mimeType = this.mimeType;
  24476. const responseType = this.responseType;
  24477. // start the fetch
  24478. fetch( req )
  24479. .then( response => {
  24480. if ( response.status === 200 || response.status === 0 ) {
  24481. // Some browsers return HTTP Status 0 when using non-http protocol
  24482. // e.g. 'file://' or 'data://'. Handle as success.
  24483. if ( response.status === 0 ) {
  24484. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24485. }
  24486. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24487. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24488. return response;
  24489. }
  24490. const callbacks = loading[ url ];
  24491. const reader = response.body.getReader();
  24492. // Nginx needs X-File-Size check
  24493. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24494. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24495. const total = contentLength ? parseInt( contentLength ) : 0;
  24496. const lengthComputable = total !== 0;
  24497. let loaded = 0;
  24498. // periodically read data into the new stream tracking while download progress
  24499. const stream = new ReadableStream( {
  24500. start( controller ) {
  24501. readData();
  24502. function readData() {
  24503. reader.read().then( ( { done, value } ) => {
  24504. if ( done ) {
  24505. controller.close();
  24506. } else {
  24507. loaded += value.byteLength;
  24508. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24509. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24510. const callback = callbacks[ i ];
  24511. if ( callback.onProgress ) callback.onProgress( event );
  24512. }
  24513. controller.enqueue( value );
  24514. readData();
  24515. }
  24516. } );
  24517. }
  24518. }
  24519. } );
  24520. return new Response( stream );
  24521. } else {
  24522. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24523. }
  24524. } )
  24525. .then( response => {
  24526. switch ( responseType ) {
  24527. case 'arraybuffer':
  24528. return response.arrayBuffer();
  24529. case 'blob':
  24530. return response.blob();
  24531. case 'document':
  24532. return response.text()
  24533. .then( text => {
  24534. const parser = new DOMParser();
  24535. return parser.parseFromString( text, mimeType );
  24536. } );
  24537. case 'json':
  24538. return response.json();
  24539. default:
  24540. if ( mimeType === undefined ) {
  24541. return response.text();
  24542. } else {
  24543. // sniff encoding
  24544. const re = /charset="?([^;"\s]*)"?/i;
  24545. const exec = re.exec( mimeType );
  24546. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24547. const decoder = new TextDecoder( label );
  24548. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24549. }
  24550. }
  24551. } )
  24552. .then( data => {
  24553. // Add to cache only on HTTP success, so that we do not cache
  24554. // error response bodies as proper responses to requests.
  24555. Cache.add( url, data );
  24556. const callbacks = loading[ url ];
  24557. delete loading[ url ];
  24558. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24559. const callback = callbacks[ i ];
  24560. if ( callback.onLoad ) callback.onLoad( data );
  24561. }
  24562. } )
  24563. .catch( err => {
  24564. // Abort errors and other errors are handled the same
  24565. const callbacks = loading[ url ];
  24566. if ( callbacks === undefined ) {
  24567. // When onLoad was called and url was deleted in `loading`
  24568. this.manager.itemError( url );
  24569. throw err;
  24570. }
  24571. delete loading[ url ];
  24572. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24573. const callback = callbacks[ i ];
  24574. if ( callback.onError ) callback.onError( err );
  24575. }
  24576. this.manager.itemError( url );
  24577. } )
  24578. .finally( () => {
  24579. this.manager.itemEnd( url );
  24580. } );
  24581. this.manager.itemStart( url );
  24582. }
  24583. setResponseType( value ) {
  24584. this.responseType = value;
  24585. return this;
  24586. }
  24587. setMimeType( value ) {
  24588. this.mimeType = value;
  24589. return this;
  24590. }
  24591. }
  24592. class AnimationLoader extends Loader {
  24593. constructor( manager ) {
  24594. super( manager );
  24595. }
  24596. load( url, onLoad, onProgress, onError ) {
  24597. const scope = this;
  24598. const loader = new FileLoader( this.manager );
  24599. loader.setPath( this.path );
  24600. loader.setRequestHeader( this.requestHeader );
  24601. loader.setWithCredentials( this.withCredentials );
  24602. loader.load( url, function ( text ) {
  24603. try {
  24604. onLoad( scope.parse( JSON.parse( text ) ) );
  24605. } catch ( e ) {
  24606. if ( onError ) {
  24607. onError( e );
  24608. } else {
  24609. console.error( e );
  24610. }
  24611. scope.manager.itemError( url );
  24612. }
  24613. }, onProgress, onError );
  24614. }
  24615. parse( json ) {
  24616. const animations = [];
  24617. for ( let i = 0; i < json.length; i ++ ) {
  24618. const clip = AnimationClip.parse( json[ i ] );
  24619. animations.push( clip );
  24620. }
  24621. return animations;
  24622. }
  24623. }
  24624. /**
  24625. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24626. *
  24627. * Sub classes have to implement the parse() method which will be used in load().
  24628. */
  24629. class CompressedTextureLoader extends Loader {
  24630. constructor( manager ) {
  24631. super( manager );
  24632. }
  24633. load( url, onLoad, onProgress, onError ) {
  24634. const scope = this;
  24635. const images = [];
  24636. const texture = new CompressedTexture();
  24637. const loader = new FileLoader( this.manager );
  24638. loader.setPath( this.path );
  24639. loader.setResponseType( 'arraybuffer' );
  24640. loader.setRequestHeader( this.requestHeader );
  24641. loader.setWithCredentials( scope.withCredentials );
  24642. let loaded = 0;
  24643. function loadTexture( i ) {
  24644. loader.load( url[ i ], function ( buffer ) {
  24645. const texDatas = scope.parse( buffer, true );
  24646. images[ i ] = {
  24647. width: texDatas.width,
  24648. height: texDatas.height,
  24649. format: texDatas.format,
  24650. mipmaps: texDatas.mipmaps
  24651. };
  24652. loaded += 1;
  24653. if ( loaded === 6 ) {
  24654. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24655. texture.image = images;
  24656. texture.format = texDatas.format;
  24657. texture.needsUpdate = true;
  24658. if ( onLoad ) onLoad( texture );
  24659. }
  24660. }, onProgress, onError );
  24661. }
  24662. if ( Array.isArray( url ) ) {
  24663. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24664. loadTexture( i );
  24665. }
  24666. } else {
  24667. // compressed cubemap texture stored in a single DDS file
  24668. loader.load( url, function ( buffer ) {
  24669. const texDatas = scope.parse( buffer, true );
  24670. if ( texDatas.isCubemap ) {
  24671. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24672. for ( let f = 0; f < faces; f ++ ) {
  24673. images[ f ] = { mipmaps: [] };
  24674. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24675. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24676. images[ f ].format = texDatas.format;
  24677. images[ f ].width = texDatas.width;
  24678. images[ f ].height = texDatas.height;
  24679. }
  24680. }
  24681. texture.image = images;
  24682. } else {
  24683. texture.image.width = texDatas.width;
  24684. texture.image.height = texDatas.height;
  24685. texture.mipmaps = texDatas.mipmaps;
  24686. }
  24687. if ( texDatas.mipmapCount === 1 ) {
  24688. texture.minFilter = LinearFilter;
  24689. }
  24690. texture.format = texDatas.format;
  24691. texture.needsUpdate = true;
  24692. if ( onLoad ) onLoad( texture );
  24693. }, onProgress, onError );
  24694. }
  24695. return texture;
  24696. }
  24697. }
  24698. class ImageLoader extends Loader {
  24699. constructor( manager ) {
  24700. super( manager );
  24701. }
  24702. load( url, onLoad, onProgress, onError ) {
  24703. if ( this.path !== undefined ) url = this.path + url;
  24704. url = this.manager.resolveURL( url );
  24705. const scope = this;
  24706. const cached = Cache.get( url );
  24707. if ( cached !== undefined ) {
  24708. scope.manager.itemStart( url );
  24709. setTimeout( function () {
  24710. if ( onLoad ) onLoad( cached );
  24711. scope.manager.itemEnd( url );
  24712. }, 0 );
  24713. return cached;
  24714. }
  24715. const image = createElementNS( 'img' );
  24716. function onImageLoad() {
  24717. removeEventListeners();
  24718. Cache.add( url, this );
  24719. if ( onLoad ) onLoad( this );
  24720. scope.manager.itemEnd( url );
  24721. }
  24722. function onImageError( event ) {
  24723. removeEventListeners();
  24724. if ( onError ) onError( event );
  24725. scope.manager.itemError( url );
  24726. scope.manager.itemEnd( url );
  24727. }
  24728. function removeEventListeners() {
  24729. image.removeEventListener( 'load', onImageLoad, false );
  24730. image.removeEventListener( 'error', onImageError, false );
  24731. }
  24732. image.addEventListener( 'load', onImageLoad, false );
  24733. image.addEventListener( 'error', onImageError, false );
  24734. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24735. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24736. }
  24737. scope.manager.itemStart( url );
  24738. image.src = url;
  24739. return image;
  24740. }
  24741. }
  24742. class CubeTextureLoader extends Loader {
  24743. constructor( manager ) {
  24744. super( manager );
  24745. }
  24746. load( urls, onLoad, onProgress, onError ) {
  24747. const texture = new CubeTexture();
  24748. const loader = new ImageLoader( this.manager );
  24749. loader.setCrossOrigin( this.crossOrigin );
  24750. loader.setPath( this.path );
  24751. let loaded = 0;
  24752. function loadTexture( i ) {
  24753. loader.load( urls[ i ], function ( image ) {
  24754. texture.images[ i ] = image;
  24755. loaded ++;
  24756. if ( loaded === 6 ) {
  24757. texture.needsUpdate = true;
  24758. if ( onLoad ) onLoad( texture );
  24759. }
  24760. }, undefined, onError );
  24761. }
  24762. for ( let i = 0; i < urls.length; ++ i ) {
  24763. loadTexture( i );
  24764. }
  24765. return texture;
  24766. }
  24767. }
  24768. /**
  24769. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24770. *
  24771. * Sub classes have to implement the parse() method which will be used in load().
  24772. */
  24773. class DataTextureLoader extends Loader {
  24774. constructor( manager ) {
  24775. super( manager );
  24776. }
  24777. load( url, onLoad, onProgress, onError ) {
  24778. const scope = this;
  24779. const texture = new DataTexture();
  24780. const loader = new FileLoader( this.manager );
  24781. loader.setResponseType( 'arraybuffer' );
  24782. loader.setRequestHeader( this.requestHeader );
  24783. loader.setPath( this.path );
  24784. loader.setWithCredentials( scope.withCredentials );
  24785. loader.load( url, function ( buffer ) {
  24786. const texData = scope.parse( buffer );
  24787. if ( ! texData ) return;
  24788. if ( texData.image !== undefined ) {
  24789. texture.image = texData.image;
  24790. } else if ( texData.data !== undefined ) {
  24791. texture.image.width = texData.width;
  24792. texture.image.height = texData.height;
  24793. texture.image.data = texData.data;
  24794. }
  24795. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24796. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24797. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24798. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24799. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24800. if ( texData.colorSpace !== undefined ) {
  24801. texture.colorSpace = texData.colorSpace;
  24802. } else if ( texData.encoding !== undefined ) { // @deprecated, r152
  24803. texture.encoding = texData.encoding;
  24804. }
  24805. if ( texData.flipY !== undefined ) {
  24806. texture.flipY = texData.flipY;
  24807. }
  24808. if ( texData.format !== undefined ) {
  24809. texture.format = texData.format;
  24810. }
  24811. if ( texData.type !== undefined ) {
  24812. texture.type = texData.type;
  24813. }
  24814. if ( texData.mipmaps !== undefined ) {
  24815. texture.mipmaps = texData.mipmaps;
  24816. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24817. }
  24818. if ( texData.mipmapCount === 1 ) {
  24819. texture.minFilter = LinearFilter;
  24820. }
  24821. if ( texData.generateMipmaps !== undefined ) {
  24822. texture.generateMipmaps = texData.generateMipmaps;
  24823. }
  24824. texture.needsUpdate = true;
  24825. if ( onLoad ) onLoad( texture, texData );
  24826. }, onProgress, onError );
  24827. return texture;
  24828. }
  24829. }
  24830. class TextureLoader extends Loader {
  24831. constructor( manager ) {
  24832. super( manager );
  24833. }
  24834. load( url, onLoad, onProgress, onError ) {
  24835. const texture = new Texture();
  24836. const loader = new ImageLoader( this.manager );
  24837. loader.setCrossOrigin( this.crossOrigin );
  24838. loader.setPath( this.path );
  24839. loader.load( url, function ( image ) {
  24840. texture.image = image;
  24841. texture.needsUpdate = true;
  24842. if ( onLoad !== undefined ) {
  24843. onLoad( texture );
  24844. }
  24845. }, onProgress, onError );
  24846. return texture;
  24847. }
  24848. }
  24849. class Light extends Object3D {
  24850. constructor( color, intensity = 1 ) {
  24851. super();
  24852. this.isLight = true;
  24853. this.type = 'Light';
  24854. this.color = new Color( color );
  24855. this.intensity = intensity;
  24856. }
  24857. dispose() {
  24858. // Empty here in base class; some subclasses override.
  24859. }
  24860. copy( source, recursive ) {
  24861. super.copy( source, recursive );
  24862. this.color.copy( source.color );
  24863. this.intensity = source.intensity;
  24864. return this;
  24865. }
  24866. toJSON( meta ) {
  24867. const data = super.toJSON( meta );
  24868. data.object.color = this.color.getHex();
  24869. data.object.intensity = this.intensity;
  24870. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24871. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24872. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24873. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24874. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24875. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24876. return data;
  24877. }
  24878. }
  24879. class HemisphereLight extends Light {
  24880. constructor( skyColor, groundColor, intensity ) {
  24881. super( skyColor, intensity );
  24882. this.isHemisphereLight = true;
  24883. this.type = 'HemisphereLight';
  24884. this.position.copy( Object3D.DEFAULT_UP );
  24885. this.updateMatrix();
  24886. this.groundColor = new Color( groundColor );
  24887. }
  24888. copy( source, recursive ) {
  24889. super.copy( source, recursive );
  24890. this.groundColor.copy( source.groundColor );
  24891. return this;
  24892. }
  24893. }
  24894. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24895. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24896. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24897. class LightShadow {
  24898. constructor( camera ) {
  24899. this.camera = camera;
  24900. this.bias = 0;
  24901. this.normalBias = 0;
  24902. this.radius = 1;
  24903. this.blurSamples = 8;
  24904. this.mapSize = new Vector2( 512, 512 );
  24905. this.map = null;
  24906. this.mapPass = null;
  24907. this.matrix = new Matrix4();
  24908. this.autoUpdate = true;
  24909. this.needsUpdate = false;
  24910. this._frustum = new Frustum();
  24911. this._frameExtents = new Vector2( 1, 1 );
  24912. this._viewportCount = 1;
  24913. this._viewports = [
  24914. new Vector4( 0, 0, 1, 1 )
  24915. ];
  24916. }
  24917. getViewportCount() {
  24918. return this._viewportCount;
  24919. }
  24920. getFrustum() {
  24921. return this._frustum;
  24922. }
  24923. updateMatrices( light ) {
  24924. const shadowCamera = this.camera;
  24925. const shadowMatrix = this.matrix;
  24926. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24927. shadowCamera.position.copy( _lightPositionWorld$1 );
  24928. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24929. shadowCamera.lookAt( _lookTarget$1 );
  24930. shadowCamera.updateMatrixWorld();
  24931. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24932. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24933. shadowMatrix.set(
  24934. 0.5, 0.0, 0.0, 0.5,
  24935. 0.0, 0.5, 0.0, 0.5,
  24936. 0.0, 0.0, 0.5, 0.5,
  24937. 0.0, 0.0, 0.0, 1.0
  24938. );
  24939. shadowMatrix.multiply( _projScreenMatrix$1 );
  24940. }
  24941. getViewport( viewportIndex ) {
  24942. return this._viewports[ viewportIndex ];
  24943. }
  24944. getFrameExtents() {
  24945. return this._frameExtents;
  24946. }
  24947. dispose() {
  24948. if ( this.map ) {
  24949. this.map.dispose();
  24950. }
  24951. if ( this.mapPass ) {
  24952. this.mapPass.dispose();
  24953. }
  24954. }
  24955. copy( source ) {
  24956. this.camera = source.camera.clone();
  24957. this.bias = source.bias;
  24958. this.radius = source.radius;
  24959. this.mapSize.copy( source.mapSize );
  24960. return this;
  24961. }
  24962. clone() {
  24963. return new this.constructor().copy( this );
  24964. }
  24965. toJSON() {
  24966. const object = {};
  24967. if ( this.bias !== 0 ) object.bias = this.bias;
  24968. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24969. if ( this.radius !== 1 ) object.radius = this.radius;
  24970. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24971. object.camera = this.camera.toJSON( false ).object;
  24972. delete object.camera.matrix;
  24973. return object;
  24974. }
  24975. }
  24976. class SpotLightShadow extends LightShadow {
  24977. constructor() {
  24978. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24979. this.isSpotLightShadow = true;
  24980. this.focus = 1;
  24981. }
  24982. updateMatrices( light ) {
  24983. const camera = this.camera;
  24984. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24985. const aspect = this.mapSize.width / this.mapSize.height;
  24986. const far = light.distance || camera.far;
  24987. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24988. camera.fov = fov;
  24989. camera.aspect = aspect;
  24990. camera.far = far;
  24991. camera.updateProjectionMatrix();
  24992. }
  24993. super.updateMatrices( light );
  24994. }
  24995. copy( source ) {
  24996. super.copy( source );
  24997. this.focus = source.focus;
  24998. return this;
  24999. }
  25000. }
  25001. class SpotLight extends Light {
  25002. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  25003. super( color, intensity );
  25004. this.isSpotLight = true;
  25005. this.type = 'SpotLight';
  25006. this.position.copy( Object3D.DEFAULT_UP );
  25007. this.updateMatrix();
  25008. this.target = new Object3D();
  25009. this.distance = distance;
  25010. this.angle = angle;
  25011. this.penumbra = penumbra;
  25012. this.decay = decay;
  25013. this.map = null;
  25014. this.shadow = new SpotLightShadow();
  25015. }
  25016. get power() {
  25017. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25018. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  25019. return this.intensity * Math.PI;
  25020. }
  25021. set power( power ) {
  25022. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25023. this.intensity = power / Math.PI;
  25024. }
  25025. dispose() {
  25026. this.shadow.dispose();
  25027. }
  25028. copy( source, recursive ) {
  25029. super.copy( source, recursive );
  25030. this.distance = source.distance;
  25031. this.angle = source.angle;
  25032. this.penumbra = source.penumbra;
  25033. this.decay = source.decay;
  25034. this.target = source.target.clone();
  25035. this.shadow = source.shadow.clone();
  25036. return this;
  25037. }
  25038. }
  25039. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  25040. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  25041. const _lookTarget = /*@__PURE__*/ new Vector3();
  25042. class PointLightShadow extends LightShadow {
  25043. constructor() {
  25044. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25045. this.isPointLightShadow = true;
  25046. this._frameExtents = new Vector2( 4, 2 );
  25047. this._viewportCount = 6;
  25048. this._viewports = [
  25049. // These viewports map a cube-map onto a 2D texture with the
  25050. // following orientation:
  25051. //
  25052. // xzXZ
  25053. // y Y
  25054. //
  25055. // X - Positive x direction
  25056. // x - Negative x direction
  25057. // Y - Positive y direction
  25058. // y - Negative y direction
  25059. // Z - Positive z direction
  25060. // z - Negative z direction
  25061. // positive X
  25062. new Vector4( 2, 1, 1, 1 ),
  25063. // negative X
  25064. new Vector4( 0, 1, 1, 1 ),
  25065. // positive Z
  25066. new Vector4( 3, 1, 1, 1 ),
  25067. // negative Z
  25068. new Vector4( 1, 1, 1, 1 ),
  25069. // positive Y
  25070. new Vector4( 3, 0, 1, 1 ),
  25071. // negative Y
  25072. new Vector4( 1, 0, 1, 1 )
  25073. ];
  25074. this._cubeDirections = [
  25075. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  25076. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  25077. ];
  25078. this._cubeUps = [
  25079. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  25080. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  25081. ];
  25082. }
  25083. updateMatrices( light, viewportIndex = 0 ) {
  25084. const camera = this.camera;
  25085. const shadowMatrix = this.matrix;
  25086. const far = light.distance || camera.far;
  25087. if ( far !== camera.far ) {
  25088. camera.far = far;
  25089. camera.updateProjectionMatrix();
  25090. }
  25091. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  25092. camera.position.copy( _lightPositionWorld );
  25093. _lookTarget.copy( camera.position );
  25094. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  25095. camera.up.copy( this._cubeUps[ viewportIndex ] );
  25096. camera.lookAt( _lookTarget );
  25097. camera.updateMatrixWorld();
  25098. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  25099. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  25100. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  25101. }
  25102. }
  25103. class PointLight extends Light {
  25104. constructor( color, intensity, distance = 0, decay = 2 ) {
  25105. super( color, intensity );
  25106. this.isPointLight = true;
  25107. this.type = 'PointLight';
  25108. this.distance = distance;
  25109. this.decay = decay;
  25110. this.shadow = new PointLightShadow();
  25111. }
  25112. get power() {
  25113. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25114. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25115. return this.intensity * 4 * Math.PI;
  25116. }
  25117. set power( power ) {
  25118. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25119. this.intensity = power / ( 4 * Math.PI );
  25120. }
  25121. dispose() {
  25122. this.shadow.dispose();
  25123. }
  25124. copy( source, recursive ) {
  25125. super.copy( source, recursive );
  25126. this.distance = source.distance;
  25127. this.decay = source.decay;
  25128. this.shadow = source.shadow.clone();
  25129. return this;
  25130. }
  25131. }
  25132. class DirectionalLightShadow extends LightShadow {
  25133. constructor() {
  25134. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25135. this.isDirectionalLightShadow = true;
  25136. }
  25137. }
  25138. class DirectionalLight extends Light {
  25139. constructor( color, intensity ) {
  25140. super( color, intensity );
  25141. this.isDirectionalLight = true;
  25142. this.type = 'DirectionalLight';
  25143. this.position.copy( Object3D.DEFAULT_UP );
  25144. this.updateMatrix();
  25145. this.target = new Object3D();
  25146. this.shadow = new DirectionalLightShadow();
  25147. }
  25148. dispose() {
  25149. this.shadow.dispose();
  25150. }
  25151. copy( source ) {
  25152. super.copy( source );
  25153. this.target = source.target.clone();
  25154. this.shadow = source.shadow.clone();
  25155. return this;
  25156. }
  25157. }
  25158. class AmbientLight extends Light {
  25159. constructor( color, intensity ) {
  25160. super( color, intensity );
  25161. this.isAmbientLight = true;
  25162. this.type = 'AmbientLight';
  25163. }
  25164. }
  25165. class RectAreaLight extends Light {
  25166. constructor( color, intensity, width = 10, height = 10 ) {
  25167. super( color, intensity );
  25168. this.isRectAreaLight = true;
  25169. this.type = 'RectAreaLight';
  25170. this.width = width;
  25171. this.height = height;
  25172. }
  25173. get power() {
  25174. // compute the light's luminous power (in lumens) from its intensity (in nits)
  25175. return this.intensity * this.width * this.height * Math.PI;
  25176. }
  25177. set power( power ) {
  25178. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  25179. this.intensity = power / ( this.width * this.height * Math.PI );
  25180. }
  25181. copy( source ) {
  25182. super.copy( source );
  25183. this.width = source.width;
  25184. this.height = source.height;
  25185. return this;
  25186. }
  25187. toJSON( meta ) {
  25188. const data = super.toJSON( meta );
  25189. data.object.width = this.width;
  25190. data.object.height = this.height;
  25191. return data;
  25192. }
  25193. }
  25194. /**
  25195. * Primary reference:
  25196. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25197. *
  25198. * Secondary reference:
  25199. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25200. */
  25201. // 3-band SH defined by 9 coefficients
  25202. class SphericalHarmonics3 {
  25203. constructor() {
  25204. this.isSphericalHarmonics3 = true;
  25205. this.coefficients = [];
  25206. for ( let i = 0; i < 9; i ++ ) {
  25207. this.coefficients.push( new Vector3() );
  25208. }
  25209. }
  25210. set( coefficients ) {
  25211. for ( let i = 0; i < 9; i ++ ) {
  25212. this.coefficients[ i ].copy( coefficients[ i ] );
  25213. }
  25214. return this;
  25215. }
  25216. zero() {
  25217. for ( let i = 0; i < 9; i ++ ) {
  25218. this.coefficients[ i ].set( 0, 0, 0 );
  25219. }
  25220. return this;
  25221. }
  25222. // get the radiance in the direction of the normal
  25223. // target is a Vector3
  25224. getAt( normal, target ) {
  25225. // normal is assumed to be unit length
  25226. const x = normal.x, y = normal.y, z = normal.z;
  25227. const coeff = this.coefficients;
  25228. // band 0
  25229. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25230. // band 1
  25231. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25232. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25233. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25234. // band 2
  25235. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25236. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25237. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25238. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25239. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25240. return target;
  25241. }
  25242. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25243. // target is a Vector3
  25244. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25245. getIrradianceAt( normal, target ) {
  25246. // normal is assumed to be unit length
  25247. const x = normal.x, y = normal.y, z = normal.z;
  25248. const coeff = this.coefficients;
  25249. // band 0
  25250. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25251. // band 1
  25252. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25253. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25254. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25255. // band 2
  25256. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25257. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25258. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25259. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25260. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25261. return target;
  25262. }
  25263. add( sh ) {
  25264. for ( let i = 0; i < 9; i ++ ) {
  25265. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25266. }
  25267. return this;
  25268. }
  25269. addScaledSH( sh, s ) {
  25270. for ( let i = 0; i < 9; i ++ ) {
  25271. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25272. }
  25273. return this;
  25274. }
  25275. scale( s ) {
  25276. for ( let i = 0; i < 9; i ++ ) {
  25277. this.coefficients[ i ].multiplyScalar( s );
  25278. }
  25279. return this;
  25280. }
  25281. lerp( sh, alpha ) {
  25282. for ( let i = 0; i < 9; i ++ ) {
  25283. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25284. }
  25285. return this;
  25286. }
  25287. equals( sh ) {
  25288. for ( let i = 0; i < 9; i ++ ) {
  25289. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25290. return false;
  25291. }
  25292. }
  25293. return true;
  25294. }
  25295. copy( sh ) {
  25296. return this.set( sh.coefficients );
  25297. }
  25298. clone() {
  25299. return new this.constructor().copy( this );
  25300. }
  25301. fromArray( array, offset = 0 ) {
  25302. const coefficients = this.coefficients;
  25303. for ( let i = 0; i < 9; i ++ ) {
  25304. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25305. }
  25306. return this;
  25307. }
  25308. toArray( array = [], offset = 0 ) {
  25309. const coefficients = this.coefficients;
  25310. for ( let i = 0; i < 9; i ++ ) {
  25311. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25312. }
  25313. return array;
  25314. }
  25315. // evaluate the basis functions
  25316. // shBasis is an Array[ 9 ]
  25317. static getBasisAt( normal, shBasis ) {
  25318. // normal is assumed to be unit length
  25319. const x = normal.x, y = normal.y, z = normal.z;
  25320. // band 0
  25321. shBasis[ 0 ] = 0.282095;
  25322. // band 1
  25323. shBasis[ 1 ] = 0.488603 * y;
  25324. shBasis[ 2 ] = 0.488603 * z;
  25325. shBasis[ 3 ] = 0.488603 * x;
  25326. // band 2
  25327. shBasis[ 4 ] = 1.092548 * x * y;
  25328. shBasis[ 5 ] = 1.092548 * y * z;
  25329. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25330. shBasis[ 7 ] = 1.092548 * x * z;
  25331. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25332. }
  25333. }
  25334. class LightProbe extends Light {
  25335. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25336. super( undefined, intensity );
  25337. this.isLightProbe = true;
  25338. this.sh = sh;
  25339. }
  25340. copy( source ) {
  25341. super.copy( source );
  25342. this.sh.copy( source.sh );
  25343. return this;
  25344. }
  25345. fromJSON( json ) {
  25346. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25347. this.sh.fromArray( json.sh );
  25348. return this;
  25349. }
  25350. toJSON( meta ) {
  25351. const data = super.toJSON( meta );
  25352. data.object.sh = this.sh.toArray();
  25353. return data;
  25354. }
  25355. }
  25356. class MaterialLoader extends Loader {
  25357. constructor( manager ) {
  25358. super( manager );
  25359. this.textures = {};
  25360. }
  25361. load( url, onLoad, onProgress, onError ) {
  25362. const scope = this;
  25363. const loader = new FileLoader( scope.manager );
  25364. loader.setPath( scope.path );
  25365. loader.setRequestHeader( scope.requestHeader );
  25366. loader.setWithCredentials( scope.withCredentials );
  25367. loader.load( url, function ( text ) {
  25368. try {
  25369. onLoad( scope.parse( JSON.parse( text ) ) );
  25370. } catch ( e ) {
  25371. if ( onError ) {
  25372. onError( e );
  25373. } else {
  25374. console.error( e );
  25375. }
  25376. scope.manager.itemError( url );
  25377. }
  25378. }, onProgress, onError );
  25379. }
  25380. parse( json ) {
  25381. const textures = this.textures;
  25382. function getTexture( name ) {
  25383. if ( textures[ name ] === undefined ) {
  25384. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25385. }
  25386. return textures[ name ];
  25387. }
  25388. const material = MaterialLoader.createMaterialFromType( json.type );
  25389. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25390. if ( json.name !== undefined ) material.name = json.name;
  25391. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25392. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25393. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25394. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25395. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25396. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25397. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25398. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25399. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25400. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25401. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25402. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25403. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25404. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25405. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25406. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25407. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25408. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25409. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25410. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25411. if ( json.fog !== undefined ) material.fog = json.fog;
  25412. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25413. if ( json.blending !== undefined ) material.blending = json.blending;
  25414. if ( json.combine !== undefined ) material.combine = json.combine;
  25415. if ( json.side !== undefined ) material.side = json.side;
  25416. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25417. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25418. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25419. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25420. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25421. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25422. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25423. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25424. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25425. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25426. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25427. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25428. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25429. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25430. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25431. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25432. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25433. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25434. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25435. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25436. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25437. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25438. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25439. if ( json.scale !== undefined ) material.scale = json.scale;
  25440. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25441. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25442. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25443. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25444. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25445. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25446. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25447. if ( json.visible !== undefined ) material.visible = json.visible;
  25448. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25449. if ( json.userData !== undefined ) material.userData = json.userData;
  25450. if ( json.vertexColors !== undefined ) {
  25451. if ( typeof json.vertexColors === 'number' ) {
  25452. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25453. } else {
  25454. material.vertexColors = json.vertexColors;
  25455. }
  25456. }
  25457. // Shader Material
  25458. if ( json.uniforms !== undefined ) {
  25459. for ( const name in json.uniforms ) {
  25460. const uniform = json.uniforms[ name ];
  25461. material.uniforms[ name ] = {};
  25462. switch ( uniform.type ) {
  25463. case 't':
  25464. material.uniforms[ name ].value = getTexture( uniform.value );
  25465. break;
  25466. case 'c':
  25467. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25468. break;
  25469. case 'v2':
  25470. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25471. break;
  25472. case 'v3':
  25473. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25474. break;
  25475. case 'v4':
  25476. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25477. break;
  25478. case 'm3':
  25479. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25480. break;
  25481. case 'm4':
  25482. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25483. break;
  25484. default:
  25485. material.uniforms[ name ].value = uniform.value;
  25486. }
  25487. }
  25488. }
  25489. if ( json.defines !== undefined ) material.defines = json.defines;
  25490. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25491. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25492. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25493. if ( json.extensions !== undefined ) {
  25494. for ( const key in json.extensions ) {
  25495. material.extensions[ key ] = json.extensions[ key ];
  25496. }
  25497. }
  25498. if ( json.lights !== undefined ) material.lights = json.lights;
  25499. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  25500. // for PointsMaterial
  25501. if ( json.size !== undefined ) material.size = json.size;
  25502. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25503. // maps
  25504. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25505. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25506. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25507. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25508. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25509. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25510. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25511. if ( json.normalScale !== undefined ) {
  25512. let normalScale = json.normalScale;
  25513. if ( Array.isArray( normalScale ) === false ) {
  25514. // Blender exporter used to export a scalar. See #7459
  25515. normalScale = [ normalScale, normalScale ];
  25516. }
  25517. material.normalScale = new Vector2().fromArray( normalScale );
  25518. }
  25519. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25520. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25521. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25522. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25523. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25524. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25525. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25526. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25527. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25528. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25529. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25530. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25531. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25532. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25533. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25534. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25535. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25536. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25537. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25538. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25539. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25540. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25541. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25542. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25543. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25544. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25545. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25546. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25547. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25548. return material;
  25549. }
  25550. setTextures( value ) {
  25551. this.textures = value;
  25552. return this;
  25553. }
  25554. static createMaterialFromType( type ) {
  25555. const materialLib = {
  25556. ShadowMaterial,
  25557. SpriteMaterial,
  25558. RawShaderMaterial,
  25559. ShaderMaterial,
  25560. PointsMaterial,
  25561. MeshPhysicalMaterial,
  25562. MeshStandardMaterial,
  25563. MeshPhongMaterial,
  25564. MeshToonMaterial,
  25565. MeshNormalMaterial,
  25566. MeshLambertMaterial,
  25567. MeshDepthMaterial,
  25568. MeshDistanceMaterial,
  25569. MeshBasicMaterial,
  25570. MeshMatcapMaterial,
  25571. LineDashedMaterial,
  25572. LineBasicMaterial,
  25573. Material
  25574. };
  25575. return new materialLib[ type ]();
  25576. }
  25577. }
  25578. class LoaderUtils {
  25579. static decodeText( array ) {
  25580. if ( typeof TextDecoder !== 'undefined' ) {
  25581. return new TextDecoder().decode( array );
  25582. }
  25583. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25584. // throws a "maximum call stack size exceeded" error for large arrays.
  25585. let s = '';
  25586. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25587. // Implicitly assumes little-endian.
  25588. s += String.fromCharCode( array[ i ] );
  25589. }
  25590. try {
  25591. // merges multi-byte utf-8 characters.
  25592. return decodeURIComponent( escape( s ) );
  25593. } catch ( e ) { // see #16358
  25594. return s;
  25595. }
  25596. }
  25597. static extractUrlBase( url ) {
  25598. const index = url.lastIndexOf( '/' );
  25599. if ( index === - 1 ) return './';
  25600. return url.slice( 0, index + 1 );
  25601. }
  25602. static resolveURL( url, path ) {
  25603. // Invalid URL
  25604. if ( typeof url !== 'string' || url === '' ) return '';
  25605. // Host Relative URL
  25606. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25607. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25608. }
  25609. // Absolute URL http://,https://,//
  25610. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25611. // Data URI
  25612. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25613. // Blob URL
  25614. if ( /^blob:.*$/i.test( url ) ) return url;
  25615. // Relative URL
  25616. return path + url;
  25617. }
  25618. }
  25619. class InstancedBufferGeometry extends BufferGeometry {
  25620. constructor() {
  25621. super();
  25622. this.isInstancedBufferGeometry = true;
  25623. this.type = 'InstancedBufferGeometry';
  25624. this.instanceCount = Infinity;
  25625. }
  25626. copy( source ) {
  25627. super.copy( source );
  25628. this.instanceCount = source.instanceCount;
  25629. return this;
  25630. }
  25631. toJSON() {
  25632. const data = super.toJSON();
  25633. data.instanceCount = this.instanceCount;
  25634. data.isInstancedBufferGeometry = true;
  25635. return data;
  25636. }
  25637. }
  25638. class BufferGeometryLoader extends Loader {
  25639. constructor( manager ) {
  25640. super( manager );
  25641. }
  25642. load( url, onLoad, onProgress, onError ) {
  25643. const scope = this;
  25644. const loader = new FileLoader( scope.manager );
  25645. loader.setPath( scope.path );
  25646. loader.setRequestHeader( scope.requestHeader );
  25647. loader.setWithCredentials( scope.withCredentials );
  25648. loader.load( url, function ( text ) {
  25649. try {
  25650. onLoad( scope.parse( JSON.parse( text ) ) );
  25651. } catch ( e ) {
  25652. if ( onError ) {
  25653. onError( e );
  25654. } else {
  25655. console.error( e );
  25656. }
  25657. scope.manager.itemError( url );
  25658. }
  25659. }, onProgress, onError );
  25660. }
  25661. parse( json ) {
  25662. const interleavedBufferMap = {};
  25663. const arrayBufferMap = {};
  25664. function getInterleavedBuffer( json, uuid ) {
  25665. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25666. const interleavedBuffers = json.interleavedBuffers;
  25667. const interleavedBuffer = interleavedBuffers[ uuid ];
  25668. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25669. const array = getTypedArray( interleavedBuffer.type, buffer );
  25670. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25671. ib.uuid = interleavedBuffer.uuid;
  25672. interleavedBufferMap[ uuid ] = ib;
  25673. return ib;
  25674. }
  25675. function getArrayBuffer( json, uuid ) {
  25676. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25677. const arrayBuffers = json.arrayBuffers;
  25678. const arrayBuffer = arrayBuffers[ uuid ];
  25679. const ab = new Uint32Array( arrayBuffer ).buffer;
  25680. arrayBufferMap[ uuid ] = ab;
  25681. return ab;
  25682. }
  25683. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25684. const index = json.data.index;
  25685. if ( index !== undefined ) {
  25686. const typedArray = getTypedArray( index.type, index.array );
  25687. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25688. }
  25689. const attributes = json.data.attributes;
  25690. for ( const key in attributes ) {
  25691. const attribute = attributes[ key ];
  25692. let bufferAttribute;
  25693. if ( attribute.isInterleavedBufferAttribute ) {
  25694. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25695. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25696. } else {
  25697. const typedArray = getTypedArray( attribute.type, attribute.array );
  25698. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25699. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25700. }
  25701. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25702. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25703. if ( attribute.updateRange !== undefined ) {
  25704. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25705. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25706. }
  25707. geometry.setAttribute( key, bufferAttribute );
  25708. }
  25709. const morphAttributes = json.data.morphAttributes;
  25710. if ( morphAttributes ) {
  25711. for ( const key in morphAttributes ) {
  25712. const attributeArray = morphAttributes[ key ];
  25713. const array = [];
  25714. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25715. const attribute = attributeArray[ i ];
  25716. let bufferAttribute;
  25717. if ( attribute.isInterleavedBufferAttribute ) {
  25718. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25719. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25720. } else {
  25721. const typedArray = getTypedArray( attribute.type, attribute.array );
  25722. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25723. }
  25724. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25725. array.push( bufferAttribute );
  25726. }
  25727. geometry.morphAttributes[ key ] = array;
  25728. }
  25729. }
  25730. const morphTargetsRelative = json.data.morphTargetsRelative;
  25731. if ( morphTargetsRelative ) {
  25732. geometry.morphTargetsRelative = true;
  25733. }
  25734. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25735. if ( groups !== undefined ) {
  25736. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25737. const group = groups[ i ];
  25738. geometry.addGroup( group.start, group.count, group.materialIndex );
  25739. }
  25740. }
  25741. const boundingSphere = json.data.boundingSphere;
  25742. if ( boundingSphere !== undefined ) {
  25743. const center = new Vector3();
  25744. if ( boundingSphere.center !== undefined ) {
  25745. center.fromArray( boundingSphere.center );
  25746. }
  25747. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25748. }
  25749. if ( json.name ) geometry.name = json.name;
  25750. if ( json.userData ) geometry.userData = json.userData;
  25751. return geometry;
  25752. }
  25753. }
  25754. class ObjectLoader extends Loader {
  25755. constructor( manager ) {
  25756. super( manager );
  25757. }
  25758. load( url, onLoad, onProgress, onError ) {
  25759. const scope = this;
  25760. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25761. this.resourcePath = this.resourcePath || path;
  25762. const loader = new FileLoader( this.manager );
  25763. loader.setPath( this.path );
  25764. loader.setRequestHeader( this.requestHeader );
  25765. loader.setWithCredentials( this.withCredentials );
  25766. loader.load( url, function ( text ) {
  25767. let json = null;
  25768. try {
  25769. json = JSON.parse( text );
  25770. } catch ( error ) {
  25771. if ( onError !== undefined ) onError( error );
  25772. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25773. return;
  25774. }
  25775. const metadata = json.metadata;
  25776. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25777. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25778. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25779. return;
  25780. }
  25781. scope.parse( json, onLoad );
  25782. }, onProgress, onError );
  25783. }
  25784. async loadAsync( url, onProgress ) {
  25785. const scope = this;
  25786. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25787. this.resourcePath = this.resourcePath || path;
  25788. const loader = new FileLoader( this.manager );
  25789. loader.setPath( this.path );
  25790. loader.setRequestHeader( this.requestHeader );
  25791. loader.setWithCredentials( this.withCredentials );
  25792. const text = await loader.loadAsync( url, onProgress );
  25793. const json = JSON.parse( text );
  25794. const metadata = json.metadata;
  25795. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25796. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25797. }
  25798. return await scope.parseAsync( json );
  25799. }
  25800. parse( json, onLoad ) {
  25801. const animations = this.parseAnimations( json.animations );
  25802. const shapes = this.parseShapes( json.shapes );
  25803. const geometries = this.parseGeometries( json.geometries, shapes );
  25804. const images = this.parseImages( json.images, function () {
  25805. if ( onLoad !== undefined ) onLoad( object );
  25806. } );
  25807. const textures = this.parseTextures( json.textures, images );
  25808. const materials = this.parseMaterials( json.materials, textures );
  25809. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25810. const skeletons = this.parseSkeletons( json.skeletons, object );
  25811. this.bindSkeletons( object, skeletons );
  25812. //
  25813. if ( onLoad !== undefined ) {
  25814. let hasImages = false;
  25815. for ( const uuid in images ) {
  25816. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25817. hasImages = true;
  25818. break;
  25819. }
  25820. }
  25821. if ( hasImages === false ) onLoad( object );
  25822. }
  25823. return object;
  25824. }
  25825. async parseAsync( json ) {
  25826. const animations = this.parseAnimations( json.animations );
  25827. const shapes = this.parseShapes( json.shapes );
  25828. const geometries = this.parseGeometries( json.geometries, shapes );
  25829. const images = await this.parseImagesAsync( json.images );
  25830. const textures = this.parseTextures( json.textures, images );
  25831. const materials = this.parseMaterials( json.materials, textures );
  25832. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25833. const skeletons = this.parseSkeletons( json.skeletons, object );
  25834. this.bindSkeletons( object, skeletons );
  25835. return object;
  25836. }
  25837. parseShapes( json ) {
  25838. const shapes = {};
  25839. if ( json !== undefined ) {
  25840. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25841. const shape = new Shape().fromJSON( json[ i ] );
  25842. shapes[ shape.uuid ] = shape;
  25843. }
  25844. }
  25845. return shapes;
  25846. }
  25847. parseSkeletons( json, object ) {
  25848. const skeletons = {};
  25849. const bones = {};
  25850. // generate bone lookup table
  25851. object.traverse( function ( child ) {
  25852. if ( child.isBone ) bones[ child.uuid ] = child;
  25853. } );
  25854. // create skeletons
  25855. if ( json !== undefined ) {
  25856. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25857. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25858. skeletons[ skeleton.uuid ] = skeleton;
  25859. }
  25860. }
  25861. return skeletons;
  25862. }
  25863. parseGeometries( json, shapes ) {
  25864. const geometries = {};
  25865. if ( json !== undefined ) {
  25866. const bufferGeometryLoader = new BufferGeometryLoader();
  25867. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25868. let geometry;
  25869. const data = json[ i ];
  25870. switch ( data.type ) {
  25871. case 'BufferGeometry':
  25872. case 'InstancedBufferGeometry':
  25873. geometry = bufferGeometryLoader.parse( data );
  25874. break;
  25875. default:
  25876. if ( data.type in Geometries ) {
  25877. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25878. } else {
  25879. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25880. }
  25881. }
  25882. geometry.uuid = data.uuid;
  25883. if ( data.name !== undefined ) geometry.name = data.name;
  25884. if ( data.userData !== undefined ) geometry.userData = data.userData;
  25885. geometries[ data.uuid ] = geometry;
  25886. }
  25887. }
  25888. return geometries;
  25889. }
  25890. parseMaterials( json, textures ) {
  25891. const cache = {}; // MultiMaterial
  25892. const materials = {};
  25893. if ( json !== undefined ) {
  25894. const loader = new MaterialLoader();
  25895. loader.setTextures( textures );
  25896. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25897. const data = json[ i ];
  25898. if ( cache[ data.uuid ] === undefined ) {
  25899. cache[ data.uuid ] = loader.parse( data );
  25900. }
  25901. materials[ data.uuid ] = cache[ data.uuid ];
  25902. }
  25903. }
  25904. return materials;
  25905. }
  25906. parseAnimations( json ) {
  25907. const animations = {};
  25908. if ( json !== undefined ) {
  25909. for ( let i = 0; i < json.length; i ++ ) {
  25910. const data = json[ i ];
  25911. const clip = AnimationClip.parse( data );
  25912. animations[ clip.uuid ] = clip;
  25913. }
  25914. }
  25915. return animations;
  25916. }
  25917. parseImages( json, onLoad ) {
  25918. const scope = this;
  25919. const images = {};
  25920. let loader;
  25921. function loadImage( url ) {
  25922. scope.manager.itemStart( url );
  25923. return loader.load( url, function () {
  25924. scope.manager.itemEnd( url );
  25925. }, undefined, function () {
  25926. scope.manager.itemError( url );
  25927. scope.manager.itemEnd( url );
  25928. } );
  25929. }
  25930. function deserializeImage( image ) {
  25931. if ( typeof image === 'string' ) {
  25932. const url = image;
  25933. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25934. return loadImage( path );
  25935. } else {
  25936. if ( image.data ) {
  25937. return {
  25938. data: getTypedArray( image.type, image.data ),
  25939. width: image.width,
  25940. height: image.height
  25941. };
  25942. } else {
  25943. return null;
  25944. }
  25945. }
  25946. }
  25947. if ( json !== undefined && json.length > 0 ) {
  25948. const manager = new LoadingManager( onLoad );
  25949. loader = new ImageLoader( manager );
  25950. loader.setCrossOrigin( this.crossOrigin );
  25951. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25952. const image = json[ i ];
  25953. const url = image.url;
  25954. if ( Array.isArray( url ) ) {
  25955. // load array of images e.g CubeTexture
  25956. const imageArray = [];
  25957. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25958. const currentUrl = url[ j ];
  25959. const deserializedImage = deserializeImage( currentUrl );
  25960. if ( deserializedImage !== null ) {
  25961. if ( deserializedImage instanceof HTMLImageElement ) {
  25962. imageArray.push( deserializedImage );
  25963. } else {
  25964. // special case: handle array of data textures for cube textures
  25965. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25966. }
  25967. }
  25968. }
  25969. images[ image.uuid ] = new Source( imageArray );
  25970. } else {
  25971. // load single image
  25972. const deserializedImage = deserializeImage( image.url );
  25973. images[ image.uuid ] = new Source( deserializedImage );
  25974. }
  25975. }
  25976. }
  25977. return images;
  25978. }
  25979. async parseImagesAsync( json ) {
  25980. const scope = this;
  25981. const images = {};
  25982. let loader;
  25983. async function deserializeImage( image ) {
  25984. if ( typeof image === 'string' ) {
  25985. const url = image;
  25986. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25987. return await loader.loadAsync( path );
  25988. } else {
  25989. if ( image.data ) {
  25990. return {
  25991. data: getTypedArray( image.type, image.data ),
  25992. width: image.width,
  25993. height: image.height
  25994. };
  25995. } else {
  25996. return null;
  25997. }
  25998. }
  25999. }
  26000. if ( json !== undefined && json.length > 0 ) {
  26001. loader = new ImageLoader( this.manager );
  26002. loader.setCrossOrigin( this.crossOrigin );
  26003. for ( let i = 0, il = json.length; i < il; i ++ ) {
  26004. const image = json[ i ];
  26005. const url = image.url;
  26006. if ( Array.isArray( url ) ) {
  26007. // load array of images e.g CubeTexture
  26008. const imageArray = [];
  26009. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  26010. const currentUrl = url[ j ];
  26011. const deserializedImage = await deserializeImage( currentUrl );
  26012. if ( deserializedImage !== null ) {
  26013. if ( deserializedImage instanceof HTMLImageElement ) {
  26014. imageArray.push( deserializedImage );
  26015. } else {
  26016. // special case: handle array of data textures for cube textures
  26017. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  26018. }
  26019. }
  26020. }
  26021. images[ image.uuid ] = new Source( imageArray );
  26022. } else {
  26023. // load single image
  26024. const deserializedImage = await deserializeImage( image.url );
  26025. images[ image.uuid ] = new Source( deserializedImage );
  26026. }
  26027. }
  26028. }
  26029. return images;
  26030. }
  26031. parseTextures( json, images ) {
  26032. function parseConstant( value, type ) {
  26033. if ( typeof value === 'number' ) return value;
  26034. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  26035. return type[ value ];
  26036. }
  26037. const textures = {};
  26038. if ( json !== undefined ) {
  26039. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26040. const data = json[ i ];
  26041. if ( data.image === undefined ) {
  26042. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  26043. }
  26044. if ( images[ data.image ] === undefined ) {
  26045. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  26046. }
  26047. const source = images[ data.image ];
  26048. const image = source.data;
  26049. let texture;
  26050. if ( Array.isArray( image ) ) {
  26051. texture = new CubeTexture();
  26052. if ( image.length === 6 ) texture.needsUpdate = true;
  26053. } else {
  26054. if ( image && image.data ) {
  26055. texture = new DataTexture();
  26056. } else {
  26057. texture = new Texture();
  26058. }
  26059. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  26060. }
  26061. texture.source = source;
  26062. texture.uuid = data.uuid;
  26063. if ( data.name !== undefined ) texture.name = data.name;
  26064. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  26065. if ( data.channel !== undefined ) texture.channel = data.channel;
  26066. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  26067. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  26068. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  26069. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  26070. if ( data.wrap !== undefined ) {
  26071. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  26072. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  26073. }
  26074. if ( data.format !== undefined ) texture.format = data.format;
  26075. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  26076. if ( data.type !== undefined ) texture.type = data.type;
  26077. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  26078. if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152
  26079. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  26080. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  26081. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  26082. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  26083. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  26084. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  26085. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  26086. if ( data.userData !== undefined ) texture.userData = data.userData;
  26087. textures[ data.uuid ] = texture;
  26088. }
  26089. }
  26090. return textures;
  26091. }
  26092. parseObject( data, geometries, materials, textures, animations ) {
  26093. let object;
  26094. function getGeometry( name ) {
  26095. if ( geometries[ name ] === undefined ) {
  26096. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  26097. }
  26098. return geometries[ name ];
  26099. }
  26100. function getMaterial( name ) {
  26101. if ( name === undefined ) return undefined;
  26102. if ( Array.isArray( name ) ) {
  26103. const array = [];
  26104. for ( let i = 0, l = name.length; i < l; i ++ ) {
  26105. const uuid = name[ i ];
  26106. if ( materials[ uuid ] === undefined ) {
  26107. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  26108. }
  26109. array.push( materials[ uuid ] );
  26110. }
  26111. return array;
  26112. }
  26113. if ( materials[ name ] === undefined ) {
  26114. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26115. }
  26116. return materials[ name ];
  26117. }
  26118. function getTexture( uuid ) {
  26119. if ( textures[ uuid ] === undefined ) {
  26120. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  26121. }
  26122. return textures[ uuid ];
  26123. }
  26124. let geometry, material;
  26125. switch ( data.type ) {
  26126. case 'Scene':
  26127. object = new Scene();
  26128. if ( data.background !== undefined ) {
  26129. if ( Number.isInteger( data.background ) ) {
  26130. object.background = new Color( data.background );
  26131. } else {
  26132. object.background = getTexture( data.background );
  26133. }
  26134. }
  26135. if ( data.environment !== undefined ) {
  26136. object.environment = getTexture( data.environment );
  26137. }
  26138. if ( data.fog !== undefined ) {
  26139. if ( data.fog.type === 'Fog' ) {
  26140. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26141. } else if ( data.fog.type === 'FogExp2' ) {
  26142. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26143. }
  26144. }
  26145. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  26146. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  26147. break;
  26148. case 'PerspectiveCamera':
  26149. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26150. if ( data.focus !== undefined ) object.focus = data.focus;
  26151. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26152. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26153. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26154. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26155. break;
  26156. case 'OrthographicCamera':
  26157. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26158. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26159. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26160. break;
  26161. case 'AmbientLight':
  26162. object = new AmbientLight( data.color, data.intensity );
  26163. break;
  26164. case 'DirectionalLight':
  26165. object = new DirectionalLight( data.color, data.intensity );
  26166. break;
  26167. case 'PointLight':
  26168. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26169. break;
  26170. case 'RectAreaLight':
  26171. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26172. break;
  26173. case 'SpotLight':
  26174. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26175. break;
  26176. case 'HemisphereLight':
  26177. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26178. break;
  26179. case 'LightProbe':
  26180. object = new LightProbe().fromJSON( data );
  26181. break;
  26182. case 'SkinnedMesh':
  26183. geometry = getGeometry( data.geometry );
  26184. material = getMaterial( data.material );
  26185. object = new SkinnedMesh( geometry, material );
  26186. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  26187. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  26188. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  26189. break;
  26190. case 'Mesh':
  26191. geometry = getGeometry( data.geometry );
  26192. material = getMaterial( data.material );
  26193. object = new Mesh( geometry, material );
  26194. break;
  26195. case 'InstancedMesh':
  26196. geometry = getGeometry( data.geometry );
  26197. material = getMaterial( data.material );
  26198. const count = data.count;
  26199. const instanceMatrix = data.instanceMatrix;
  26200. const instanceColor = data.instanceColor;
  26201. object = new InstancedMesh( geometry, material, count );
  26202. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  26203. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  26204. break;
  26205. case 'LOD':
  26206. object = new LOD();
  26207. break;
  26208. case 'Line':
  26209. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  26210. break;
  26211. case 'LineLoop':
  26212. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26213. break;
  26214. case 'LineSegments':
  26215. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26216. break;
  26217. case 'PointCloud':
  26218. case 'Points':
  26219. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26220. break;
  26221. case 'Sprite':
  26222. object = new Sprite( getMaterial( data.material ) );
  26223. break;
  26224. case 'Group':
  26225. object = new Group();
  26226. break;
  26227. case 'Bone':
  26228. object = new Bone();
  26229. break;
  26230. default:
  26231. object = new Object3D();
  26232. }
  26233. object.uuid = data.uuid;
  26234. if ( data.name !== undefined ) object.name = data.name;
  26235. if ( data.matrix !== undefined ) {
  26236. object.matrix.fromArray( data.matrix );
  26237. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26238. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26239. } else {
  26240. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26241. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26242. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26243. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26244. }
  26245. if ( data.up !== undefined ) object.up.fromArray( data.up );
  26246. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26247. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26248. if ( data.shadow ) {
  26249. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26250. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26251. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26252. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26253. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26254. }
  26255. if ( data.visible !== undefined ) object.visible = data.visible;
  26256. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26257. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26258. if ( data.userData !== undefined ) object.userData = data.userData;
  26259. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26260. if ( data.children !== undefined ) {
  26261. const children = data.children;
  26262. for ( let i = 0; i < children.length; i ++ ) {
  26263. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26264. }
  26265. }
  26266. if ( data.animations !== undefined ) {
  26267. const objectAnimations = data.animations;
  26268. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26269. const uuid = objectAnimations[ i ];
  26270. object.animations.push( animations[ uuid ] );
  26271. }
  26272. }
  26273. if ( data.type === 'LOD' ) {
  26274. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26275. const levels = data.levels;
  26276. for ( let l = 0; l < levels.length; l ++ ) {
  26277. const level = levels[ l ];
  26278. const child = object.getObjectByProperty( 'uuid', level.object );
  26279. if ( child !== undefined ) {
  26280. object.addLevel( child, level.distance, level.hysteresis );
  26281. }
  26282. }
  26283. }
  26284. return object;
  26285. }
  26286. bindSkeletons( object, skeletons ) {
  26287. if ( Object.keys( skeletons ).length === 0 ) return;
  26288. object.traverse( function ( child ) {
  26289. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26290. const skeleton = skeletons[ child.skeleton ];
  26291. if ( skeleton === undefined ) {
  26292. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26293. } else {
  26294. child.bind( skeleton, child.bindMatrix );
  26295. }
  26296. }
  26297. } );
  26298. }
  26299. }
  26300. const TEXTURE_MAPPING = {
  26301. UVMapping: UVMapping,
  26302. CubeReflectionMapping: CubeReflectionMapping,
  26303. CubeRefractionMapping: CubeRefractionMapping,
  26304. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26305. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26306. CubeUVReflectionMapping: CubeUVReflectionMapping
  26307. };
  26308. const TEXTURE_WRAPPING = {
  26309. RepeatWrapping: RepeatWrapping,
  26310. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26311. MirroredRepeatWrapping: MirroredRepeatWrapping
  26312. };
  26313. const TEXTURE_FILTER = {
  26314. NearestFilter: NearestFilter,
  26315. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26316. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26317. LinearFilter: LinearFilter,
  26318. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26319. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26320. };
  26321. class ImageBitmapLoader extends Loader {
  26322. constructor( manager ) {
  26323. super( manager );
  26324. this.isImageBitmapLoader = true;
  26325. if ( typeof createImageBitmap === 'undefined' ) {
  26326. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26327. }
  26328. if ( typeof fetch === 'undefined' ) {
  26329. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26330. }
  26331. this.options = { premultiplyAlpha: 'none' };
  26332. }
  26333. setOptions( options ) {
  26334. this.options = options;
  26335. return this;
  26336. }
  26337. load( url, onLoad, onProgress, onError ) {
  26338. if ( url === undefined ) url = '';
  26339. if ( this.path !== undefined ) url = this.path + url;
  26340. url = this.manager.resolveURL( url );
  26341. const scope = this;
  26342. const cached = Cache.get( url );
  26343. if ( cached !== undefined ) {
  26344. scope.manager.itemStart( url );
  26345. setTimeout( function () {
  26346. if ( onLoad ) onLoad( cached );
  26347. scope.manager.itemEnd( url );
  26348. }, 0 );
  26349. return cached;
  26350. }
  26351. const fetchOptions = {};
  26352. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26353. fetchOptions.headers = this.requestHeader;
  26354. fetch( url, fetchOptions ).then( function ( res ) {
  26355. return res.blob();
  26356. } ).then( function ( blob ) {
  26357. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26358. } ).then( function ( imageBitmap ) {
  26359. Cache.add( url, imageBitmap );
  26360. if ( onLoad ) onLoad( imageBitmap );
  26361. scope.manager.itemEnd( url );
  26362. } ).catch( function ( e ) {
  26363. if ( onError ) onError( e );
  26364. scope.manager.itemError( url );
  26365. scope.manager.itemEnd( url );
  26366. } );
  26367. scope.manager.itemStart( url );
  26368. }
  26369. }
  26370. let _context;
  26371. class AudioContext {
  26372. static getContext() {
  26373. if ( _context === undefined ) {
  26374. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26375. }
  26376. return _context;
  26377. }
  26378. static setContext( value ) {
  26379. _context = value;
  26380. }
  26381. }
  26382. class AudioLoader extends Loader {
  26383. constructor( manager ) {
  26384. super( manager );
  26385. }
  26386. load( url, onLoad, onProgress, onError ) {
  26387. const scope = this;
  26388. const loader = new FileLoader( this.manager );
  26389. loader.setResponseType( 'arraybuffer' );
  26390. loader.setPath( this.path );
  26391. loader.setRequestHeader( this.requestHeader );
  26392. loader.setWithCredentials( this.withCredentials );
  26393. loader.load( url, function ( buffer ) {
  26394. try {
  26395. // Create a copy of the buffer. The `decodeAudioData` method
  26396. // detaches the buffer when complete, preventing reuse.
  26397. const bufferCopy = buffer.slice( 0 );
  26398. const context = AudioContext.getContext();
  26399. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26400. onLoad( audioBuffer );
  26401. }, handleError );
  26402. } catch ( e ) {
  26403. handleError( e );
  26404. }
  26405. }, onProgress, onError );
  26406. function handleError( e ) {
  26407. if ( onError ) {
  26408. onError( e );
  26409. } else {
  26410. console.error( e );
  26411. }
  26412. scope.manager.itemError( url );
  26413. }
  26414. }
  26415. }
  26416. class HemisphereLightProbe extends LightProbe {
  26417. constructor( skyColor, groundColor, intensity = 1 ) {
  26418. super( undefined, intensity );
  26419. this.isHemisphereLightProbe = true;
  26420. const color1 = new Color().set( skyColor );
  26421. const color2 = new Color().set( groundColor );
  26422. const sky = new Vector3( color1.r, color1.g, color1.b );
  26423. const ground = new Vector3( color2.r, color2.g, color2.b );
  26424. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26425. const c0 = Math.sqrt( Math.PI );
  26426. const c1 = c0 * Math.sqrt( 0.75 );
  26427. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26428. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26429. }
  26430. }
  26431. class AmbientLightProbe extends LightProbe {
  26432. constructor( color, intensity = 1 ) {
  26433. super( undefined, intensity );
  26434. this.isAmbientLightProbe = true;
  26435. const color1 = new Color().set( color );
  26436. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26437. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26438. }
  26439. }
  26440. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26441. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26442. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26443. class StereoCamera {
  26444. constructor() {
  26445. this.type = 'StereoCamera';
  26446. this.aspect = 1;
  26447. this.eyeSep = 0.064;
  26448. this.cameraL = new PerspectiveCamera();
  26449. this.cameraL.layers.enable( 1 );
  26450. this.cameraL.matrixAutoUpdate = false;
  26451. this.cameraR = new PerspectiveCamera();
  26452. this.cameraR.layers.enable( 2 );
  26453. this.cameraR.matrixAutoUpdate = false;
  26454. this._cache = {
  26455. focus: null,
  26456. fov: null,
  26457. aspect: null,
  26458. near: null,
  26459. far: null,
  26460. zoom: null,
  26461. eyeSep: null
  26462. };
  26463. }
  26464. update( camera ) {
  26465. const cache = this._cache;
  26466. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26467. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26468. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26469. if ( needsUpdate ) {
  26470. cache.focus = camera.focus;
  26471. cache.fov = camera.fov;
  26472. cache.aspect = camera.aspect * this.aspect;
  26473. cache.near = camera.near;
  26474. cache.far = camera.far;
  26475. cache.zoom = camera.zoom;
  26476. cache.eyeSep = this.eyeSep;
  26477. // Off-axis stereoscopic effect based on
  26478. // http://paulbourke.net/stereographics/stereorender/
  26479. _projectionMatrix.copy( camera.projectionMatrix );
  26480. const eyeSepHalf = cache.eyeSep / 2;
  26481. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26482. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26483. let xmin, xmax;
  26484. // translate xOffset
  26485. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26486. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26487. // for left eye
  26488. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26489. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26490. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26491. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26492. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26493. // for right eye
  26494. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26495. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26496. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26497. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26498. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26499. }
  26500. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26501. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26502. }
  26503. }
  26504. class Clock {
  26505. constructor( autoStart = true ) {
  26506. this.autoStart = autoStart;
  26507. this.startTime = 0;
  26508. this.oldTime = 0;
  26509. this.elapsedTime = 0;
  26510. this.running = false;
  26511. }
  26512. start() {
  26513. this.startTime = now();
  26514. this.oldTime = this.startTime;
  26515. this.elapsedTime = 0;
  26516. this.running = true;
  26517. }
  26518. stop() {
  26519. this.getElapsedTime();
  26520. this.running = false;
  26521. this.autoStart = false;
  26522. }
  26523. getElapsedTime() {
  26524. this.getDelta();
  26525. return this.elapsedTime;
  26526. }
  26527. getDelta() {
  26528. let diff = 0;
  26529. if ( this.autoStart && ! this.running ) {
  26530. this.start();
  26531. return 0;
  26532. }
  26533. if ( this.running ) {
  26534. const newTime = now();
  26535. diff = ( newTime - this.oldTime ) / 1000;
  26536. this.oldTime = newTime;
  26537. this.elapsedTime += diff;
  26538. }
  26539. return diff;
  26540. }
  26541. }
  26542. function now() {
  26543. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26544. }
  26545. const _position$1 = /*@__PURE__*/ new Vector3();
  26546. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26547. const _scale$1 = /*@__PURE__*/ new Vector3();
  26548. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26549. class AudioListener extends Object3D {
  26550. constructor() {
  26551. super();
  26552. this.type = 'AudioListener';
  26553. this.context = AudioContext.getContext();
  26554. this.gain = this.context.createGain();
  26555. this.gain.connect( this.context.destination );
  26556. this.filter = null;
  26557. this.timeDelta = 0;
  26558. // private
  26559. this._clock = new Clock();
  26560. }
  26561. getInput() {
  26562. return this.gain;
  26563. }
  26564. removeFilter() {
  26565. if ( this.filter !== null ) {
  26566. this.gain.disconnect( this.filter );
  26567. this.filter.disconnect( this.context.destination );
  26568. this.gain.connect( this.context.destination );
  26569. this.filter = null;
  26570. }
  26571. return this;
  26572. }
  26573. getFilter() {
  26574. return this.filter;
  26575. }
  26576. setFilter( value ) {
  26577. if ( this.filter !== null ) {
  26578. this.gain.disconnect( this.filter );
  26579. this.filter.disconnect( this.context.destination );
  26580. } else {
  26581. this.gain.disconnect( this.context.destination );
  26582. }
  26583. this.filter = value;
  26584. this.gain.connect( this.filter );
  26585. this.filter.connect( this.context.destination );
  26586. return this;
  26587. }
  26588. getMasterVolume() {
  26589. return this.gain.gain.value;
  26590. }
  26591. setMasterVolume( value ) {
  26592. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26593. return this;
  26594. }
  26595. updateMatrixWorld( force ) {
  26596. super.updateMatrixWorld( force );
  26597. const listener = this.context.listener;
  26598. const up = this.up;
  26599. this.timeDelta = this._clock.getDelta();
  26600. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26601. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26602. if ( listener.positionX ) {
  26603. // code path for Chrome (see #14393)
  26604. const endTime = this.context.currentTime + this.timeDelta;
  26605. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26606. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26607. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26608. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26609. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26610. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26611. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26612. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26613. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26614. } else {
  26615. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26616. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26617. }
  26618. }
  26619. }
  26620. class Audio extends Object3D {
  26621. constructor( listener ) {
  26622. super();
  26623. this.type = 'Audio';
  26624. this.listener = listener;
  26625. this.context = listener.context;
  26626. this.gain = this.context.createGain();
  26627. this.gain.connect( listener.getInput() );
  26628. this.autoplay = false;
  26629. this.buffer = null;
  26630. this.detune = 0;
  26631. this.loop = false;
  26632. this.loopStart = 0;
  26633. this.loopEnd = 0;
  26634. this.offset = 0;
  26635. this.duration = undefined;
  26636. this.playbackRate = 1;
  26637. this.isPlaying = false;
  26638. this.hasPlaybackControl = true;
  26639. this.source = null;
  26640. this.sourceType = 'empty';
  26641. this._startedAt = 0;
  26642. this._progress = 0;
  26643. this._connected = false;
  26644. this.filters = [];
  26645. }
  26646. getOutput() {
  26647. return this.gain;
  26648. }
  26649. setNodeSource( audioNode ) {
  26650. this.hasPlaybackControl = false;
  26651. this.sourceType = 'audioNode';
  26652. this.source = audioNode;
  26653. this.connect();
  26654. return this;
  26655. }
  26656. setMediaElementSource( mediaElement ) {
  26657. this.hasPlaybackControl = false;
  26658. this.sourceType = 'mediaNode';
  26659. this.source = this.context.createMediaElementSource( mediaElement );
  26660. this.connect();
  26661. return this;
  26662. }
  26663. setMediaStreamSource( mediaStream ) {
  26664. this.hasPlaybackControl = false;
  26665. this.sourceType = 'mediaStreamNode';
  26666. this.source = this.context.createMediaStreamSource( mediaStream );
  26667. this.connect();
  26668. return this;
  26669. }
  26670. setBuffer( audioBuffer ) {
  26671. this.buffer = audioBuffer;
  26672. this.sourceType = 'buffer';
  26673. if ( this.autoplay ) this.play();
  26674. return this;
  26675. }
  26676. play( delay = 0 ) {
  26677. if ( this.isPlaying === true ) {
  26678. console.warn( 'THREE.Audio: Audio is already playing.' );
  26679. return;
  26680. }
  26681. if ( this.hasPlaybackControl === false ) {
  26682. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26683. return;
  26684. }
  26685. this._startedAt = this.context.currentTime + delay;
  26686. const source = this.context.createBufferSource();
  26687. source.buffer = this.buffer;
  26688. source.loop = this.loop;
  26689. source.loopStart = this.loopStart;
  26690. source.loopEnd = this.loopEnd;
  26691. source.onended = this.onEnded.bind( this );
  26692. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26693. this.isPlaying = true;
  26694. this.source = source;
  26695. this.setDetune( this.detune );
  26696. this.setPlaybackRate( this.playbackRate );
  26697. return this.connect();
  26698. }
  26699. pause() {
  26700. if ( this.hasPlaybackControl === false ) {
  26701. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26702. return;
  26703. }
  26704. if ( this.isPlaying === true ) {
  26705. // update current progress
  26706. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26707. if ( this.loop === true ) {
  26708. // ensure _progress does not exceed duration with looped audios
  26709. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26710. }
  26711. this.source.stop();
  26712. this.source.onended = null;
  26713. this.isPlaying = false;
  26714. }
  26715. return this;
  26716. }
  26717. stop() {
  26718. if ( this.hasPlaybackControl === false ) {
  26719. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26720. return;
  26721. }
  26722. this._progress = 0;
  26723. if ( this.source !== null ) {
  26724. this.source.stop();
  26725. this.source.onended = null;
  26726. }
  26727. this.isPlaying = false;
  26728. return this;
  26729. }
  26730. connect() {
  26731. if ( this.filters.length > 0 ) {
  26732. this.source.connect( this.filters[ 0 ] );
  26733. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26734. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26735. }
  26736. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26737. } else {
  26738. this.source.connect( this.getOutput() );
  26739. }
  26740. this._connected = true;
  26741. return this;
  26742. }
  26743. disconnect() {
  26744. if ( this.filters.length > 0 ) {
  26745. this.source.disconnect( this.filters[ 0 ] );
  26746. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26747. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26748. }
  26749. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26750. } else {
  26751. this.source.disconnect( this.getOutput() );
  26752. }
  26753. this._connected = false;
  26754. return this;
  26755. }
  26756. getFilters() {
  26757. return this.filters;
  26758. }
  26759. setFilters( value ) {
  26760. if ( ! value ) value = [];
  26761. if ( this._connected === true ) {
  26762. this.disconnect();
  26763. this.filters = value.slice();
  26764. this.connect();
  26765. } else {
  26766. this.filters = value.slice();
  26767. }
  26768. return this;
  26769. }
  26770. setDetune( value ) {
  26771. this.detune = value;
  26772. if ( this.source.detune === undefined ) return; // only set detune when available
  26773. if ( this.isPlaying === true ) {
  26774. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26775. }
  26776. return this;
  26777. }
  26778. getDetune() {
  26779. return this.detune;
  26780. }
  26781. getFilter() {
  26782. return this.getFilters()[ 0 ];
  26783. }
  26784. setFilter( filter ) {
  26785. return this.setFilters( filter ? [ filter ] : [] );
  26786. }
  26787. setPlaybackRate( value ) {
  26788. if ( this.hasPlaybackControl === false ) {
  26789. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26790. return;
  26791. }
  26792. this.playbackRate = value;
  26793. if ( this.isPlaying === true ) {
  26794. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26795. }
  26796. return this;
  26797. }
  26798. getPlaybackRate() {
  26799. return this.playbackRate;
  26800. }
  26801. onEnded() {
  26802. this.isPlaying = false;
  26803. }
  26804. getLoop() {
  26805. if ( this.hasPlaybackControl === false ) {
  26806. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26807. return false;
  26808. }
  26809. return this.loop;
  26810. }
  26811. setLoop( value ) {
  26812. if ( this.hasPlaybackControl === false ) {
  26813. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26814. return;
  26815. }
  26816. this.loop = value;
  26817. if ( this.isPlaying === true ) {
  26818. this.source.loop = this.loop;
  26819. }
  26820. return this;
  26821. }
  26822. setLoopStart( value ) {
  26823. this.loopStart = value;
  26824. return this;
  26825. }
  26826. setLoopEnd( value ) {
  26827. this.loopEnd = value;
  26828. return this;
  26829. }
  26830. getVolume() {
  26831. return this.gain.gain.value;
  26832. }
  26833. setVolume( value ) {
  26834. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26835. return this;
  26836. }
  26837. }
  26838. const _position = /*@__PURE__*/ new Vector3();
  26839. const _quaternion = /*@__PURE__*/ new Quaternion();
  26840. const _scale = /*@__PURE__*/ new Vector3();
  26841. const _orientation = /*@__PURE__*/ new Vector3();
  26842. class PositionalAudio extends Audio {
  26843. constructor( listener ) {
  26844. super( listener );
  26845. this.panner = this.context.createPanner();
  26846. this.panner.panningModel = 'HRTF';
  26847. this.panner.connect( this.gain );
  26848. }
  26849. disconnect() {
  26850. super.disconnect();
  26851. this.panner.disconnect( this.gain );
  26852. }
  26853. getOutput() {
  26854. return this.panner;
  26855. }
  26856. getRefDistance() {
  26857. return this.panner.refDistance;
  26858. }
  26859. setRefDistance( value ) {
  26860. this.panner.refDistance = value;
  26861. return this;
  26862. }
  26863. getRolloffFactor() {
  26864. return this.panner.rolloffFactor;
  26865. }
  26866. setRolloffFactor( value ) {
  26867. this.panner.rolloffFactor = value;
  26868. return this;
  26869. }
  26870. getDistanceModel() {
  26871. return this.panner.distanceModel;
  26872. }
  26873. setDistanceModel( value ) {
  26874. this.panner.distanceModel = value;
  26875. return this;
  26876. }
  26877. getMaxDistance() {
  26878. return this.panner.maxDistance;
  26879. }
  26880. setMaxDistance( value ) {
  26881. this.panner.maxDistance = value;
  26882. return this;
  26883. }
  26884. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26885. this.panner.coneInnerAngle = coneInnerAngle;
  26886. this.panner.coneOuterAngle = coneOuterAngle;
  26887. this.panner.coneOuterGain = coneOuterGain;
  26888. return this;
  26889. }
  26890. updateMatrixWorld( force ) {
  26891. super.updateMatrixWorld( force );
  26892. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26893. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26894. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26895. const panner = this.panner;
  26896. if ( panner.positionX ) {
  26897. // code path for Chrome and Firefox (see #14393)
  26898. const endTime = this.context.currentTime + this.listener.timeDelta;
  26899. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26900. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26901. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26902. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26903. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26904. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26905. } else {
  26906. panner.setPosition( _position.x, _position.y, _position.z );
  26907. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26908. }
  26909. }
  26910. }
  26911. class AudioAnalyser {
  26912. constructor( audio, fftSize = 2048 ) {
  26913. this.analyser = audio.context.createAnalyser();
  26914. this.analyser.fftSize = fftSize;
  26915. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26916. audio.getOutput().connect( this.analyser );
  26917. }
  26918. getFrequencyData() {
  26919. this.analyser.getByteFrequencyData( this.data );
  26920. return this.data;
  26921. }
  26922. getAverageFrequency() {
  26923. let value = 0;
  26924. const data = this.getFrequencyData();
  26925. for ( let i = 0; i < data.length; i ++ ) {
  26926. value += data[ i ];
  26927. }
  26928. return value / data.length;
  26929. }
  26930. }
  26931. class PropertyMixer {
  26932. constructor( binding, typeName, valueSize ) {
  26933. this.binding = binding;
  26934. this.valueSize = valueSize;
  26935. let mixFunction,
  26936. mixFunctionAdditive,
  26937. setIdentity;
  26938. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26939. //
  26940. // interpolators can use .buffer as their .result
  26941. // the data then goes to 'incoming'
  26942. //
  26943. // 'accu0' and 'accu1' are used frame-interleaved for
  26944. // the cumulative result and are compared to detect
  26945. // changes
  26946. //
  26947. // 'orig' stores the original state of the property
  26948. //
  26949. // 'add' is used for additive cumulative results
  26950. //
  26951. // 'work' is optional and is only present for quaternion types. It is used
  26952. // to store intermediate quaternion multiplication results
  26953. switch ( typeName ) {
  26954. case 'quaternion':
  26955. mixFunction = this._slerp;
  26956. mixFunctionAdditive = this._slerpAdditive;
  26957. setIdentity = this._setAdditiveIdentityQuaternion;
  26958. this.buffer = new Float64Array( valueSize * 6 );
  26959. this._workIndex = 5;
  26960. break;
  26961. case 'string':
  26962. case 'bool':
  26963. mixFunction = this._select;
  26964. // Use the regular mix function and for additive on these types,
  26965. // additive is not relevant for non-numeric types
  26966. mixFunctionAdditive = this._select;
  26967. setIdentity = this._setAdditiveIdentityOther;
  26968. this.buffer = new Array( valueSize * 5 );
  26969. break;
  26970. default:
  26971. mixFunction = this._lerp;
  26972. mixFunctionAdditive = this._lerpAdditive;
  26973. setIdentity = this._setAdditiveIdentityNumeric;
  26974. this.buffer = new Float64Array( valueSize * 5 );
  26975. }
  26976. this._mixBufferRegion = mixFunction;
  26977. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26978. this._setIdentity = setIdentity;
  26979. this._origIndex = 3;
  26980. this._addIndex = 4;
  26981. this.cumulativeWeight = 0;
  26982. this.cumulativeWeightAdditive = 0;
  26983. this.useCount = 0;
  26984. this.referenceCount = 0;
  26985. }
  26986. // accumulate data in the 'incoming' region into 'accu<i>'
  26987. accumulate( accuIndex, weight ) {
  26988. // note: happily accumulating nothing when weight = 0, the caller knows
  26989. // the weight and shouldn't have made the call in the first place
  26990. const buffer = this.buffer,
  26991. stride = this.valueSize,
  26992. offset = accuIndex * stride + stride;
  26993. let currentWeight = this.cumulativeWeight;
  26994. if ( currentWeight === 0 ) {
  26995. // accuN := incoming * weight
  26996. for ( let i = 0; i !== stride; ++ i ) {
  26997. buffer[ offset + i ] = buffer[ i ];
  26998. }
  26999. currentWeight = weight;
  27000. } else {
  27001. // accuN := accuN + incoming * weight
  27002. currentWeight += weight;
  27003. const mix = weight / currentWeight;
  27004. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27005. }
  27006. this.cumulativeWeight = currentWeight;
  27007. }
  27008. // accumulate data in the 'incoming' region into 'add'
  27009. accumulateAdditive( weight ) {
  27010. const buffer = this.buffer,
  27011. stride = this.valueSize,
  27012. offset = stride * this._addIndex;
  27013. if ( this.cumulativeWeightAdditive === 0 ) {
  27014. // add = identity
  27015. this._setIdentity();
  27016. }
  27017. // add := add + incoming * weight
  27018. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  27019. this.cumulativeWeightAdditive += weight;
  27020. }
  27021. // apply the state of 'accu<i>' to the binding when accus differ
  27022. apply( accuIndex ) {
  27023. const stride = this.valueSize,
  27024. buffer = this.buffer,
  27025. offset = accuIndex * stride + stride,
  27026. weight = this.cumulativeWeight,
  27027. weightAdditive = this.cumulativeWeightAdditive,
  27028. binding = this.binding;
  27029. this.cumulativeWeight = 0;
  27030. this.cumulativeWeightAdditive = 0;
  27031. if ( weight < 1 ) {
  27032. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27033. const originalValueOffset = stride * this._origIndex;
  27034. this._mixBufferRegion(
  27035. buffer, offset, originalValueOffset, 1 - weight, stride );
  27036. }
  27037. if ( weightAdditive > 0 ) {
  27038. // accuN := accuN + additive accuN
  27039. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  27040. }
  27041. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  27042. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27043. // value has changed -> update scene graph
  27044. binding.setValue( buffer, offset );
  27045. break;
  27046. }
  27047. }
  27048. }
  27049. // remember the state of the bound property and copy it to both accus
  27050. saveOriginalState() {
  27051. const binding = this.binding;
  27052. const buffer = this.buffer,
  27053. stride = this.valueSize,
  27054. originalValueOffset = stride * this._origIndex;
  27055. binding.getValue( buffer, originalValueOffset );
  27056. // accu[0..1] := orig -- initially detect changes against the original
  27057. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27058. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27059. }
  27060. // Add to identity for additive
  27061. this._setIdentity();
  27062. this.cumulativeWeight = 0;
  27063. this.cumulativeWeightAdditive = 0;
  27064. }
  27065. // apply the state previously taken via 'saveOriginalState' to the binding
  27066. restoreOriginalState() {
  27067. const originalValueOffset = this.valueSize * 3;
  27068. this.binding.setValue( this.buffer, originalValueOffset );
  27069. }
  27070. _setAdditiveIdentityNumeric() {
  27071. const startIndex = this._addIndex * this.valueSize;
  27072. const endIndex = startIndex + this.valueSize;
  27073. for ( let i = startIndex; i < endIndex; i ++ ) {
  27074. this.buffer[ i ] = 0;
  27075. }
  27076. }
  27077. _setAdditiveIdentityQuaternion() {
  27078. this._setAdditiveIdentityNumeric();
  27079. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  27080. }
  27081. _setAdditiveIdentityOther() {
  27082. const startIndex = this._origIndex * this.valueSize;
  27083. const targetIndex = this._addIndex * this.valueSize;
  27084. for ( let i = 0; i < this.valueSize; i ++ ) {
  27085. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  27086. }
  27087. }
  27088. // mix functions
  27089. _select( buffer, dstOffset, srcOffset, t, stride ) {
  27090. if ( t >= 0.5 ) {
  27091. for ( let i = 0; i !== stride; ++ i ) {
  27092. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27093. }
  27094. }
  27095. }
  27096. _slerp( buffer, dstOffset, srcOffset, t ) {
  27097. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27098. }
  27099. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27100. const workOffset = this._workIndex * stride;
  27101. // Store result in intermediate buffer offset
  27102. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  27103. // Slerp to the intermediate result
  27104. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  27105. }
  27106. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  27107. const s = 1 - t;
  27108. for ( let i = 0; i !== stride; ++ i ) {
  27109. const j = dstOffset + i;
  27110. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27111. }
  27112. }
  27113. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27114. for ( let i = 0; i !== stride; ++ i ) {
  27115. const j = dstOffset + i;
  27116. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  27117. }
  27118. }
  27119. }
  27120. // Characters [].:/ are reserved for track binding syntax.
  27121. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27122. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27123. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27124. // only latin characters, and the unicode \p{L} is not yet supported. So
  27125. // instead, we exclude reserved characters and match everything else.
  27126. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27127. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27128. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27129. // be matched to parse the rest of the track name.
  27130. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27131. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27132. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27133. // Object on target node, and accessor. May not contain reserved
  27134. // characters. Accessor may contain any character except closing bracket.
  27135. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27136. // Property and accessor. May not contain reserved characters. Accessor may
  27137. // contain any non-bracket characters.
  27138. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27139. const _trackRe = new RegExp( ''
  27140. + '^'
  27141. + _directoryRe
  27142. + _nodeRe
  27143. + _objectRe
  27144. + _propertyRe
  27145. + '$'
  27146. );
  27147. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  27148. class Composite {
  27149. constructor( targetGroup, path, optionalParsedPath ) {
  27150. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27151. this._targetGroup = targetGroup;
  27152. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27153. }
  27154. getValue( array, offset ) {
  27155. this.bind(); // bind all binding
  27156. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27157. binding = this._bindings[ firstValidIndex ];
  27158. // and only call .getValue on the first
  27159. if ( binding !== undefined ) binding.getValue( array, offset );
  27160. }
  27161. setValue( array, offset ) {
  27162. const bindings = this._bindings;
  27163. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27164. bindings[ i ].setValue( array, offset );
  27165. }
  27166. }
  27167. bind() {
  27168. const bindings = this._bindings;
  27169. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27170. bindings[ i ].bind();
  27171. }
  27172. }
  27173. unbind() {
  27174. const bindings = this._bindings;
  27175. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27176. bindings[ i ].unbind();
  27177. }
  27178. }
  27179. }
  27180. // Note: This class uses a State pattern on a per-method basis:
  27181. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27182. // prototype version of these methods with one that represents
  27183. // the bound state. When the property is not found, the methods
  27184. // become no-ops.
  27185. class PropertyBinding {
  27186. constructor( rootNode, path, parsedPath ) {
  27187. this.path = path;
  27188. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27189. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  27190. this.rootNode = rootNode;
  27191. // initial state of these methods that calls 'bind'
  27192. this.getValue = this._getValue_unbound;
  27193. this.setValue = this._setValue_unbound;
  27194. }
  27195. static create( root, path, parsedPath ) {
  27196. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27197. return new PropertyBinding( root, path, parsedPath );
  27198. } else {
  27199. return new PropertyBinding.Composite( root, path, parsedPath );
  27200. }
  27201. }
  27202. /**
  27203. * Replaces spaces with underscores and removes unsupported characters from
  27204. * node names, to ensure compatibility with parseTrackName().
  27205. *
  27206. * @param {string} name Node name to be sanitized.
  27207. * @return {string}
  27208. */
  27209. static sanitizeNodeName( name ) {
  27210. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27211. }
  27212. static parseTrackName( trackName ) {
  27213. const matches = _trackRe.exec( trackName );
  27214. if ( matches === null ) {
  27215. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27216. }
  27217. const results = {
  27218. // directoryName: matches[ 1 ], // (tschw) currently unused
  27219. nodeName: matches[ 2 ],
  27220. objectName: matches[ 3 ],
  27221. objectIndex: matches[ 4 ],
  27222. propertyName: matches[ 5 ], // required
  27223. propertyIndex: matches[ 6 ]
  27224. };
  27225. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27226. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27227. const objectName = results.nodeName.substring( lastDot + 1 );
  27228. // Object names must be checked against an allowlist. Otherwise, there
  27229. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27230. // 'bar' could be the objectName, or part of a nodeName (which can
  27231. // include '.' characters).
  27232. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27233. results.nodeName = results.nodeName.substring( 0, lastDot );
  27234. results.objectName = objectName;
  27235. }
  27236. }
  27237. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27238. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27239. }
  27240. return results;
  27241. }
  27242. static findNode( root, nodeName ) {
  27243. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27244. return root;
  27245. }
  27246. // search into skeleton bones.
  27247. if ( root.skeleton ) {
  27248. const bone = root.skeleton.getBoneByName( nodeName );
  27249. if ( bone !== undefined ) {
  27250. return bone;
  27251. }
  27252. }
  27253. // search into node subtree.
  27254. if ( root.children ) {
  27255. const searchNodeSubtree = function ( children ) {
  27256. for ( let i = 0; i < children.length; i ++ ) {
  27257. const childNode = children[ i ];
  27258. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27259. return childNode;
  27260. }
  27261. const result = searchNodeSubtree( childNode.children );
  27262. if ( result ) return result;
  27263. }
  27264. return null;
  27265. };
  27266. const subTreeNode = searchNodeSubtree( root.children );
  27267. if ( subTreeNode ) {
  27268. return subTreeNode;
  27269. }
  27270. }
  27271. return null;
  27272. }
  27273. // these are used to "bind" a nonexistent property
  27274. _getValue_unavailable() {}
  27275. _setValue_unavailable() {}
  27276. // Getters
  27277. _getValue_direct( buffer, offset ) {
  27278. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27279. }
  27280. _getValue_array( buffer, offset ) {
  27281. const source = this.resolvedProperty;
  27282. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27283. buffer[ offset ++ ] = source[ i ];
  27284. }
  27285. }
  27286. _getValue_arrayElement( buffer, offset ) {
  27287. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27288. }
  27289. _getValue_toArray( buffer, offset ) {
  27290. this.resolvedProperty.toArray( buffer, offset );
  27291. }
  27292. // Direct
  27293. _setValue_direct( buffer, offset ) {
  27294. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27295. }
  27296. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27297. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27298. this.targetObject.needsUpdate = true;
  27299. }
  27300. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27301. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27302. this.targetObject.matrixWorldNeedsUpdate = true;
  27303. }
  27304. // EntireArray
  27305. _setValue_array( buffer, offset ) {
  27306. const dest = this.resolvedProperty;
  27307. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27308. dest[ i ] = buffer[ offset ++ ];
  27309. }
  27310. }
  27311. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27312. const dest = this.resolvedProperty;
  27313. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27314. dest[ i ] = buffer[ offset ++ ];
  27315. }
  27316. this.targetObject.needsUpdate = true;
  27317. }
  27318. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27319. const dest = this.resolvedProperty;
  27320. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27321. dest[ i ] = buffer[ offset ++ ];
  27322. }
  27323. this.targetObject.matrixWorldNeedsUpdate = true;
  27324. }
  27325. // ArrayElement
  27326. _setValue_arrayElement( buffer, offset ) {
  27327. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27328. }
  27329. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27330. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27331. this.targetObject.needsUpdate = true;
  27332. }
  27333. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27334. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27335. this.targetObject.matrixWorldNeedsUpdate = true;
  27336. }
  27337. // HasToFromArray
  27338. _setValue_fromArray( buffer, offset ) {
  27339. this.resolvedProperty.fromArray( buffer, offset );
  27340. }
  27341. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27342. this.resolvedProperty.fromArray( buffer, offset );
  27343. this.targetObject.needsUpdate = true;
  27344. }
  27345. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27346. this.resolvedProperty.fromArray( buffer, offset );
  27347. this.targetObject.matrixWorldNeedsUpdate = true;
  27348. }
  27349. _getValue_unbound( targetArray, offset ) {
  27350. this.bind();
  27351. this.getValue( targetArray, offset );
  27352. }
  27353. _setValue_unbound( sourceArray, offset ) {
  27354. this.bind();
  27355. this.setValue( sourceArray, offset );
  27356. }
  27357. // create getter / setter pair for a property in the scene graph
  27358. bind() {
  27359. let targetObject = this.node;
  27360. const parsedPath = this.parsedPath;
  27361. const objectName = parsedPath.objectName;
  27362. const propertyName = parsedPath.propertyName;
  27363. let propertyIndex = parsedPath.propertyIndex;
  27364. if ( ! targetObject ) {
  27365. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27366. this.node = targetObject;
  27367. }
  27368. // set fail state so we can just 'return' on error
  27369. this.getValue = this._getValue_unavailable;
  27370. this.setValue = this._setValue_unavailable;
  27371. // ensure there is a value node
  27372. if ( ! targetObject ) {
  27373. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27374. return;
  27375. }
  27376. if ( objectName ) {
  27377. let objectIndex = parsedPath.objectIndex;
  27378. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27379. switch ( objectName ) {
  27380. case 'materials':
  27381. if ( ! targetObject.material ) {
  27382. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27383. return;
  27384. }
  27385. if ( ! targetObject.material.materials ) {
  27386. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27387. return;
  27388. }
  27389. targetObject = targetObject.material.materials;
  27390. break;
  27391. case 'bones':
  27392. if ( ! targetObject.skeleton ) {
  27393. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27394. return;
  27395. }
  27396. // potential future optimization: skip this if propertyIndex is already an integer
  27397. // and convert the integer string to a true integer.
  27398. targetObject = targetObject.skeleton.bones;
  27399. // support resolving morphTarget names into indices.
  27400. for ( let i = 0; i < targetObject.length; i ++ ) {
  27401. if ( targetObject[ i ].name === objectIndex ) {
  27402. objectIndex = i;
  27403. break;
  27404. }
  27405. }
  27406. break;
  27407. case 'map':
  27408. if ( 'map' in targetObject ) {
  27409. targetObject = targetObject.map;
  27410. break;
  27411. }
  27412. if ( ! targetObject.material ) {
  27413. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27414. return;
  27415. }
  27416. if ( ! targetObject.material.map ) {
  27417. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27418. return;
  27419. }
  27420. targetObject = targetObject.material.map;
  27421. break;
  27422. default:
  27423. if ( targetObject[ objectName ] === undefined ) {
  27424. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27425. return;
  27426. }
  27427. targetObject = targetObject[ objectName ];
  27428. }
  27429. if ( objectIndex !== undefined ) {
  27430. if ( targetObject[ objectIndex ] === undefined ) {
  27431. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27432. return;
  27433. }
  27434. targetObject = targetObject[ objectIndex ];
  27435. }
  27436. }
  27437. // resolve property
  27438. const nodeProperty = targetObject[ propertyName ];
  27439. if ( nodeProperty === undefined ) {
  27440. const nodeName = parsedPath.nodeName;
  27441. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27442. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27443. return;
  27444. }
  27445. // determine versioning scheme
  27446. let versioning = this.Versioning.None;
  27447. this.targetObject = targetObject;
  27448. if ( targetObject.needsUpdate !== undefined ) { // material
  27449. versioning = this.Versioning.NeedsUpdate;
  27450. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27451. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27452. }
  27453. // determine how the property gets bound
  27454. let bindingType = this.BindingType.Direct;
  27455. if ( propertyIndex !== undefined ) {
  27456. // access a sub element of the property array (only primitives are supported right now)
  27457. if ( propertyName === 'morphTargetInfluences' ) {
  27458. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27459. // support resolving morphTarget names into indices.
  27460. if ( ! targetObject.geometry ) {
  27461. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27462. return;
  27463. }
  27464. if ( ! targetObject.geometry.morphAttributes ) {
  27465. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27466. return;
  27467. }
  27468. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27469. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27470. }
  27471. }
  27472. bindingType = this.BindingType.ArrayElement;
  27473. this.resolvedProperty = nodeProperty;
  27474. this.propertyIndex = propertyIndex;
  27475. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27476. // must use copy for Object3D.Euler/Quaternion
  27477. bindingType = this.BindingType.HasFromToArray;
  27478. this.resolvedProperty = nodeProperty;
  27479. } else if ( Array.isArray( nodeProperty ) ) {
  27480. bindingType = this.BindingType.EntireArray;
  27481. this.resolvedProperty = nodeProperty;
  27482. } else {
  27483. this.propertyName = propertyName;
  27484. }
  27485. // select getter / setter
  27486. this.getValue = this.GetterByBindingType[ bindingType ];
  27487. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27488. }
  27489. unbind() {
  27490. this.node = null;
  27491. // back to the prototype version of getValue / setValue
  27492. // note: avoiding to mutate the shape of 'this' via 'delete'
  27493. this.getValue = this._getValue_unbound;
  27494. this.setValue = this._setValue_unbound;
  27495. }
  27496. }
  27497. PropertyBinding.Composite = Composite;
  27498. PropertyBinding.prototype.BindingType = {
  27499. Direct: 0,
  27500. EntireArray: 1,
  27501. ArrayElement: 2,
  27502. HasFromToArray: 3
  27503. };
  27504. PropertyBinding.prototype.Versioning = {
  27505. None: 0,
  27506. NeedsUpdate: 1,
  27507. MatrixWorldNeedsUpdate: 2
  27508. };
  27509. PropertyBinding.prototype.GetterByBindingType = [
  27510. PropertyBinding.prototype._getValue_direct,
  27511. PropertyBinding.prototype._getValue_array,
  27512. PropertyBinding.prototype._getValue_arrayElement,
  27513. PropertyBinding.prototype._getValue_toArray,
  27514. ];
  27515. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27516. [
  27517. // Direct
  27518. PropertyBinding.prototype._setValue_direct,
  27519. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27520. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27521. ], [
  27522. // EntireArray
  27523. PropertyBinding.prototype._setValue_array,
  27524. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27525. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27526. ], [
  27527. // ArrayElement
  27528. PropertyBinding.prototype._setValue_arrayElement,
  27529. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27530. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27531. ], [
  27532. // HasToFromArray
  27533. PropertyBinding.prototype._setValue_fromArray,
  27534. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27535. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27536. ]
  27537. ];
  27538. /**
  27539. *
  27540. * A group of objects that receives a shared animation state.
  27541. *
  27542. * Usage:
  27543. *
  27544. * - Add objects you would otherwise pass as 'root' to the
  27545. * constructor or the .clipAction method of AnimationMixer.
  27546. *
  27547. * - Instead pass this object as 'root'.
  27548. *
  27549. * - You can also add and remove objects later when the mixer
  27550. * is running.
  27551. *
  27552. * Note:
  27553. *
  27554. * Objects of this class appear as one object to the mixer,
  27555. * so cache control of the individual objects must be done
  27556. * on the group.
  27557. *
  27558. * Limitation:
  27559. *
  27560. * - The animated properties must be compatible among the
  27561. * all objects in the group.
  27562. *
  27563. * - A single property can either be controlled through a
  27564. * target group or directly, but not both.
  27565. */
  27566. class AnimationObjectGroup {
  27567. constructor() {
  27568. this.isAnimationObjectGroup = true;
  27569. this.uuid = generateUUID();
  27570. // cached objects followed by the active ones
  27571. this._objects = Array.prototype.slice.call( arguments );
  27572. this.nCachedObjects_ = 0; // threshold
  27573. // note: read by PropertyBinding.Composite
  27574. const indices = {};
  27575. this._indicesByUUID = indices; // for bookkeeping
  27576. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27577. indices[ arguments[ i ].uuid ] = i;
  27578. }
  27579. this._paths = []; // inside: string
  27580. this._parsedPaths = []; // inside: { we don't care, here }
  27581. this._bindings = []; // inside: Array< PropertyBinding >
  27582. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27583. const scope = this;
  27584. this.stats = {
  27585. objects: {
  27586. get total() {
  27587. return scope._objects.length;
  27588. },
  27589. get inUse() {
  27590. return this.total - scope.nCachedObjects_;
  27591. }
  27592. },
  27593. get bindingsPerObject() {
  27594. return scope._bindings.length;
  27595. }
  27596. };
  27597. }
  27598. add() {
  27599. const objects = this._objects,
  27600. indicesByUUID = this._indicesByUUID,
  27601. paths = this._paths,
  27602. parsedPaths = this._parsedPaths,
  27603. bindings = this._bindings,
  27604. nBindings = bindings.length;
  27605. let knownObject = undefined,
  27606. nObjects = objects.length,
  27607. nCachedObjects = this.nCachedObjects_;
  27608. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27609. const object = arguments[ i ],
  27610. uuid = object.uuid;
  27611. let index = indicesByUUID[ uuid ];
  27612. if ( index === undefined ) {
  27613. // unknown object -> add it to the ACTIVE region
  27614. index = nObjects ++;
  27615. indicesByUUID[ uuid ] = index;
  27616. objects.push( object );
  27617. // accounting is done, now do the same for all bindings
  27618. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27619. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27620. }
  27621. } else if ( index < nCachedObjects ) {
  27622. knownObject = objects[ index ];
  27623. // move existing object to the ACTIVE region
  27624. const firstActiveIndex = -- nCachedObjects,
  27625. lastCachedObject = objects[ firstActiveIndex ];
  27626. indicesByUUID[ lastCachedObject.uuid ] = index;
  27627. objects[ index ] = lastCachedObject;
  27628. indicesByUUID[ uuid ] = firstActiveIndex;
  27629. objects[ firstActiveIndex ] = object;
  27630. // accounting is done, now do the same for all bindings
  27631. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27632. const bindingsForPath = bindings[ j ],
  27633. lastCached = bindingsForPath[ firstActiveIndex ];
  27634. let binding = bindingsForPath[ index ];
  27635. bindingsForPath[ index ] = lastCached;
  27636. if ( binding === undefined ) {
  27637. // since we do not bother to create new bindings
  27638. // for objects that are cached, the binding may
  27639. // or may not exist
  27640. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27641. }
  27642. bindingsForPath[ firstActiveIndex ] = binding;
  27643. }
  27644. } else if ( objects[ index ] !== knownObject ) {
  27645. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27646. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27647. } // else the object is already where we want it to be
  27648. } // for arguments
  27649. this.nCachedObjects_ = nCachedObjects;
  27650. }
  27651. remove() {
  27652. const objects = this._objects,
  27653. indicesByUUID = this._indicesByUUID,
  27654. bindings = this._bindings,
  27655. nBindings = bindings.length;
  27656. let nCachedObjects = this.nCachedObjects_;
  27657. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27658. const object = arguments[ i ],
  27659. uuid = object.uuid,
  27660. index = indicesByUUID[ uuid ];
  27661. if ( index !== undefined && index >= nCachedObjects ) {
  27662. // move existing object into the CACHED region
  27663. const lastCachedIndex = nCachedObjects ++,
  27664. firstActiveObject = objects[ lastCachedIndex ];
  27665. indicesByUUID[ firstActiveObject.uuid ] = index;
  27666. objects[ index ] = firstActiveObject;
  27667. indicesByUUID[ uuid ] = lastCachedIndex;
  27668. objects[ lastCachedIndex ] = object;
  27669. // accounting is done, now do the same for all bindings
  27670. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27671. const bindingsForPath = bindings[ j ],
  27672. firstActive = bindingsForPath[ lastCachedIndex ],
  27673. binding = bindingsForPath[ index ];
  27674. bindingsForPath[ index ] = firstActive;
  27675. bindingsForPath[ lastCachedIndex ] = binding;
  27676. }
  27677. }
  27678. } // for arguments
  27679. this.nCachedObjects_ = nCachedObjects;
  27680. }
  27681. // remove & forget
  27682. uncache() {
  27683. const objects = this._objects,
  27684. indicesByUUID = this._indicesByUUID,
  27685. bindings = this._bindings,
  27686. nBindings = bindings.length;
  27687. let nCachedObjects = this.nCachedObjects_,
  27688. nObjects = objects.length;
  27689. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27690. const object = arguments[ i ],
  27691. uuid = object.uuid,
  27692. index = indicesByUUID[ uuid ];
  27693. if ( index !== undefined ) {
  27694. delete indicesByUUID[ uuid ];
  27695. if ( index < nCachedObjects ) {
  27696. // object is cached, shrink the CACHED region
  27697. const firstActiveIndex = -- nCachedObjects,
  27698. lastCachedObject = objects[ firstActiveIndex ],
  27699. lastIndex = -- nObjects,
  27700. lastObject = objects[ lastIndex ];
  27701. // last cached object takes this object's place
  27702. indicesByUUID[ lastCachedObject.uuid ] = index;
  27703. objects[ index ] = lastCachedObject;
  27704. // last object goes to the activated slot and pop
  27705. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27706. objects[ firstActiveIndex ] = lastObject;
  27707. objects.pop();
  27708. // accounting is done, now do the same for all bindings
  27709. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27710. const bindingsForPath = bindings[ j ],
  27711. lastCached = bindingsForPath[ firstActiveIndex ],
  27712. last = bindingsForPath[ lastIndex ];
  27713. bindingsForPath[ index ] = lastCached;
  27714. bindingsForPath[ firstActiveIndex ] = last;
  27715. bindingsForPath.pop();
  27716. }
  27717. } else {
  27718. // object is active, just swap with the last and pop
  27719. const lastIndex = -- nObjects,
  27720. lastObject = objects[ lastIndex ];
  27721. if ( lastIndex > 0 ) {
  27722. indicesByUUID[ lastObject.uuid ] = index;
  27723. }
  27724. objects[ index ] = lastObject;
  27725. objects.pop();
  27726. // accounting is done, now do the same for all bindings
  27727. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27728. const bindingsForPath = bindings[ j ];
  27729. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27730. bindingsForPath.pop();
  27731. }
  27732. } // cached or active
  27733. } // if object is known
  27734. } // for arguments
  27735. this.nCachedObjects_ = nCachedObjects;
  27736. }
  27737. // Internal interface used by befriended PropertyBinding.Composite:
  27738. subscribe_( path, parsedPath ) {
  27739. // returns an array of bindings for the given path that is changed
  27740. // according to the contained objects in the group
  27741. const indicesByPath = this._bindingsIndicesByPath;
  27742. let index = indicesByPath[ path ];
  27743. const bindings = this._bindings;
  27744. if ( index !== undefined ) return bindings[ index ];
  27745. const paths = this._paths,
  27746. parsedPaths = this._parsedPaths,
  27747. objects = this._objects,
  27748. nObjects = objects.length,
  27749. nCachedObjects = this.nCachedObjects_,
  27750. bindingsForPath = new Array( nObjects );
  27751. index = bindings.length;
  27752. indicesByPath[ path ] = index;
  27753. paths.push( path );
  27754. parsedPaths.push( parsedPath );
  27755. bindings.push( bindingsForPath );
  27756. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27757. const object = objects[ i ];
  27758. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27759. }
  27760. return bindingsForPath;
  27761. }
  27762. unsubscribe_( path ) {
  27763. // tells the group to forget about a property path and no longer
  27764. // update the array previously obtained with 'subscribe_'
  27765. const indicesByPath = this._bindingsIndicesByPath,
  27766. index = indicesByPath[ path ];
  27767. if ( index !== undefined ) {
  27768. const paths = this._paths,
  27769. parsedPaths = this._parsedPaths,
  27770. bindings = this._bindings,
  27771. lastBindingsIndex = bindings.length - 1,
  27772. lastBindings = bindings[ lastBindingsIndex ],
  27773. lastBindingsPath = path[ lastBindingsIndex ];
  27774. indicesByPath[ lastBindingsPath ] = index;
  27775. bindings[ index ] = lastBindings;
  27776. bindings.pop();
  27777. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27778. parsedPaths.pop();
  27779. paths[ index ] = paths[ lastBindingsIndex ];
  27780. paths.pop();
  27781. }
  27782. }
  27783. }
  27784. class AnimationAction {
  27785. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27786. this._mixer = mixer;
  27787. this._clip = clip;
  27788. this._localRoot = localRoot;
  27789. this.blendMode = blendMode;
  27790. const tracks = clip.tracks,
  27791. nTracks = tracks.length,
  27792. interpolants = new Array( nTracks );
  27793. const interpolantSettings = {
  27794. endingStart: ZeroCurvatureEnding,
  27795. endingEnd: ZeroCurvatureEnding
  27796. };
  27797. for ( let i = 0; i !== nTracks; ++ i ) {
  27798. const interpolant = tracks[ i ].createInterpolant( null );
  27799. interpolants[ i ] = interpolant;
  27800. interpolant.settings = interpolantSettings;
  27801. }
  27802. this._interpolantSettings = interpolantSettings;
  27803. this._interpolants = interpolants; // bound by the mixer
  27804. // inside: PropertyMixer (managed by the mixer)
  27805. this._propertyBindings = new Array( nTracks );
  27806. this._cacheIndex = null; // for the memory manager
  27807. this._byClipCacheIndex = null; // for the memory manager
  27808. this._timeScaleInterpolant = null;
  27809. this._weightInterpolant = null;
  27810. this.loop = LoopRepeat;
  27811. this._loopCount = - 1;
  27812. // global mixer time when the action is to be started
  27813. // it's set back to 'null' upon start of the action
  27814. this._startTime = null;
  27815. // scaled local time of the action
  27816. // gets clamped or wrapped to 0..clip.duration according to loop
  27817. this.time = 0;
  27818. this.timeScale = 1;
  27819. this._effectiveTimeScale = 1;
  27820. this.weight = 1;
  27821. this._effectiveWeight = 1;
  27822. this.repetitions = Infinity; // no. of repetitions when looping
  27823. this.paused = false; // true -> zero effective time scale
  27824. this.enabled = true; // false -> zero effective weight
  27825. this.clampWhenFinished = false;// keep feeding the last frame?
  27826. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27827. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27828. }
  27829. // State & Scheduling
  27830. play() {
  27831. this._mixer._activateAction( this );
  27832. return this;
  27833. }
  27834. stop() {
  27835. this._mixer._deactivateAction( this );
  27836. return this.reset();
  27837. }
  27838. reset() {
  27839. this.paused = false;
  27840. this.enabled = true;
  27841. this.time = 0; // restart clip
  27842. this._loopCount = - 1;// forget previous loops
  27843. this._startTime = null;// forget scheduling
  27844. return this.stopFading().stopWarping();
  27845. }
  27846. isRunning() {
  27847. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27848. this._startTime === null && this._mixer._isActiveAction( this );
  27849. }
  27850. // return true when play has been called
  27851. isScheduled() {
  27852. return this._mixer._isActiveAction( this );
  27853. }
  27854. startAt( time ) {
  27855. this._startTime = time;
  27856. return this;
  27857. }
  27858. setLoop( mode, repetitions ) {
  27859. this.loop = mode;
  27860. this.repetitions = repetitions;
  27861. return this;
  27862. }
  27863. // Weight
  27864. // set the weight stopping any scheduled fading
  27865. // although .enabled = false yields an effective weight of zero, this
  27866. // method does *not* change .enabled, because it would be confusing
  27867. setEffectiveWeight( weight ) {
  27868. this.weight = weight;
  27869. // note: same logic as when updated at runtime
  27870. this._effectiveWeight = this.enabled ? weight : 0;
  27871. return this.stopFading();
  27872. }
  27873. // return the weight considering fading and .enabled
  27874. getEffectiveWeight() {
  27875. return this._effectiveWeight;
  27876. }
  27877. fadeIn( duration ) {
  27878. return this._scheduleFading( duration, 0, 1 );
  27879. }
  27880. fadeOut( duration ) {
  27881. return this._scheduleFading( duration, 1, 0 );
  27882. }
  27883. crossFadeFrom( fadeOutAction, duration, warp ) {
  27884. fadeOutAction.fadeOut( duration );
  27885. this.fadeIn( duration );
  27886. if ( warp ) {
  27887. const fadeInDuration = this._clip.duration,
  27888. fadeOutDuration = fadeOutAction._clip.duration,
  27889. startEndRatio = fadeOutDuration / fadeInDuration,
  27890. endStartRatio = fadeInDuration / fadeOutDuration;
  27891. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27892. this.warp( endStartRatio, 1.0, duration );
  27893. }
  27894. return this;
  27895. }
  27896. crossFadeTo( fadeInAction, duration, warp ) {
  27897. return fadeInAction.crossFadeFrom( this, duration, warp );
  27898. }
  27899. stopFading() {
  27900. const weightInterpolant = this._weightInterpolant;
  27901. if ( weightInterpolant !== null ) {
  27902. this._weightInterpolant = null;
  27903. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27904. }
  27905. return this;
  27906. }
  27907. // Time Scale Control
  27908. // set the time scale stopping any scheduled warping
  27909. // although .paused = true yields an effective time scale of zero, this
  27910. // method does *not* change .paused, because it would be confusing
  27911. setEffectiveTimeScale( timeScale ) {
  27912. this.timeScale = timeScale;
  27913. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27914. return this.stopWarping();
  27915. }
  27916. // return the time scale considering warping and .paused
  27917. getEffectiveTimeScale() {
  27918. return this._effectiveTimeScale;
  27919. }
  27920. setDuration( duration ) {
  27921. this.timeScale = this._clip.duration / duration;
  27922. return this.stopWarping();
  27923. }
  27924. syncWith( action ) {
  27925. this.time = action.time;
  27926. this.timeScale = action.timeScale;
  27927. return this.stopWarping();
  27928. }
  27929. halt( duration ) {
  27930. return this.warp( this._effectiveTimeScale, 0, duration );
  27931. }
  27932. warp( startTimeScale, endTimeScale, duration ) {
  27933. const mixer = this._mixer,
  27934. now = mixer.time,
  27935. timeScale = this.timeScale;
  27936. let interpolant = this._timeScaleInterpolant;
  27937. if ( interpolant === null ) {
  27938. interpolant = mixer._lendControlInterpolant();
  27939. this._timeScaleInterpolant = interpolant;
  27940. }
  27941. const times = interpolant.parameterPositions,
  27942. values = interpolant.sampleValues;
  27943. times[ 0 ] = now;
  27944. times[ 1 ] = now + duration;
  27945. values[ 0 ] = startTimeScale / timeScale;
  27946. values[ 1 ] = endTimeScale / timeScale;
  27947. return this;
  27948. }
  27949. stopWarping() {
  27950. const timeScaleInterpolant = this._timeScaleInterpolant;
  27951. if ( timeScaleInterpolant !== null ) {
  27952. this._timeScaleInterpolant = null;
  27953. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27954. }
  27955. return this;
  27956. }
  27957. // Object Accessors
  27958. getMixer() {
  27959. return this._mixer;
  27960. }
  27961. getClip() {
  27962. return this._clip;
  27963. }
  27964. getRoot() {
  27965. return this._localRoot || this._mixer._root;
  27966. }
  27967. // Interna
  27968. _update( time, deltaTime, timeDirection, accuIndex ) {
  27969. // called by the mixer
  27970. if ( ! this.enabled ) {
  27971. // call ._updateWeight() to update ._effectiveWeight
  27972. this._updateWeight( time );
  27973. return;
  27974. }
  27975. const startTime = this._startTime;
  27976. if ( startTime !== null ) {
  27977. // check for scheduled start of action
  27978. const timeRunning = ( time - startTime ) * timeDirection;
  27979. if ( timeRunning < 0 || timeDirection === 0 ) {
  27980. deltaTime = 0;
  27981. } else {
  27982. this._startTime = null; // unschedule
  27983. deltaTime = timeDirection * timeRunning;
  27984. }
  27985. }
  27986. // apply time scale and advance time
  27987. deltaTime *= this._updateTimeScale( time );
  27988. const clipTime = this._updateTime( deltaTime );
  27989. // note: _updateTime may disable the action resulting in
  27990. // an effective weight of 0
  27991. const weight = this._updateWeight( time );
  27992. if ( weight > 0 ) {
  27993. const interpolants = this._interpolants;
  27994. const propertyMixers = this._propertyBindings;
  27995. switch ( this.blendMode ) {
  27996. case AdditiveAnimationBlendMode:
  27997. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27998. interpolants[ j ].evaluate( clipTime );
  27999. propertyMixers[ j ].accumulateAdditive( weight );
  28000. }
  28001. break;
  28002. case NormalAnimationBlendMode:
  28003. default:
  28004. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28005. interpolants[ j ].evaluate( clipTime );
  28006. propertyMixers[ j ].accumulate( accuIndex, weight );
  28007. }
  28008. }
  28009. }
  28010. }
  28011. _updateWeight( time ) {
  28012. let weight = 0;
  28013. if ( this.enabled ) {
  28014. weight = this.weight;
  28015. const interpolant = this._weightInterpolant;
  28016. if ( interpolant !== null ) {
  28017. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28018. weight *= interpolantValue;
  28019. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28020. this.stopFading();
  28021. if ( interpolantValue === 0 ) {
  28022. // faded out, disable
  28023. this.enabled = false;
  28024. }
  28025. }
  28026. }
  28027. }
  28028. this._effectiveWeight = weight;
  28029. return weight;
  28030. }
  28031. _updateTimeScale( time ) {
  28032. let timeScale = 0;
  28033. if ( ! this.paused ) {
  28034. timeScale = this.timeScale;
  28035. const interpolant = this._timeScaleInterpolant;
  28036. if ( interpolant !== null ) {
  28037. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28038. timeScale *= interpolantValue;
  28039. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28040. this.stopWarping();
  28041. if ( timeScale === 0 ) {
  28042. // motion has halted, pause
  28043. this.paused = true;
  28044. } else {
  28045. // warp done - apply final time scale
  28046. this.timeScale = timeScale;
  28047. }
  28048. }
  28049. }
  28050. }
  28051. this._effectiveTimeScale = timeScale;
  28052. return timeScale;
  28053. }
  28054. _updateTime( deltaTime ) {
  28055. const duration = this._clip.duration;
  28056. const loop = this.loop;
  28057. let time = this.time + deltaTime;
  28058. let loopCount = this._loopCount;
  28059. const pingPong = ( loop === LoopPingPong );
  28060. if ( deltaTime === 0 ) {
  28061. if ( loopCount === - 1 ) return time;
  28062. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  28063. }
  28064. if ( loop === LoopOnce ) {
  28065. if ( loopCount === - 1 ) {
  28066. // just started
  28067. this._loopCount = 0;
  28068. this._setEndings( true, true, false );
  28069. }
  28070. handle_stop: {
  28071. if ( time >= duration ) {
  28072. time = duration;
  28073. } else if ( time < 0 ) {
  28074. time = 0;
  28075. } else {
  28076. this.time = time;
  28077. break handle_stop;
  28078. }
  28079. if ( this.clampWhenFinished ) this.paused = true;
  28080. else this.enabled = false;
  28081. this.time = time;
  28082. this._mixer.dispatchEvent( {
  28083. type: 'finished', action: this,
  28084. direction: deltaTime < 0 ? - 1 : 1
  28085. } );
  28086. }
  28087. } else { // repetitive Repeat or PingPong
  28088. if ( loopCount === - 1 ) {
  28089. // just started
  28090. if ( deltaTime >= 0 ) {
  28091. loopCount = 0;
  28092. this._setEndings( true, this.repetitions === 0, pingPong );
  28093. } else {
  28094. // when looping in reverse direction, the initial
  28095. // transition through zero counts as a repetition,
  28096. // so leave loopCount at -1
  28097. this._setEndings( this.repetitions === 0, true, pingPong );
  28098. }
  28099. }
  28100. if ( time >= duration || time < 0 ) {
  28101. // wrap around
  28102. const loopDelta = Math.floor( time / duration ); // signed
  28103. time -= duration * loopDelta;
  28104. loopCount += Math.abs( loopDelta );
  28105. const pending = this.repetitions - loopCount;
  28106. if ( pending <= 0 ) {
  28107. // have to stop (switch state, clamp time, fire event)
  28108. if ( this.clampWhenFinished ) this.paused = true;
  28109. else this.enabled = false;
  28110. time = deltaTime > 0 ? duration : 0;
  28111. this.time = time;
  28112. this._mixer.dispatchEvent( {
  28113. type: 'finished', action: this,
  28114. direction: deltaTime > 0 ? 1 : - 1
  28115. } );
  28116. } else {
  28117. // keep running
  28118. if ( pending === 1 ) {
  28119. // entering the last round
  28120. const atStart = deltaTime < 0;
  28121. this._setEndings( atStart, ! atStart, pingPong );
  28122. } else {
  28123. this._setEndings( false, false, pingPong );
  28124. }
  28125. this._loopCount = loopCount;
  28126. this.time = time;
  28127. this._mixer.dispatchEvent( {
  28128. type: 'loop', action: this, loopDelta: loopDelta
  28129. } );
  28130. }
  28131. } else {
  28132. this.time = time;
  28133. }
  28134. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28135. // invert time for the "pong round"
  28136. return duration - time;
  28137. }
  28138. }
  28139. return time;
  28140. }
  28141. _setEndings( atStart, atEnd, pingPong ) {
  28142. const settings = this._interpolantSettings;
  28143. if ( pingPong ) {
  28144. settings.endingStart = ZeroSlopeEnding;
  28145. settings.endingEnd = ZeroSlopeEnding;
  28146. } else {
  28147. // assuming for LoopOnce atStart == atEnd == true
  28148. if ( atStart ) {
  28149. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28150. } else {
  28151. settings.endingStart = WrapAroundEnding;
  28152. }
  28153. if ( atEnd ) {
  28154. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28155. } else {
  28156. settings.endingEnd = WrapAroundEnding;
  28157. }
  28158. }
  28159. }
  28160. _scheduleFading( duration, weightNow, weightThen ) {
  28161. const mixer = this._mixer, now = mixer.time;
  28162. let interpolant = this._weightInterpolant;
  28163. if ( interpolant === null ) {
  28164. interpolant = mixer._lendControlInterpolant();
  28165. this._weightInterpolant = interpolant;
  28166. }
  28167. const times = interpolant.parameterPositions,
  28168. values = interpolant.sampleValues;
  28169. times[ 0 ] = now;
  28170. values[ 0 ] = weightNow;
  28171. times[ 1 ] = now + duration;
  28172. values[ 1 ] = weightThen;
  28173. return this;
  28174. }
  28175. }
  28176. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  28177. class AnimationMixer extends EventDispatcher {
  28178. constructor( root ) {
  28179. super();
  28180. this._root = root;
  28181. this._initMemoryManager();
  28182. this._accuIndex = 0;
  28183. this.time = 0;
  28184. this.timeScale = 1.0;
  28185. }
  28186. _bindAction( action, prototypeAction ) {
  28187. const root = action._localRoot || this._root,
  28188. tracks = action._clip.tracks,
  28189. nTracks = tracks.length,
  28190. bindings = action._propertyBindings,
  28191. interpolants = action._interpolants,
  28192. rootUuid = root.uuid,
  28193. bindingsByRoot = this._bindingsByRootAndName;
  28194. let bindingsByName = bindingsByRoot[ rootUuid ];
  28195. if ( bindingsByName === undefined ) {
  28196. bindingsByName = {};
  28197. bindingsByRoot[ rootUuid ] = bindingsByName;
  28198. }
  28199. for ( let i = 0; i !== nTracks; ++ i ) {
  28200. const track = tracks[ i ],
  28201. trackName = track.name;
  28202. let binding = bindingsByName[ trackName ];
  28203. if ( binding !== undefined ) {
  28204. ++ binding.referenceCount;
  28205. bindings[ i ] = binding;
  28206. } else {
  28207. binding = bindings[ i ];
  28208. if ( binding !== undefined ) {
  28209. // existing binding, make sure the cache knows
  28210. if ( binding._cacheIndex === null ) {
  28211. ++ binding.referenceCount;
  28212. this._addInactiveBinding( binding, rootUuid, trackName );
  28213. }
  28214. continue;
  28215. }
  28216. const path = prototypeAction && prototypeAction.
  28217. _propertyBindings[ i ].binding.parsedPath;
  28218. binding = new PropertyMixer(
  28219. PropertyBinding.create( root, trackName, path ),
  28220. track.ValueTypeName, track.getValueSize() );
  28221. ++ binding.referenceCount;
  28222. this._addInactiveBinding( binding, rootUuid, trackName );
  28223. bindings[ i ] = binding;
  28224. }
  28225. interpolants[ i ].resultBuffer = binding.buffer;
  28226. }
  28227. }
  28228. _activateAction( action ) {
  28229. if ( ! this._isActiveAction( action ) ) {
  28230. if ( action._cacheIndex === null ) {
  28231. // this action has been forgotten by the cache, but the user
  28232. // appears to be still using it -> rebind
  28233. const rootUuid = ( action._localRoot || this._root ).uuid,
  28234. clipUuid = action._clip.uuid,
  28235. actionsForClip = this._actionsByClip[ clipUuid ];
  28236. this._bindAction( action,
  28237. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28238. this._addInactiveAction( action, clipUuid, rootUuid );
  28239. }
  28240. const bindings = action._propertyBindings;
  28241. // increment reference counts / sort out state
  28242. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28243. const binding = bindings[ i ];
  28244. if ( binding.useCount ++ === 0 ) {
  28245. this._lendBinding( binding );
  28246. binding.saveOriginalState();
  28247. }
  28248. }
  28249. this._lendAction( action );
  28250. }
  28251. }
  28252. _deactivateAction( action ) {
  28253. if ( this._isActiveAction( action ) ) {
  28254. const bindings = action._propertyBindings;
  28255. // decrement reference counts / sort out state
  28256. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28257. const binding = bindings[ i ];
  28258. if ( -- binding.useCount === 0 ) {
  28259. binding.restoreOriginalState();
  28260. this._takeBackBinding( binding );
  28261. }
  28262. }
  28263. this._takeBackAction( action );
  28264. }
  28265. }
  28266. // Memory manager
  28267. _initMemoryManager() {
  28268. this._actions = []; // 'nActiveActions' followed by inactive ones
  28269. this._nActiveActions = 0;
  28270. this._actionsByClip = {};
  28271. // inside:
  28272. // {
  28273. // knownActions: Array< AnimationAction > - used as prototypes
  28274. // actionByRoot: AnimationAction - lookup
  28275. // }
  28276. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28277. this._nActiveBindings = 0;
  28278. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28279. this._controlInterpolants = []; // same game as above
  28280. this._nActiveControlInterpolants = 0;
  28281. const scope = this;
  28282. this.stats = {
  28283. actions: {
  28284. get total() {
  28285. return scope._actions.length;
  28286. },
  28287. get inUse() {
  28288. return scope._nActiveActions;
  28289. }
  28290. },
  28291. bindings: {
  28292. get total() {
  28293. return scope._bindings.length;
  28294. },
  28295. get inUse() {
  28296. return scope._nActiveBindings;
  28297. }
  28298. },
  28299. controlInterpolants: {
  28300. get total() {
  28301. return scope._controlInterpolants.length;
  28302. },
  28303. get inUse() {
  28304. return scope._nActiveControlInterpolants;
  28305. }
  28306. }
  28307. };
  28308. }
  28309. // Memory management for AnimationAction objects
  28310. _isActiveAction( action ) {
  28311. const index = action._cacheIndex;
  28312. return index !== null && index < this._nActiveActions;
  28313. }
  28314. _addInactiveAction( action, clipUuid, rootUuid ) {
  28315. const actions = this._actions,
  28316. actionsByClip = this._actionsByClip;
  28317. let actionsForClip = actionsByClip[ clipUuid ];
  28318. if ( actionsForClip === undefined ) {
  28319. actionsForClip = {
  28320. knownActions: [ action ],
  28321. actionByRoot: {}
  28322. };
  28323. action._byClipCacheIndex = 0;
  28324. actionsByClip[ clipUuid ] = actionsForClip;
  28325. } else {
  28326. const knownActions = actionsForClip.knownActions;
  28327. action._byClipCacheIndex = knownActions.length;
  28328. knownActions.push( action );
  28329. }
  28330. action._cacheIndex = actions.length;
  28331. actions.push( action );
  28332. actionsForClip.actionByRoot[ rootUuid ] = action;
  28333. }
  28334. _removeInactiveAction( action ) {
  28335. const actions = this._actions,
  28336. lastInactiveAction = actions[ actions.length - 1 ],
  28337. cacheIndex = action._cacheIndex;
  28338. lastInactiveAction._cacheIndex = cacheIndex;
  28339. actions[ cacheIndex ] = lastInactiveAction;
  28340. actions.pop();
  28341. action._cacheIndex = null;
  28342. const clipUuid = action._clip.uuid,
  28343. actionsByClip = this._actionsByClip,
  28344. actionsForClip = actionsByClip[ clipUuid ],
  28345. knownActionsForClip = actionsForClip.knownActions,
  28346. lastKnownAction =
  28347. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28348. byClipCacheIndex = action._byClipCacheIndex;
  28349. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28350. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28351. knownActionsForClip.pop();
  28352. action._byClipCacheIndex = null;
  28353. const actionByRoot = actionsForClip.actionByRoot,
  28354. rootUuid = ( action._localRoot || this._root ).uuid;
  28355. delete actionByRoot[ rootUuid ];
  28356. if ( knownActionsForClip.length === 0 ) {
  28357. delete actionsByClip[ clipUuid ];
  28358. }
  28359. this._removeInactiveBindingsForAction( action );
  28360. }
  28361. _removeInactiveBindingsForAction( action ) {
  28362. const bindings = action._propertyBindings;
  28363. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28364. const binding = bindings[ i ];
  28365. if ( -- binding.referenceCount === 0 ) {
  28366. this._removeInactiveBinding( binding );
  28367. }
  28368. }
  28369. }
  28370. _lendAction( action ) {
  28371. // [ active actions | inactive actions ]
  28372. // [ active actions >| inactive actions ]
  28373. // s a
  28374. // <-swap->
  28375. // a s
  28376. const actions = this._actions,
  28377. prevIndex = action._cacheIndex,
  28378. lastActiveIndex = this._nActiveActions ++,
  28379. firstInactiveAction = actions[ lastActiveIndex ];
  28380. action._cacheIndex = lastActiveIndex;
  28381. actions[ lastActiveIndex ] = action;
  28382. firstInactiveAction._cacheIndex = prevIndex;
  28383. actions[ prevIndex ] = firstInactiveAction;
  28384. }
  28385. _takeBackAction( action ) {
  28386. // [ active actions | inactive actions ]
  28387. // [ active actions |< inactive actions ]
  28388. // a s
  28389. // <-swap->
  28390. // s a
  28391. const actions = this._actions,
  28392. prevIndex = action._cacheIndex,
  28393. firstInactiveIndex = -- this._nActiveActions,
  28394. lastActiveAction = actions[ firstInactiveIndex ];
  28395. action._cacheIndex = firstInactiveIndex;
  28396. actions[ firstInactiveIndex ] = action;
  28397. lastActiveAction._cacheIndex = prevIndex;
  28398. actions[ prevIndex ] = lastActiveAction;
  28399. }
  28400. // Memory management for PropertyMixer objects
  28401. _addInactiveBinding( binding, rootUuid, trackName ) {
  28402. const bindingsByRoot = this._bindingsByRootAndName,
  28403. bindings = this._bindings;
  28404. let bindingByName = bindingsByRoot[ rootUuid ];
  28405. if ( bindingByName === undefined ) {
  28406. bindingByName = {};
  28407. bindingsByRoot[ rootUuid ] = bindingByName;
  28408. }
  28409. bindingByName[ trackName ] = binding;
  28410. binding._cacheIndex = bindings.length;
  28411. bindings.push( binding );
  28412. }
  28413. _removeInactiveBinding( binding ) {
  28414. const bindings = this._bindings,
  28415. propBinding = binding.binding,
  28416. rootUuid = propBinding.rootNode.uuid,
  28417. trackName = propBinding.path,
  28418. bindingsByRoot = this._bindingsByRootAndName,
  28419. bindingByName = bindingsByRoot[ rootUuid ],
  28420. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28421. cacheIndex = binding._cacheIndex;
  28422. lastInactiveBinding._cacheIndex = cacheIndex;
  28423. bindings[ cacheIndex ] = lastInactiveBinding;
  28424. bindings.pop();
  28425. delete bindingByName[ trackName ];
  28426. if ( Object.keys( bindingByName ).length === 0 ) {
  28427. delete bindingsByRoot[ rootUuid ];
  28428. }
  28429. }
  28430. _lendBinding( binding ) {
  28431. const bindings = this._bindings,
  28432. prevIndex = binding._cacheIndex,
  28433. lastActiveIndex = this._nActiveBindings ++,
  28434. firstInactiveBinding = bindings[ lastActiveIndex ];
  28435. binding._cacheIndex = lastActiveIndex;
  28436. bindings[ lastActiveIndex ] = binding;
  28437. firstInactiveBinding._cacheIndex = prevIndex;
  28438. bindings[ prevIndex ] = firstInactiveBinding;
  28439. }
  28440. _takeBackBinding( binding ) {
  28441. const bindings = this._bindings,
  28442. prevIndex = binding._cacheIndex,
  28443. firstInactiveIndex = -- this._nActiveBindings,
  28444. lastActiveBinding = bindings[ firstInactiveIndex ];
  28445. binding._cacheIndex = firstInactiveIndex;
  28446. bindings[ firstInactiveIndex ] = binding;
  28447. lastActiveBinding._cacheIndex = prevIndex;
  28448. bindings[ prevIndex ] = lastActiveBinding;
  28449. }
  28450. // Memory management of Interpolants for weight and time scale
  28451. _lendControlInterpolant() {
  28452. const interpolants = this._controlInterpolants,
  28453. lastActiveIndex = this._nActiveControlInterpolants ++;
  28454. let interpolant = interpolants[ lastActiveIndex ];
  28455. if ( interpolant === undefined ) {
  28456. interpolant = new LinearInterpolant(
  28457. new Float32Array( 2 ), new Float32Array( 2 ),
  28458. 1, _controlInterpolantsResultBuffer );
  28459. interpolant.__cacheIndex = lastActiveIndex;
  28460. interpolants[ lastActiveIndex ] = interpolant;
  28461. }
  28462. return interpolant;
  28463. }
  28464. _takeBackControlInterpolant( interpolant ) {
  28465. const interpolants = this._controlInterpolants,
  28466. prevIndex = interpolant.__cacheIndex,
  28467. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28468. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28469. interpolant.__cacheIndex = firstInactiveIndex;
  28470. interpolants[ firstInactiveIndex ] = interpolant;
  28471. lastActiveInterpolant.__cacheIndex = prevIndex;
  28472. interpolants[ prevIndex ] = lastActiveInterpolant;
  28473. }
  28474. // return an action for a clip optionally using a custom root target
  28475. // object (this method allocates a lot of dynamic memory in case a
  28476. // previously unknown clip/root combination is specified)
  28477. clipAction( clip, optionalRoot, blendMode ) {
  28478. const root = optionalRoot || this._root,
  28479. rootUuid = root.uuid;
  28480. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28481. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28482. const actionsForClip = this._actionsByClip[ clipUuid ];
  28483. let prototypeAction = null;
  28484. if ( blendMode === undefined ) {
  28485. if ( clipObject !== null ) {
  28486. blendMode = clipObject.blendMode;
  28487. } else {
  28488. blendMode = NormalAnimationBlendMode;
  28489. }
  28490. }
  28491. if ( actionsForClip !== undefined ) {
  28492. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28493. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28494. return existingAction;
  28495. }
  28496. // we know the clip, so we don't have to parse all
  28497. // the bindings again but can just copy
  28498. prototypeAction = actionsForClip.knownActions[ 0 ];
  28499. // also, take the clip from the prototype action
  28500. if ( clipObject === null )
  28501. clipObject = prototypeAction._clip;
  28502. }
  28503. // clip must be known when specified via string
  28504. if ( clipObject === null ) return null;
  28505. // allocate all resources required to run it
  28506. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28507. this._bindAction( newAction, prototypeAction );
  28508. // and make the action known to the memory manager
  28509. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28510. return newAction;
  28511. }
  28512. // get an existing action
  28513. existingAction( clip, optionalRoot ) {
  28514. const root = optionalRoot || this._root,
  28515. rootUuid = root.uuid,
  28516. clipObject = typeof clip === 'string' ?
  28517. AnimationClip.findByName( root, clip ) : clip,
  28518. clipUuid = clipObject ? clipObject.uuid : clip,
  28519. actionsForClip = this._actionsByClip[ clipUuid ];
  28520. if ( actionsForClip !== undefined ) {
  28521. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28522. }
  28523. return null;
  28524. }
  28525. // deactivates all previously scheduled actions
  28526. stopAllAction() {
  28527. const actions = this._actions,
  28528. nActions = this._nActiveActions;
  28529. for ( let i = nActions - 1; i >= 0; -- i ) {
  28530. actions[ i ].stop();
  28531. }
  28532. return this;
  28533. }
  28534. // advance the time and update apply the animation
  28535. update( deltaTime ) {
  28536. deltaTime *= this.timeScale;
  28537. const actions = this._actions,
  28538. nActions = this._nActiveActions,
  28539. time = this.time += deltaTime,
  28540. timeDirection = Math.sign( deltaTime ),
  28541. accuIndex = this._accuIndex ^= 1;
  28542. // run active actions
  28543. for ( let i = 0; i !== nActions; ++ i ) {
  28544. const action = actions[ i ];
  28545. action._update( time, deltaTime, timeDirection, accuIndex );
  28546. }
  28547. // update scene graph
  28548. const bindings = this._bindings,
  28549. nBindings = this._nActiveBindings;
  28550. for ( let i = 0; i !== nBindings; ++ i ) {
  28551. bindings[ i ].apply( accuIndex );
  28552. }
  28553. return this;
  28554. }
  28555. // Allows you to seek to a specific time in an animation.
  28556. setTime( timeInSeconds ) {
  28557. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28558. for ( let i = 0; i < this._actions.length; i ++ ) {
  28559. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28560. }
  28561. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28562. }
  28563. // return this mixer's root target object
  28564. getRoot() {
  28565. return this._root;
  28566. }
  28567. // free all resources specific to a particular clip
  28568. uncacheClip( clip ) {
  28569. const actions = this._actions,
  28570. clipUuid = clip.uuid,
  28571. actionsByClip = this._actionsByClip,
  28572. actionsForClip = actionsByClip[ clipUuid ];
  28573. if ( actionsForClip !== undefined ) {
  28574. // note: just calling _removeInactiveAction would mess up the
  28575. // iteration state and also require updating the state we can
  28576. // just throw away
  28577. const actionsToRemove = actionsForClip.knownActions;
  28578. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28579. const action = actionsToRemove[ i ];
  28580. this._deactivateAction( action );
  28581. const cacheIndex = action._cacheIndex,
  28582. lastInactiveAction = actions[ actions.length - 1 ];
  28583. action._cacheIndex = null;
  28584. action._byClipCacheIndex = null;
  28585. lastInactiveAction._cacheIndex = cacheIndex;
  28586. actions[ cacheIndex ] = lastInactiveAction;
  28587. actions.pop();
  28588. this._removeInactiveBindingsForAction( action );
  28589. }
  28590. delete actionsByClip[ clipUuid ];
  28591. }
  28592. }
  28593. // free all resources specific to a particular root target object
  28594. uncacheRoot( root ) {
  28595. const rootUuid = root.uuid,
  28596. actionsByClip = this._actionsByClip;
  28597. for ( const clipUuid in actionsByClip ) {
  28598. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28599. action = actionByRoot[ rootUuid ];
  28600. if ( action !== undefined ) {
  28601. this._deactivateAction( action );
  28602. this._removeInactiveAction( action );
  28603. }
  28604. }
  28605. const bindingsByRoot = this._bindingsByRootAndName,
  28606. bindingByName = bindingsByRoot[ rootUuid ];
  28607. if ( bindingByName !== undefined ) {
  28608. for ( const trackName in bindingByName ) {
  28609. const binding = bindingByName[ trackName ];
  28610. binding.restoreOriginalState();
  28611. this._removeInactiveBinding( binding );
  28612. }
  28613. }
  28614. }
  28615. // remove a targeted clip from the cache
  28616. uncacheAction( clip, optionalRoot ) {
  28617. const action = this.existingAction( clip, optionalRoot );
  28618. if ( action !== null ) {
  28619. this._deactivateAction( action );
  28620. this._removeInactiveAction( action );
  28621. }
  28622. }
  28623. }
  28624. class Uniform {
  28625. constructor( value ) {
  28626. this.value = value;
  28627. }
  28628. clone() {
  28629. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28630. }
  28631. }
  28632. let id = 0;
  28633. class UniformsGroup extends EventDispatcher {
  28634. constructor() {
  28635. super();
  28636. this.isUniformsGroup = true;
  28637. Object.defineProperty( this, 'id', { value: id ++ } );
  28638. this.name = '';
  28639. this.usage = StaticDrawUsage;
  28640. this.uniforms = [];
  28641. }
  28642. add( uniform ) {
  28643. this.uniforms.push( uniform );
  28644. return this;
  28645. }
  28646. remove( uniform ) {
  28647. const index = this.uniforms.indexOf( uniform );
  28648. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28649. return this;
  28650. }
  28651. setName( name ) {
  28652. this.name = name;
  28653. return this;
  28654. }
  28655. setUsage( value ) {
  28656. this.usage = value;
  28657. return this;
  28658. }
  28659. dispose() {
  28660. this.dispatchEvent( { type: 'dispose' } );
  28661. return this;
  28662. }
  28663. copy( source ) {
  28664. this.name = source.name;
  28665. this.usage = source.usage;
  28666. const uniformsSource = source.uniforms;
  28667. this.uniforms.length = 0;
  28668. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28669. this.uniforms.push( uniformsSource[ i ].clone() );
  28670. }
  28671. return this;
  28672. }
  28673. clone() {
  28674. return new this.constructor().copy( this );
  28675. }
  28676. }
  28677. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28678. constructor( array, stride, meshPerAttribute = 1 ) {
  28679. super( array, stride );
  28680. this.isInstancedInterleavedBuffer = true;
  28681. this.meshPerAttribute = meshPerAttribute;
  28682. }
  28683. copy( source ) {
  28684. super.copy( source );
  28685. this.meshPerAttribute = source.meshPerAttribute;
  28686. return this;
  28687. }
  28688. clone( data ) {
  28689. const ib = super.clone( data );
  28690. ib.meshPerAttribute = this.meshPerAttribute;
  28691. return ib;
  28692. }
  28693. toJSON( data ) {
  28694. const json = super.toJSON( data );
  28695. json.isInstancedInterleavedBuffer = true;
  28696. json.meshPerAttribute = this.meshPerAttribute;
  28697. return json;
  28698. }
  28699. }
  28700. class GLBufferAttribute {
  28701. constructor( buffer, type, itemSize, elementSize, count ) {
  28702. this.isGLBufferAttribute = true;
  28703. this.name = '';
  28704. this.buffer = buffer;
  28705. this.type = type;
  28706. this.itemSize = itemSize;
  28707. this.elementSize = elementSize;
  28708. this.count = count;
  28709. this.version = 0;
  28710. }
  28711. set needsUpdate( value ) {
  28712. if ( value === true ) this.version ++;
  28713. }
  28714. setBuffer( buffer ) {
  28715. this.buffer = buffer;
  28716. return this;
  28717. }
  28718. setType( type, elementSize ) {
  28719. this.type = type;
  28720. this.elementSize = elementSize;
  28721. return this;
  28722. }
  28723. setItemSize( itemSize ) {
  28724. this.itemSize = itemSize;
  28725. return this;
  28726. }
  28727. setCount( count ) {
  28728. this.count = count;
  28729. return this;
  28730. }
  28731. }
  28732. class Raycaster {
  28733. constructor( origin, direction, near = 0, far = Infinity ) {
  28734. this.ray = new Ray( origin, direction );
  28735. // direction is assumed to be normalized (for accurate distance calculations)
  28736. this.near = near;
  28737. this.far = far;
  28738. this.camera = null;
  28739. this.layers = new Layers();
  28740. this.params = {
  28741. Mesh: {},
  28742. Line: { threshold: 1 },
  28743. LOD: {},
  28744. Points: { threshold: 1 },
  28745. Sprite: {}
  28746. };
  28747. }
  28748. set( origin, direction ) {
  28749. // direction is assumed to be normalized (for accurate distance calculations)
  28750. this.ray.set( origin, direction );
  28751. }
  28752. setFromCamera( coords, camera ) {
  28753. if ( camera.isPerspectiveCamera ) {
  28754. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28755. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28756. this.camera = camera;
  28757. } else if ( camera.isOrthographicCamera ) {
  28758. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28759. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28760. this.camera = camera;
  28761. } else {
  28762. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28763. }
  28764. }
  28765. intersectObject( object, recursive = true, intersects = [] ) {
  28766. intersectObject( object, this, intersects, recursive );
  28767. intersects.sort( ascSort );
  28768. return intersects;
  28769. }
  28770. intersectObjects( objects, recursive = true, intersects = [] ) {
  28771. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28772. intersectObject( objects[ i ], this, intersects, recursive );
  28773. }
  28774. intersects.sort( ascSort );
  28775. return intersects;
  28776. }
  28777. }
  28778. function ascSort( a, b ) {
  28779. return a.distance - b.distance;
  28780. }
  28781. function intersectObject( object, raycaster, intersects, recursive ) {
  28782. if ( object.layers.test( raycaster.layers ) ) {
  28783. object.raycast( raycaster, intersects );
  28784. }
  28785. if ( recursive === true ) {
  28786. const children = object.children;
  28787. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28788. intersectObject( children[ i ], raycaster, intersects, true );
  28789. }
  28790. }
  28791. }
  28792. /**
  28793. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28794. *
  28795. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28796. * The azimuthal angle (theta) is measured from the positive z-axis.
  28797. */
  28798. class Spherical {
  28799. constructor( radius = 1, phi = 0, theta = 0 ) {
  28800. this.radius = radius;
  28801. this.phi = phi; // polar angle
  28802. this.theta = theta; // azimuthal angle
  28803. return this;
  28804. }
  28805. set( radius, phi, theta ) {
  28806. this.radius = radius;
  28807. this.phi = phi;
  28808. this.theta = theta;
  28809. return this;
  28810. }
  28811. copy( other ) {
  28812. this.radius = other.radius;
  28813. this.phi = other.phi;
  28814. this.theta = other.theta;
  28815. return this;
  28816. }
  28817. // restrict phi to be between EPS and PI-EPS
  28818. makeSafe() {
  28819. const EPS = 0.000001;
  28820. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28821. return this;
  28822. }
  28823. setFromVector3( v ) {
  28824. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28825. }
  28826. setFromCartesianCoords( x, y, z ) {
  28827. this.radius = Math.sqrt( x * x + y * y + z * z );
  28828. if ( this.radius === 0 ) {
  28829. this.theta = 0;
  28830. this.phi = 0;
  28831. } else {
  28832. this.theta = Math.atan2( x, z );
  28833. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28834. }
  28835. return this;
  28836. }
  28837. clone() {
  28838. return new this.constructor().copy( this );
  28839. }
  28840. }
  28841. /**
  28842. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28843. */
  28844. class Cylindrical {
  28845. constructor( radius = 1, theta = 0, y = 0 ) {
  28846. this.radius = radius; // distance from the origin to a point in the x-z plane
  28847. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28848. this.y = y; // height above the x-z plane
  28849. return this;
  28850. }
  28851. set( radius, theta, y ) {
  28852. this.radius = radius;
  28853. this.theta = theta;
  28854. this.y = y;
  28855. return this;
  28856. }
  28857. copy( other ) {
  28858. this.radius = other.radius;
  28859. this.theta = other.theta;
  28860. this.y = other.y;
  28861. return this;
  28862. }
  28863. setFromVector3( v ) {
  28864. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28865. }
  28866. setFromCartesianCoords( x, y, z ) {
  28867. this.radius = Math.sqrt( x * x + z * z );
  28868. this.theta = Math.atan2( x, z );
  28869. this.y = y;
  28870. return this;
  28871. }
  28872. clone() {
  28873. return new this.constructor().copy( this );
  28874. }
  28875. }
  28876. const _vector$4 = /*@__PURE__*/ new Vector2();
  28877. class Box2 {
  28878. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28879. this.isBox2 = true;
  28880. this.min = min;
  28881. this.max = max;
  28882. }
  28883. set( min, max ) {
  28884. this.min.copy( min );
  28885. this.max.copy( max );
  28886. return this;
  28887. }
  28888. setFromPoints( points ) {
  28889. this.makeEmpty();
  28890. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28891. this.expandByPoint( points[ i ] );
  28892. }
  28893. return this;
  28894. }
  28895. setFromCenterAndSize( center, size ) {
  28896. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28897. this.min.copy( center ).sub( halfSize );
  28898. this.max.copy( center ).add( halfSize );
  28899. return this;
  28900. }
  28901. clone() {
  28902. return new this.constructor().copy( this );
  28903. }
  28904. copy( box ) {
  28905. this.min.copy( box.min );
  28906. this.max.copy( box.max );
  28907. return this;
  28908. }
  28909. makeEmpty() {
  28910. this.min.x = this.min.y = + Infinity;
  28911. this.max.x = this.max.y = - Infinity;
  28912. return this;
  28913. }
  28914. isEmpty() {
  28915. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28916. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28917. }
  28918. getCenter( target ) {
  28919. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28920. }
  28921. getSize( target ) {
  28922. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28923. }
  28924. expandByPoint( point ) {
  28925. this.min.min( point );
  28926. this.max.max( point );
  28927. return this;
  28928. }
  28929. expandByVector( vector ) {
  28930. this.min.sub( vector );
  28931. this.max.add( vector );
  28932. return this;
  28933. }
  28934. expandByScalar( scalar ) {
  28935. this.min.addScalar( - scalar );
  28936. this.max.addScalar( scalar );
  28937. return this;
  28938. }
  28939. containsPoint( point ) {
  28940. return point.x < this.min.x || point.x > this.max.x ||
  28941. point.y < this.min.y || point.y > this.max.y ? false : true;
  28942. }
  28943. containsBox( box ) {
  28944. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28945. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28946. }
  28947. getParameter( point, target ) {
  28948. // This can potentially have a divide by zero if the box
  28949. // has a size dimension of 0.
  28950. return target.set(
  28951. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28952. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28953. );
  28954. }
  28955. intersectsBox( box ) {
  28956. // using 4 splitting planes to rule out intersections
  28957. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28958. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28959. }
  28960. clampPoint( point, target ) {
  28961. return target.copy( point ).clamp( this.min, this.max );
  28962. }
  28963. distanceToPoint( point ) {
  28964. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28965. }
  28966. intersect( box ) {
  28967. this.min.max( box.min );
  28968. this.max.min( box.max );
  28969. if ( this.isEmpty() ) this.makeEmpty();
  28970. return this;
  28971. }
  28972. union( box ) {
  28973. this.min.min( box.min );
  28974. this.max.max( box.max );
  28975. return this;
  28976. }
  28977. translate( offset ) {
  28978. this.min.add( offset );
  28979. this.max.add( offset );
  28980. return this;
  28981. }
  28982. equals( box ) {
  28983. return box.min.equals( this.min ) && box.max.equals( this.max );
  28984. }
  28985. }
  28986. const _startP = /*@__PURE__*/ new Vector3();
  28987. const _startEnd = /*@__PURE__*/ new Vector3();
  28988. class Line3 {
  28989. constructor( start = new Vector3(), end = new Vector3() ) {
  28990. this.start = start;
  28991. this.end = end;
  28992. }
  28993. set( start, end ) {
  28994. this.start.copy( start );
  28995. this.end.copy( end );
  28996. return this;
  28997. }
  28998. copy( line ) {
  28999. this.start.copy( line.start );
  29000. this.end.copy( line.end );
  29001. return this;
  29002. }
  29003. getCenter( target ) {
  29004. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  29005. }
  29006. delta( target ) {
  29007. return target.subVectors( this.end, this.start );
  29008. }
  29009. distanceSq() {
  29010. return this.start.distanceToSquared( this.end );
  29011. }
  29012. distance() {
  29013. return this.start.distanceTo( this.end );
  29014. }
  29015. at( t, target ) {
  29016. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29017. }
  29018. closestPointToPointParameter( point, clampToLine ) {
  29019. _startP.subVectors( point, this.start );
  29020. _startEnd.subVectors( this.end, this.start );
  29021. const startEnd2 = _startEnd.dot( _startEnd );
  29022. const startEnd_startP = _startEnd.dot( _startP );
  29023. let t = startEnd_startP / startEnd2;
  29024. if ( clampToLine ) {
  29025. t = clamp( t, 0, 1 );
  29026. }
  29027. return t;
  29028. }
  29029. closestPointToPoint( point, clampToLine, target ) {
  29030. const t = this.closestPointToPointParameter( point, clampToLine );
  29031. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29032. }
  29033. applyMatrix4( matrix ) {
  29034. this.start.applyMatrix4( matrix );
  29035. this.end.applyMatrix4( matrix );
  29036. return this;
  29037. }
  29038. equals( line ) {
  29039. return line.start.equals( this.start ) && line.end.equals( this.end );
  29040. }
  29041. clone() {
  29042. return new this.constructor().copy( this );
  29043. }
  29044. }
  29045. const _vector$3 = /*@__PURE__*/ new Vector3();
  29046. class SpotLightHelper extends Object3D {
  29047. constructor( light, color ) {
  29048. super();
  29049. this.light = light;
  29050. this.matrix = light.matrixWorld;
  29051. this.matrixAutoUpdate = false;
  29052. this.color = color;
  29053. this.type = 'SpotLightHelper';
  29054. const geometry = new BufferGeometry();
  29055. const positions = [
  29056. 0, 0, 0, 0, 0, 1,
  29057. 0, 0, 0, 1, 0, 1,
  29058. 0, 0, 0, - 1, 0, 1,
  29059. 0, 0, 0, 0, 1, 1,
  29060. 0, 0, 0, 0, - 1, 1
  29061. ];
  29062. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  29063. const p1 = ( i / l ) * Math.PI * 2;
  29064. const p2 = ( j / l ) * Math.PI * 2;
  29065. positions.push(
  29066. Math.cos( p1 ), Math.sin( p1 ), 1,
  29067. Math.cos( p2 ), Math.sin( p2 ), 1
  29068. );
  29069. }
  29070. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29071. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29072. this.cone = new LineSegments( geometry, material );
  29073. this.add( this.cone );
  29074. this.update();
  29075. }
  29076. dispose() {
  29077. this.cone.geometry.dispose();
  29078. this.cone.material.dispose();
  29079. }
  29080. update() {
  29081. this.light.updateWorldMatrix( true, false );
  29082. this.light.target.updateWorldMatrix( true, false );
  29083. const coneLength = this.light.distance ? this.light.distance : 1000;
  29084. const coneWidth = coneLength * Math.tan( this.light.angle );
  29085. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  29086. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29087. this.cone.lookAt( _vector$3 );
  29088. if ( this.color !== undefined ) {
  29089. this.cone.material.color.set( this.color );
  29090. } else {
  29091. this.cone.material.color.copy( this.light.color );
  29092. }
  29093. }
  29094. }
  29095. const _vector$2 = /*@__PURE__*/ new Vector3();
  29096. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  29097. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  29098. class SkeletonHelper extends LineSegments {
  29099. constructor( object ) {
  29100. const bones = getBoneList( object );
  29101. const geometry = new BufferGeometry();
  29102. const vertices = [];
  29103. const colors = [];
  29104. const color1 = new Color( 0, 0, 1 );
  29105. const color2 = new Color( 0, 1, 0 );
  29106. for ( let i = 0; i < bones.length; i ++ ) {
  29107. const bone = bones[ i ];
  29108. if ( bone.parent && bone.parent.isBone ) {
  29109. vertices.push( 0, 0, 0 );
  29110. vertices.push( 0, 0, 0 );
  29111. colors.push( color1.r, color1.g, color1.b );
  29112. colors.push( color2.r, color2.g, color2.b );
  29113. }
  29114. }
  29115. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29116. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29117. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  29118. super( geometry, material );
  29119. this.isSkeletonHelper = true;
  29120. this.type = 'SkeletonHelper';
  29121. this.root = object;
  29122. this.bones = bones;
  29123. this.matrix = object.matrixWorld;
  29124. this.matrixAutoUpdate = false;
  29125. }
  29126. updateMatrixWorld( force ) {
  29127. const bones = this.bones;
  29128. const geometry = this.geometry;
  29129. const position = geometry.getAttribute( 'position' );
  29130. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29131. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29132. const bone = bones[ i ];
  29133. if ( bone.parent && bone.parent.isBone ) {
  29134. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29135. _vector$2.setFromMatrixPosition( _boneMatrix );
  29136. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29137. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29138. _vector$2.setFromMatrixPosition( _boneMatrix );
  29139. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29140. j += 2;
  29141. }
  29142. }
  29143. geometry.getAttribute( 'position' ).needsUpdate = true;
  29144. super.updateMatrixWorld( force );
  29145. }
  29146. dispose() {
  29147. this.geometry.dispose();
  29148. this.material.dispose();
  29149. }
  29150. }
  29151. function getBoneList( object ) {
  29152. const boneList = [];
  29153. if ( object.isBone === true ) {
  29154. boneList.push( object );
  29155. }
  29156. for ( let i = 0; i < object.children.length; i ++ ) {
  29157. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29158. }
  29159. return boneList;
  29160. }
  29161. class PointLightHelper extends Mesh {
  29162. constructor( light, sphereSize, color ) {
  29163. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29164. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29165. super( geometry, material );
  29166. this.light = light;
  29167. this.color = color;
  29168. this.type = 'PointLightHelper';
  29169. this.matrix = this.light.matrixWorld;
  29170. this.matrixAutoUpdate = false;
  29171. this.update();
  29172. /*
  29173. // TODO: delete this comment?
  29174. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  29175. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29176. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29177. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29178. const d = light.distance;
  29179. if ( d === 0.0 ) {
  29180. this.lightDistance.visible = false;
  29181. } else {
  29182. this.lightDistance.scale.set( d, d, d );
  29183. }
  29184. this.add( this.lightDistance );
  29185. */
  29186. }
  29187. dispose() {
  29188. this.geometry.dispose();
  29189. this.material.dispose();
  29190. }
  29191. update() {
  29192. this.light.updateWorldMatrix( true, false );
  29193. if ( this.color !== undefined ) {
  29194. this.material.color.set( this.color );
  29195. } else {
  29196. this.material.color.copy( this.light.color );
  29197. }
  29198. /*
  29199. const d = this.light.distance;
  29200. if ( d === 0.0 ) {
  29201. this.lightDistance.visible = false;
  29202. } else {
  29203. this.lightDistance.visible = true;
  29204. this.lightDistance.scale.set( d, d, d );
  29205. }
  29206. */
  29207. }
  29208. }
  29209. const _vector$1 = /*@__PURE__*/ new Vector3();
  29210. const _color1 = /*@__PURE__*/ new Color();
  29211. const _color2 = /*@__PURE__*/ new Color();
  29212. class HemisphereLightHelper extends Object3D {
  29213. constructor( light, size, color ) {
  29214. super();
  29215. this.light = light;
  29216. this.matrix = light.matrixWorld;
  29217. this.matrixAutoUpdate = false;
  29218. this.color = color;
  29219. this.type = 'HemisphereLightHelper';
  29220. const geometry = new OctahedronGeometry( size );
  29221. geometry.rotateY( Math.PI * 0.5 );
  29222. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29223. if ( this.color === undefined ) this.material.vertexColors = true;
  29224. const position = geometry.getAttribute( 'position' );
  29225. const colors = new Float32Array( position.count * 3 );
  29226. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29227. this.add( new Mesh( geometry, this.material ) );
  29228. this.update();
  29229. }
  29230. dispose() {
  29231. this.children[ 0 ].geometry.dispose();
  29232. this.children[ 0 ].material.dispose();
  29233. }
  29234. update() {
  29235. const mesh = this.children[ 0 ];
  29236. if ( this.color !== undefined ) {
  29237. this.material.color.set( this.color );
  29238. } else {
  29239. const colors = mesh.geometry.getAttribute( 'color' );
  29240. _color1.copy( this.light.color );
  29241. _color2.copy( this.light.groundColor );
  29242. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29243. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29244. colors.setXYZ( i, color.r, color.g, color.b );
  29245. }
  29246. colors.needsUpdate = true;
  29247. }
  29248. this.light.updateWorldMatrix( true, false );
  29249. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29250. }
  29251. }
  29252. class GridHelper extends LineSegments {
  29253. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29254. color1 = new Color( color1 );
  29255. color2 = new Color( color2 );
  29256. const center = divisions / 2;
  29257. const step = size / divisions;
  29258. const halfSize = size / 2;
  29259. const vertices = [], colors = [];
  29260. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29261. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29262. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29263. const color = i === center ? color1 : color2;
  29264. color.toArray( colors, j ); j += 3;
  29265. color.toArray( colors, j ); j += 3;
  29266. color.toArray( colors, j ); j += 3;
  29267. color.toArray( colors, j ); j += 3;
  29268. }
  29269. const geometry = new BufferGeometry();
  29270. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29271. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29272. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29273. super( geometry, material );
  29274. this.type = 'GridHelper';
  29275. }
  29276. dispose() {
  29277. this.geometry.dispose();
  29278. this.material.dispose();
  29279. }
  29280. }
  29281. class PolarGridHelper extends LineSegments {
  29282. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29283. color1 = new Color( color1 );
  29284. color2 = new Color( color2 );
  29285. const vertices = [];
  29286. const colors = [];
  29287. // create the sectors
  29288. if ( sectors > 1 ) {
  29289. for ( let i = 0; i < sectors; i ++ ) {
  29290. const v = ( i / sectors ) * ( Math.PI * 2 );
  29291. const x = Math.sin( v ) * radius;
  29292. const z = Math.cos( v ) * radius;
  29293. vertices.push( 0, 0, 0 );
  29294. vertices.push( x, 0, z );
  29295. const color = ( i & 1 ) ? color1 : color2;
  29296. colors.push( color.r, color.g, color.b );
  29297. colors.push( color.r, color.g, color.b );
  29298. }
  29299. }
  29300. // create the rings
  29301. for ( let i = 0; i < rings; i ++ ) {
  29302. const color = ( i & 1 ) ? color1 : color2;
  29303. const r = radius - ( radius / rings * i );
  29304. for ( let j = 0; j < divisions; j ++ ) {
  29305. // first vertex
  29306. let v = ( j / divisions ) * ( Math.PI * 2 );
  29307. let x = Math.sin( v ) * r;
  29308. let z = Math.cos( v ) * r;
  29309. vertices.push( x, 0, z );
  29310. colors.push( color.r, color.g, color.b );
  29311. // second vertex
  29312. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29313. x = Math.sin( v ) * r;
  29314. z = Math.cos( v ) * r;
  29315. vertices.push( x, 0, z );
  29316. colors.push( color.r, color.g, color.b );
  29317. }
  29318. }
  29319. const geometry = new BufferGeometry();
  29320. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29321. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29322. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29323. super( geometry, material );
  29324. this.type = 'PolarGridHelper';
  29325. }
  29326. dispose() {
  29327. this.geometry.dispose();
  29328. this.material.dispose();
  29329. }
  29330. }
  29331. const _v1 = /*@__PURE__*/ new Vector3();
  29332. const _v2 = /*@__PURE__*/ new Vector3();
  29333. const _v3 = /*@__PURE__*/ new Vector3();
  29334. class DirectionalLightHelper extends Object3D {
  29335. constructor( light, size, color ) {
  29336. super();
  29337. this.light = light;
  29338. this.matrix = light.matrixWorld;
  29339. this.matrixAutoUpdate = false;
  29340. this.color = color;
  29341. this.type = 'DirectionalLightHelper';
  29342. if ( size === undefined ) size = 1;
  29343. let geometry = new BufferGeometry();
  29344. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29345. - size, size, 0,
  29346. size, size, 0,
  29347. size, - size, 0,
  29348. - size, - size, 0,
  29349. - size, size, 0
  29350. ], 3 ) );
  29351. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29352. this.lightPlane = new Line( geometry, material );
  29353. this.add( this.lightPlane );
  29354. geometry = new BufferGeometry();
  29355. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29356. this.targetLine = new Line( geometry, material );
  29357. this.add( this.targetLine );
  29358. this.update();
  29359. }
  29360. dispose() {
  29361. this.lightPlane.geometry.dispose();
  29362. this.lightPlane.material.dispose();
  29363. this.targetLine.geometry.dispose();
  29364. this.targetLine.material.dispose();
  29365. }
  29366. update() {
  29367. this.light.updateWorldMatrix( true, false );
  29368. this.light.target.updateWorldMatrix( true, false );
  29369. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29370. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29371. _v3.subVectors( _v2, _v1 );
  29372. this.lightPlane.lookAt( _v2 );
  29373. if ( this.color !== undefined ) {
  29374. this.lightPlane.material.color.set( this.color );
  29375. this.targetLine.material.color.set( this.color );
  29376. } else {
  29377. this.lightPlane.material.color.copy( this.light.color );
  29378. this.targetLine.material.color.copy( this.light.color );
  29379. }
  29380. this.targetLine.lookAt( _v2 );
  29381. this.targetLine.scale.z = _v3.length();
  29382. }
  29383. }
  29384. const _vector = /*@__PURE__*/ new Vector3();
  29385. const _camera = /*@__PURE__*/ new Camera();
  29386. /**
  29387. * - shows frustum, line of sight and up of the camera
  29388. * - suitable for fast updates
  29389. * - based on frustum visualization in lightgl.js shadowmap example
  29390. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29391. */
  29392. class CameraHelper extends LineSegments {
  29393. constructor( camera ) {
  29394. const geometry = new BufferGeometry();
  29395. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29396. const vertices = [];
  29397. const colors = [];
  29398. const pointMap = {};
  29399. // near
  29400. addLine( 'n1', 'n2' );
  29401. addLine( 'n2', 'n4' );
  29402. addLine( 'n4', 'n3' );
  29403. addLine( 'n3', 'n1' );
  29404. // far
  29405. addLine( 'f1', 'f2' );
  29406. addLine( 'f2', 'f4' );
  29407. addLine( 'f4', 'f3' );
  29408. addLine( 'f3', 'f1' );
  29409. // sides
  29410. addLine( 'n1', 'f1' );
  29411. addLine( 'n2', 'f2' );
  29412. addLine( 'n3', 'f3' );
  29413. addLine( 'n4', 'f4' );
  29414. // cone
  29415. addLine( 'p', 'n1' );
  29416. addLine( 'p', 'n2' );
  29417. addLine( 'p', 'n3' );
  29418. addLine( 'p', 'n4' );
  29419. // up
  29420. addLine( 'u1', 'u2' );
  29421. addLine( 'u2', 'u3' );
  29422. addLine( 'u3', 'u1' );
  29423. // target
  29424. addLine( 'c', 't' );
  29425. addLine( 'p', 'c' );
  29426. // cross
  29427. addLine( 'cn1', 'cn2' );
  29428. addLine( 'cn3', 'cn4' );
  29429. addLine( 'cf1', 'cf2' );
  29430. addLine( 'cf3', 'cf4' );
  29431. function addLine( a, b ) {
  29432. addPoint( a );
  29433. addPoint( b );
  29434. }
  29435. function addPoint( id ) {
  29436. vertices.push( 0, 0, 0 );
  29437. colors.push( 0, 0, 0 );
  29438. if ( pointMap[ id ] === undefined ) {
  29439. pointMap[ id ] = [];
  29440. }
  29441. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29442. }
  29443. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29444. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29445. super( geometry, material );
  29446. this.type = 'CameraHelper';
  29447. this.camera = camera;
  29448. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29449. this.matrix = camera.matrixWorld;
  29450. this.matrixAutoUpdate = false;
  29451. this.pointMap = pointMap;
  29452. this.update();
  29453. // colors
  29454. const colorFrustum = new Color( 0xffaa00 );
  29455. const colorCone = new Color( 0xff0000 );
  29456. const colorUp = new Color( 0x00aaff );
  29457. const colorTarget = new Color( 0xffffff );
  29458. const colorCross = new Color( 0x333333 );
  29459. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29460. }
  29461. setColors( frustum, cone, up, target, cross ) {
  29462. const geometry = this.geometry;
  29463. const colorAttribute = geometry.getAttribute( 'color' );
  29464. // near
  29465. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29466. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29467. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29468. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29469. // far
  29470. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29471. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29472. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29473. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29474. // sides
  29475. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29476. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29477. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29478. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29479. // cone
  29480. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29481. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29482. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29483. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29484. // up
  29485. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29486. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29487. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29488. // target
  29489. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29490. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29491. // cross
  29492. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29493. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29494. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29495. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29496. colorAttribute.needsUpdate = true;
  29497. }
  29498. update() {
  29499. const geometry = this.geometry;
  29500. const pointMap = this.pointMap;
  29501. const w = 1, h = 1;
  29502. // we need just camera projection matrix inverse
  29503. // world matrix must be identity
  29504. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29505. // center / target
  29506. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29507. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29508. // near
  29509. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29510. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29511. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29512. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29513. // far
  29514. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29515. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29516. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29517. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29518. // up
  29519. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29520. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29521. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29522. // cross
  29523. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29524. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29525. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29526. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29527. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29528. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29529. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29530. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29531. geometry.getAttribute( 'position' ).needsUpdate = true;
  29532. }
  29533. dispose() {
  29534. this.geometry.dispose();
  29535. this.material.dispose();
  29536. }
  29537. }
  29538. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29539. _vector.set( x, y, z ).unproject( camera );
  29540. const points = pointMap[ point ];
  29541. if ( points !== undefined ) {
  29542. const position = geometry.getAttribute( 'position' );
  29543. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29544. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29545. }
  29546. }
  29547. }
  29548. const _box = /*@__PURE__*/ new Box3();
  29549. class BoxHelper extends LineSegments {
  29550. constructor( object, color = 0xffff00 ) {
  29551. 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 ] );
  29552. const positions = new Float32Array( 8 * 3 );
  29553. const geometry = new BufferGeometry();
  29554. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29555. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29556. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29557. this.object = object;
  29558. this.type = 'BoxHelper';
  29559. this.matrixAutoUpdate = false;
  29560. this.update();
  29561. }
  29562. update( object ) {
  29563. if ( object !== undefined ) {
  29564. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29565. }
  29566. if ( this.object !== undefined ) {
  29567. _box.setFromObject( this.object );
  29568. }
  29569. if ( _box.isEmpty() ) return;
  29570. const min = _box.min;
  29571. const max = _box.max;
  29572. /*
  29573. 5____4
  29574. 1/___0/|
  29575. | 6__|_7
  29576. 2/___3/
  29577. 0: max.x, max.y, max.z
  29578. 1: min.x, max.y, max.z
  29579. 2: min.x, min.y, max.z
  29580. 3: max.x, min.y, max.z
  29581. 4: max.x, max.y, min.z
  29582. 5: min.x, max.y, min.z
  29583. 6: min.x, min.y, min.z
  29584. 7: max.x, min.y, min.z
  29585. */
  29586. const position = this.geometry.attributes.position;
  29587. const array = position.array;
  29588. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29589. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29590. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29591. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29592. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29593. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29594. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29595. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29596. position.needsUpdate = true;
  29597. this.geometry.computeBoundingSphere();
  29598. }
  29599. setFromObject( object ) {
  29600. this.object = object;
  29601. this.update();
  29602. return this;
  29603. }
  29604. copy( source, recursive ) {
  29605. super.copy( source, recursive );
  29606. this.object = source.object;
  29607. return this;
  29608. }
  29609. dispose() {
  29610. this.geometry.dispose();
  29611. this.material.dispose();
  29612. }
  29613. }
  29614. class Box3Helper extends LineSegments {
  29615. constructor( box, color = 0xffff00 ) {
  29616. 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 ] );
  29617. 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 ];
  29618. const geometry = new BufferGeometry();
  29619. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29620. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29621. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29622. this.box = box;
  29623. this.type = 'Box3Helper';
  29624. this.geometry.computeBoundingSphere();
  29625. }
  29626. updateMatrixWorld( force ) {
  29627. const box = this.box;
  29628. if ( box.isEmpty() ) return;
  29629. box.getCenter( this.position );
  29630. box.getSize( this.scale );
  29631. this.scale.multiplyScalar( 0.5 );
  29632. super.updateMatrixWorld( force );
  29633. }
  29634. dispose() {
  29635. this.geometry.dispose();
  29636. this.material.dispose();
  29637. }
  29638. }
  29639. class PlaneHelper extends Line {
  29640. constructor( plane, size = 1, hex = 0xffff00 ) {
  29641. const color = hex;
  29642. 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 ];
  29643. const geometry = new BufferGeometry();
  29644. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29645. geometry.computeBoundingSphere();
  29646. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29647. this.type = 'PlaneHelper';
  29648. this.plane = plane;
  29649. this.size = size;
  29650. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29651. const geometry2 = new BufferGeometry();
  29652. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29653. geometry2.computeBoundingSphere();
  29654. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29655. }
  29656. updateMatrixWorld( force ) {
  29657. this.position.set( 0, 0, 0 );
  29658. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29659. this.lookAt( this.plane.normal );
  29660. this.translateZ( - this.plane.constant );
  29661. super.updateMatrixWorld( force );
  29662. }
  29663. dispose() {
  29664. this.geometry.dispose();
  29665. this.material.dispose();
  29666. this.children[ 0 ].geometry.dispose();
  29667. this.children[ 0 ].material.dispose();
  29668. }
  29669. }
  29670. const _axis = /*@__PURE__*/ new Vector3();
  29671. let _lineGeometry, _coneGeometry;
  29672. class ArrowHelper extends Object3D {
  29673. // dir is assumed to be normalized
  29674. 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 ) {
  29675. super();
  29676. this.type = 'ArrowHelper';
  29677. if ( _lineGeometry === undefined ) {
  29678. _lineGeometry = new BufferGeometry();
  29679. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29680. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29681. _coneGeometry.translate( 0, - 0.5, 0 );
  29682. }
  29683. this.position.copy( origin );
  29684. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29685. this.line.matrixAutoUpdate = false;
  29686. this.add( this.line );
  29687. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29688. this.cone.matrixAutoUpdate = false;
  29689. this.add( this.cone );
  29690. this.setDirection( dir );
  29691. this.setLength( length, headLength, headWidth );
  29692. }
  29693. setDirection( dir ) {
  29694. // dir is assumed to be normalized
  29695. if ( dir.y > 0.99999 ) {
  29696. this.quaternion.set( 0, 0, 0, 1 );
  29697. } else if ( dir.y < - 0.99999 ) {
  29698. this.quaternion.set( 1, 0, 0, 0 );
  29699. } else {
  29700. _axis.set( dir.z, 0, - dir.x ).normalize();
  29701. const radians = Math.acos( dir.y );
  29702. this.quaternion.setFromAxisAngle( _axis, radians );
  29703. }
  29704. }
  29705. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29706. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29707. this.line.updateMatrix();
  29708. this.cone.scale.set( headWidth, headLength, headWidth );
  29709. this.cone.position.y = length;
  29710. this.cone.updateMatrix();
  29711. }
  29712. setColor( color ) {
  29713. this.line.material.color.set( color );
  29714. this.cone.material.color.set( color );
  29715. }
  29716. copy( source ) {
  29717. super.copy( source, false );
  29718. this.line.copy( source.line );
  29719. this.cone.copy( source.cone );
  29720. return this;
  29721. }
  29722. dispose() {
  29723. this.line.geometry.dispose();
  29724. this.line.material.dispose();
  29725. this.cone.geometry.dispose();
  29726. this.cone.material.dispose();
  29727. }
  29728. }
  29729. class AxesHelper extends LineSegments {
  29730. constructor( size = 1 ) {
  29731. const vertices = [
  29732. 0, 0, 0, size, 0, 0,
  29733. 0, 0, 0, 0, size, 0,
  29734. 0, 0, 0, 0, 0, size
  29735. ];
  29736. const colors = [
  29737. 1, 0, 0, 1, 0.6, 0,
  29738. 0, 1, 0, 0.6, 1, 0,
  29739. 0, 0, 1, 0, 0.6, 1
  29740. ];
  29741. const geometry = new BufferGeometry();
  29742. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29743. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29744. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29745. super( geometry, material );
  29746. this.type = 'AxesHelper';
  29747. }
  29748. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29749. const color = new Color();
  29750. const array = this.geometry.attributes.color.array;
  29751. color.set( xAxisColor );
  29752. color.toArray( array, 0 );
  29753. color.toArray( array, 3 );
  29754. color.set( yAxisColor );
  29755. color.toArray( array, 6 );
  29756. color.toArray( array, 9 );
  29757. color.set( zAxisColor );
  29758. color.toArray( array, 12 );
  29759. color.toArray( array, 15 );
  29760. this.geometry.attributes.color.needsUpdate = true;
  29761. return this;
  29762. }
  29763. dispose() {
  29764. this.geometry.dispose();
  29765. this.material.dispose();
  29766. }
  29767. }
  29768. class ShapePath {
  29769. constructor() {
  29770. this.type = 'ShapePath';
  29771. this.color = new Color();
  29772. this.subPaths = [];
  29773. this.currentPath = null;
  29774. }
  29775. moveTo( x, y ) {
  29776. this.currentPath = new Path();
  29777. this.subPaths.push( this.currentPath );
  29778. this.currentPath.moveTo( x, y );
  29779. return this;
  29780. }
  29781. lineTo( x, y ) {
  29782. this.currentPath.lineTo( x, y );
  29783. return this;
  29784. }
  29785. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29786. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29787. return this;
  29788. }
  29789. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29790. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29791. return this;
  29792. }
  29793. splineThru( pts ) {
  29794. this.currentPath.splineThru( pts );
  29795. return this;
  29796. }
  29797. toShapes( isCCW ) {
  29798. function toShapesNoHoles( inSubpaths ) {
  29799. const shapes = [];
  29800. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29801. const tmpPath = inSubpaths[ i ];
  29802. const tmpShape = new Shape();
  29803. tmpShape.curves = tmpPath.curves;
  29804. shapes.push( tmpShape );
  29805. }
  29806. return shapes;
  29807. }
  29808. function isPointInsidePolygon( inPt, inPolygon ) {
  29809. const polyLen = inPolygon.length;
  29810. // inPt on polygon contour => immediate success or
  29811. // toggling of inside/outside at every single! intersection point of an edge
  29812. // with the horizontal line through inPt, left of inPt
  29813. // not counting lowerY endpoints of edges and whole edges on that line
  29814. let inside = false;
  29815. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29816. let edgeLowPt = inPolygon[ p ];
  29817. let edgeHighPt = inPolygon[ q ];
  29818. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29819. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29820. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29821. // not parallel
  29822. if ( edgeDy < 0 ) {
  29823. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29824. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29825. }
  29826. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29827. if ( inPt.y === edgeLowPt.y ) {
  29828. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29829. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29830. } else {
  29831. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29832. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29833. if ( perpEdge < 0 ) continue;
  29834. inside = ! inside; // true intersection left of inPt
  29835. }
  29836. } else {
  29837. // parallel or collinear
  29838. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29839. // edge lies on the same horizontal line as inPt
  29840. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29841. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29842. // continue;
  29843. }
  29844. }
  29845. return inside;
  29846. }
  29847. const isClockWise = ShapeUtils.isClockWise;
  29848. const subPaths = this.subPaths;
  29849. if ( subPaths.length === 0 ) return [];
  29850. let solid, tmpPath, tmpShape;
  29851. const shapes = [];
  29852. if ( subPaths.length === 1 ) {
  29853. tmpPath = subPaths[ 0 ];
  29854. tmpShape = new Shape();
  29855. tmpShape.curves = tmpPath.curves;
  29856. shapes.push( tmpShape );
  29857. return shapes;
  29858. }
  29859. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29860. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29861. // console.log("Holes first", holesFirst);
  29862. const betterShapeHoles = [];
  29863. const newShapes = [];
  29864. let newShapeHoles = [];
  29865. let mainIdx = 0;
  29866. let tmpPoints;
  29867. newShapes[ mainIdx ] = undefined;
  29868. newShapeHoles[ mainIdx ] = [];
  29869. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29870. tmpPath = subPaths[ i ];
  29871. tmpPoints = tmpPath.getPoints();
  29872. solid = isClockWise( tmpPoints );
  29873. solid = isCCW ? ! solid : solid;
  29874. if ( solid ) {
  29875. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29876. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29877. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29878. if ( holesFirst ) mainIdx ++;
  29879. newShapeHoles[ mainIdx ] = [];
  29880. //console.log('cw', i);
  29881. } else {
  29882. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29883. //console.log('ccw', i);
  29884. }
  29885. }
  29886. // only Holes? -> probably all Shapes with wrong orientation
  29887. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29888. if ( newShapes.length > 1 ) {
  29889. let ambiguous = false;
  29890. let toChange = 0;
  29891. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29892. betterShapeHoles[ sIdx ] = [];
  29893. }
  29894. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29895. const sho = newShapeHoles[ sIdx ];
  29896. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29897. const ho = sho[ hIdx ];
  29898. let hole_unassigned = true;
  29899. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29900. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29901. if ( sIdx !== s2Idx ) toChange ++;
  29902. if ( hole_unassigned ) {
  29903. hole_unassigned = false;
  29904. betterShapeHoles[ s2Idx ].push( ho );
  29905. } else {
  29906. ambiguous = true;
  29907. }
  29908. }
  29909. }
  29910. if ( hole_unassigned ) {
  29911. betterShapeHoles[ sIdx ].push( ho );
  29912. }
  29913. }
  29914. }
  29915. if ( toChange > 0 && ambiguous === false ) {
  29916. newShapeHoles = betterShapeHoles;
  29917. }
  29918. }
  29919. let tmpHoles;
  29920. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29921. tmpShape = newShapes[ i ].s;
  29922. shapes.push( tmpShape );
  29923. tmpHoles = newShapeHoles[ i ];
  29924. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29925. tmpShape.holes.push( tmpHoles[ j ].h );
  29926. }
  29927. }
  29928. //console.log("shape", shapes);
  29929. return shapes;
  29930. }
  29931. }
  29932. class BoxBufferGeometry extends BoxGeometry { // @deprecated, r144
  29933. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29934. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29935. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29936. }
  29937. }
  29938. class CapsuleBufferGeometry extends CapsuleGeometry { // @deprecated, r144
  29939. constructor( radius, length, capSegments, radialSegments ) {
  29940. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29941. super( radius, length, capSegments, radialSegments );
  29942. }
  29943. }
  29944. class CircleBufferGeometry extends CircleGeometry { // @deprecated, r144
  29945. constructor( radius, segments, thetaStart, thetaLength ) {
  29946. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29947. super( radius, segments, thetaStart, thetaLength );
  29948. }
  29949. }
  29950. class ConeBufferGeometry extends ConeGeometry { // @deprecated, r144
  29951. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29952. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29953. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29954. }
  29955. }
  29956. class CylinderBufferGeometry extends CylinderGeometry { // @deprecated, r144
  29957. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29958. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29959. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29960. }
  29961. }
  29962. class DodecahedronBufferGeometry extends DodecahedronGeometry { // @deprecated, r144
  29963. constructor( radius, detail ) {
  29964. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29965. super( radius, detail );
  29966. }
  29967. }
  29968. class ExtrudeBufferGeometry extends ExtrudeGeometry { // @deprecated, r144
  29969. constructor( shapes, options ) {
  29970. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29971. super( shapes, options );
  29972. }
  29973. }
  29974. class IcosahedronBufferGeometry extends IcosahedronGeometry { // @deprecated, r144
  29975. constructor( radius, detail ) {
  29976. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29977. super( radius, detail );
  29978. }
  29979. }
  29980. class LatheBufferGeometry extends LatheGeometry { // @deprecated, r144
  29981. constructor( points, segments, phiStart, phiLength ) {
  29982. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29983. super( points, segments, phiStart, phiLength );
  29984. }
  29985. }
  29986. class OctahedronBufferGeometry extends OctahedronGeometry { // @deprecated, r144
  29987. constructor( radius, detail ) {
  29988. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29989. super( radius, detail );
  29990. }
  29991. }
  29992. class PlaneBufferGeometry extends PlaneGeometry { // @deprecated, r144
  29993. constructor( width, height, widthSegments, heightSegments ) {
  29994. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29995. super( width, height, widthSegments, heightSegments );
  29996. }
  29997. }
  29998. class PolyhedronBufferGeometry extends PolyhedronGeometry { // @deprecated, r144
  29999. constructor( vertices, indices, radius, detail ) {
  30000. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  30001. super( vertices, indices, radius, detail );
  30002. }
  30003. }
  30004. class RingBufferGeometry extends RingGeometry { // @deprecated, r144
  30005. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  30006. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  30007. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  30008. }
  30009. }
  30010. class ShapeBufferGeometry extends ShapeGeometry { // @deprecated, r144
  30011. constructor( shapes, curveSegments ) {
  30012. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  30013. super( shapes, curveSegments );
  30014. }
  30015. }
  30016. class SphereBufferGeometry extends SphereGeometry { // @deprecated, r144
  30017. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  30018. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  30019. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  30020. }
  30021. }
  30022. class TetrahedronBufferGeometry extends TetrahedronGeometry { // @deprecated, r144
  30023. constructor( radius, detail ) {
  30024. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  30025. super( radius, detail );
  30026. }
  30027. }
  30028. class TorusBufferGeometry extends TorusGeometry { // @deprecated, r144
  30029. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  30030. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  30031. super( radius, tube, radialSegments, tubularSegments, arc );
  30032. }
  30033. }
  30034. class TorusKnotBufferGeometry extends TorusKnotGeometry { // @deprecated, r144
  30035. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  30036. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  30037. super( radius, tube, tubularSegments, radialSegments, p, q );
  30038. }
  30039. }
  30040. class TubeBufferGeometry extends TubeGeometry { // @deprecated, r144
  30041. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  30042. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  30043. super( path, tubularSegments, radius, radialSegments, closed );
  30044. }
  30045. }
  30046. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30047. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30048. revision: REVISION,
  30049. } } ) );
  30050. }
  30051. if ( typeof window !== 'undefined' ) {
  30052. if ( window.__THREE__ ) {
  30053. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30054. } else {
  30055. window.__THREE__ = REVISION;
  30056. }
  30057. }
  30058. 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 };