three.webgpu.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '169dev';
  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$1 = 0;
  14. const PCFShadowMap$1 = 1;
  15. const PCFSoftShadowMap$1 = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const DisplayP3ColorSpace = 'display-p3';
  168. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  169. const LinearTransfer = 'linear';
  170. const SRGBTransfer = 'srgb';
  171. const Rec709Primaries = 'rec709';
  172. const P3Primaries = 'p3';
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const NeverCompare = 512;
  190. const LessCompare = 513;
  191. const EqualCompare = 514;
  192. const LessEqualCompare = 515;
  193. const GreaterCompare = 516;
  194. const NotEqualCompare = 517;
  195. const GreaterEqualCompare = 518;
  196. const AlwaysCompare = 519;
  197. const StaticDrawUsage = 35044;
  198. const DynamicDrawUsage = 35048;
  199. const StreamDrawUsage = 35040;
  200. const StaticReadUsage = 35045;
  201. const DynamicReadUsage = 35049;
  202. const StreamReadUsage = 35041;
  203. const StaticCopyUsage = 35046;
  204. const DynamicCopyUsage = 35050;
  205. const StreamCopyUsage = 35042;
  206. const GLSL1 = '100';
  207. const GLSL3 = '300 es';
  208. const WebGLCoordinateSystem = 2000;
  209. const WebGPUCoordinateSystem = 2001;
  210. /**
  211. * https://github.com/mrdoob/eventdispatcher.js/
  212. */
  213. class EventDispatcher {
  214. addEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) this._listeners = {};
  216. const listeners = this._listeners;
  217. if ( listeners[ type ] === undefined ) {
  218. listeners[ type ] = [];
  219. }
  220. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  221. listeners[ type ].push( listener );
  222. }
  223. }
  224. hasEventListener( type, listener ) {
  225. if ( this._listeners === undefined ) return false;
  226. const listeners = this._listeners;
  227. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  228. }
  229. removeEventListener( type, listener ) {
  230. if ( this._listeners === undefined ) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[ type ];
  233. if ( listenerArray !== undefined ) {
  234. const index = listenerArray.indexOf( listener );
  235. if ( index !== - 1 ) {
  236. listenerArray.splice( index, 1 );
  237. }
  238. }
  239. }
  240. dispatchEvent( event ) {
  241. if ( this._listeners === undefined ) return;
  242. const listeners = this._listeners;
  243. const listenerArray = listeners[ event.type ];
  244. if ( listenerArray !== undefined ) {
  245. event.target = this;
  246. // Make a copy, in case listeners are removed while iterating.
  247. const array = listenerArray.slice( 0 );
  248. for ( let i = 0, l = array.length; i < l; i ++ ) {
  249. array[ i ].call( this, event );
  250. }
  251. event.target = null;
  252. }
  253. }
  254. }
  255. 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' ];
  256. let _seed = 1234567;
  257. const DEG2RAD = Math.PI / 180;
  258. const RAD2DEG = 180 / Math.PI;
  259. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  260. function generateUUID() {
  261. const d0 = Math.random() * 0xffffffff | 0;
  262. const d1 = Math.random() * 0xffffffff | 0;
  263. const d2 = Math.random() * 0xffffffff | 0;
  264. const d3 = Math.random() * 0xffffffff | 0;
  265. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  266. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  267. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  268. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  269. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  270. return uuid.toLowerCase();
  271. }
  272. function clamp$1( value, min, max ) {
  273. return Math.max( min, Math.min( max, value ) );
  274. }
  275. // compute euclidean modulo of m % n
  276. // https://en.wikipedia.org/wiki/Modulo_operation
  277. function euclideanModulo( n, m ) {
  278. return ( ( n % m ) + m ) % m;
  279. }
  280. // Linear mapping from range <a1, a2> to range <b1, b2>
  281. function mapLinear( x, a1, a2, b1, b2 ) {
  282. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  283. }
  284. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  285. function inverseLerp( x, y, value ) {
  286. if ( x !== y ) {
  287. return ( value - x ) / ( y - x );
  288. } else {
  289. return 0;
  290. }
  291. }
  292. // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp( x, y, t ) {
  294. return ( 1 - t ) * x + t * y;
  295. }
  296. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  297. function damp( x, y, lambda, dt ) {
  298. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  299. }
  300. // https://www.desmos.com/calculator/vcsjnyz7x4
  301. function pingpong( x, length = 1 ) {
  302. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  303. }
  304. // http://en.wikipedia.org/wiki/Smoothstep
  305. function smoothstep$1( x, min, max ) {
  306. if ( x <= min ) return 0;
  307. if ( x >= max ) return 1;
  308. x = ( x - min ) / ( max - min );
  309. return x * x * ( 3 - 2 * x );
  310. }
  311. function smootherstep( x, min, max ) {
  312. if ( x <= min ) return 0;
  313. if ( x >= max ) return 1;
  314. x = ( x - min ) / ( max - min );
  315. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  316. }
  317. // Random integer from <low, high> interval
  318. function randInt( low, high ) {
  319. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  320. }
  321. // Random float from <low, high> interval
  322. function randFloat( low, high ) {
  323. return low + Math.random() * ( high - low );
  324. }
  325. // Random float from <-range/2, range/2> interval
  326. function randFloatSpread( range ) {
  327. return range * ( 0.5 - Math.random() );
  328. }
  329. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  330. function seededRandom( s ) {
  331. if ( s !== undefined ) _seed = s;
  332. // Mulberry32 generator
  333. let t = _seed += 0x6D2B79F5;
  334. t = Math.imul( t ^ t >>> 15, t | 1 );
  335. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  336. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  337. }
  338. function degToRad( degrees ) {
  339. return degrees * DEG2RAD;
  340. }
  341. function radToDeg( radians ) {
  342. return radians * RAD2DEG;
  343. }
  344. function isPowerOfTwo( value ) {
  345. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  346. }
  347. function ceilPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function floorPowerOfTwo( value ) {
  351. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  352. }
  353. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  354. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  355. // rotations are applied to the axes in the order specified by 'order'
  356. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  357. // angles are in radians
  358. const cos = Math.cos;
  359. const sin = Math.sin;
  360. const c2 = cos( b / 2 );
  361. const s2 = sin( b / 2 );
  362. const c13 = cos( ( a + c ) / 2 );
  363. const s13 = sin( ( a + c ) / 2 );
  364. const c1_3 = cos( ( a - c ) / 2 );
  365. const s1_3 = sin( ( a - c ) / 2 );
  366. const c3_1 = cos( ( c - a ) / 2 );
  367. const s3_1 = sin( ( c - a ) / 2 );
  368. switch ( order ) {
  369. case 'XYX':
  370. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  371. break;
  372. case 'YZY':
  373. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  374. break;
  375. case 'ZXZ':
  376. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  377. break;
  378. case 'XZX':
  379. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  380. break;
  381. case 'YXY':
  382. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  383. break;
  384. case 'ZYZ':
  385. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  386. break;
  387. default:
  388. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  389. }
  390. }
  391. function denormalize( value, array ) {
  392. switch ( array.constructor ) {
  393. case Float32Array:
  394. return value;
  395. case Uint32Array:
  396. return value / 4294967295.0;
  397. case Uint16Array:
  398. return value / 65535.0;
  399. case Uint8Array:
  400. return value / 255.0;
  401. case Int32Array:
  402. return Math.max( value / 2147483647.0, - 1.0 );
  403. case Int16Array:
  404. return Math.max( value / 32767.0, - 1.0 );
  405. case Int8Array:
  406. return Math.max( value / 127.0, - 1.0 );
  407. default:
  408. throw new Error( 'Invalid component type.' );
  409. }
  410. }
  411. function normalize$1( value, array ) {
  412. switch ( array.constructor ) {
  413. case Float32Array:
  414. return value;
  415. case Uint32Array:
  416. return Math.round( value * 4294967295.0 );
  417. case Uint16Array:
  418. return Math.round( value * 65535.0 );
  419. case Uint8Array:
  420. return Math.round( value * 255.0 );
  421. case Int32Array:
  422. return Math.round( value * 2147483647.0 );
  423. case Int16Array:
  424. return Math.round( value * 32767.0 );
  425. case Int8Array:
  426. return Math.round( value * 127.0 );
  427. default:
  428. throw new Error( 'Invalid component type.' );
  429. }
  430. }
  431. const MathUtils = {
  432. DEG2RAD: DEG2RAD,
  433. RAD2DEG: RAD2DEG,
  434. generateUUID: generateUUID,
  435. clamp: clamp$1,
  436. euclideanModulo: euclideanModulo,
  437. mapLinear: mapLinear,
  438. inverseLerp: inverseLerp,
  439. lerp: lerp,
  440. damp: damp,
  441. pingpong: pingpong,
  442. smoothstep: smoothstep$1,
  443. smootherstep: smootherstep,
  444. randInt: randInt,
  445. randFloat: randFloat,
  446. randFloatSpread: randFloatSpread,
  447. seededRandom: seededRandom,
  448. degToRad: degToRad,
  449. radToDeg: radToDeg,
  450. isPowerOfTwo: isPowerOfTwo,
  451. ceilPowerOfTwo: ceilPowerOfTwo,
  452. floorPowerOfTwo: floorPowerOfTwo,
  453. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  454. normalize: normalize$1,
  455. denormalize: denormalize
  456. };
  457. class Vector2 {
  458. constructor( x = 0, y = 0 ) {
  459. Vector2.prototype.isVector2 = true;
  460. this.x = x;
  461. this.y = y;
  462. }
  463. get width() {
  464. return this.x;
  465. }
  466. set width( value ) {
  467. this.x = value;
  468. }
  469. get height() {
  470. return this.y;
  471. }
  472. set height( value ) {
  473. this.y = value;
  474. }
  475. set( x, y ) {
  476. this.x = x;
  477. this.y = y;
  478. return this;
  479. }
  480. setScalar( scalar ) {
  481. this.x = scalar;
  482. this.y = scalar;
  483. return this;
  484. }
  485. setX( x ) {
  486. this.x = x;
  487. return this;
  488. }
  489. setY( y ) {
  490. this.y = y;
  491. return this;
  492. }
  493. setComponent( index, value ) {
  494. switch ( index ) {
  495. case 0: this.x = value; break;
  496. case 1: this.y = value; break;
  497. default: throw new Error( 'index is out of range: ' + index );
  498. }
  499. return this;
  500. }
  501. getComponent( index ) {
  502. switch ( index ) {
  503. case 0: return this.x;
  504. case 1: return this.y;
  505. default: throw new Error( 'index is out of range: ' + index );
  506. }
  507. }
  508. clone() {
  509. return new this.constructor( this.x, this.y );
  510. }
  511. copy( v ) {
  512. this.x = v.x;
  513. this.y = v.y;
  514. return this;
  515. }
  516. add( v ) {
  517. this.x += v.x;
  518. this.y += v.y;
  519. return this;
  520. }
  521. addScalar( s ) {
  522. this.x += s;
  523. this.y += s;
  524. return this;
  525. }
  526. addVectors( a, b ) {
  527. this.x = a.x + b.x;
  528. this.y = a.y + b.y;
  529. return this;
  530. }
  531. addScaledVector( v, s ) {
  532. this.x += v.x * s;
  533. this.y += v.y * s;
  534. return this;
  535. }
  536. sub( v ) {
  537. this.x -= v.x;
  538. this.y -= v.y;
  539. return this;
  540. }
  541. subScalar( s ) {
  542. this.x -= s;
  543. this.y -= s;
  544. return this;
  545. }
  546. subVectors( a, b ) {
  547. this.x = a.x - b.x;
  548. this.y = a.y - b.y;
  549. return this;
  550. }
  551. multiply( v ) {
  552. this.x *= v.x;
  553. this.y *= v.y;
  554. return this;
  555. }
  556. multiplyScalar( scalar ) {
  557. this.x *= scalar;
  558. this.y *= scalar;
  559. return this;
  560. }
  561. divide( v ) {
  562. this.x /= v.x;
  563. this.y /= v.y;
  564. return this;
  565. }
  566. divideScalar( scalar ) {
  567. return this.multiplyScalar( 1 / scalar );
  568. }
  569. applyMatrix3( m ) {
  570. const x = this.x, y = this.y;
  571. const e = m.elements;
  572. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  573. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  574. return this;
  575. }
  576. min( v ) {
  577. this.x = Math.min( this.x, v.x );
  578. this.y = Math.min( this.y, v.y );
  579. return this;
  580. }
  581. max( v ) {
  582. this.x = Math.max( this.x, v.x );
  583. this.y = Math.max( this.y, v.y );
  584. return this;
  585. }
  586. clamp( min, max ) {
  587. // assumes min < max, componentwise
  588. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  589. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  590. return this;
  591. }
  592. clampScalar( minVal, maxVal ) {
  593. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  594. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  595. return this;
  596. }
  597. clampLength( min, max ) {
  598. const length = this.length();
  599. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  600. }
  601. floor() {
  602. this.x = Math.floor( this.x );
  603. this.y = Math.floor( this.y );
  604. return this;
  605. }
  606. ceil() {
  607. this.x = Math.ceil( this.x );
  608. this.y = Math.ceil( this.y );
  609. return this;
  610. }
  611. round() {
  612. this.x = Math.round( this.x );
  613. this.y = Math.round( this.y );
  614. return this;
  615. }
  616. roundToZero() {
  617. this.x = Math.trunc( this.x );
  618. this.y = Math.trunc( this.y );
  619. return this;
  620. }
  621. negate() {
  622. this.x = - this.x;
  623. this.y = - this.y;
  624. return this;
  625. }
  626. dot( v ) {
  627. return this.x * v.x + this.y * v.y;
  628. }
  629. cross( v ) {
  630. return this.x * v.y - this.y * v.x;
  631. }
  632. lengthSq() {
  633. return this.x * this.x + this.y * this.y;
  634. }
  635. length() {
  636. return Math.sqrt( this.x * this.x + this.y * this.y );
  637. }
  638. manhattanLength() {
  639. return Math.abs( this.x ) + Math.abs( this.y );
  640. }
  641. normalize() {
  642. return this.divideScalar( this.length() || 1 );
  643. }
  644. angle() {
  645. // computes the angle in radians with respect to the positive x-axis
  646. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  647. return angle;
  648. }
  649. angleTo( v ) {
  650. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  651. if ( denominator === 0 ) return Math.PI / 2;
  652. const theta = this.dot( v ) / denominator;
  653. // clamp, to handle numerical problems
  654. return Math.acos( clamp$1( theta, - 1, 1 ) );
  655. }
  656. distanceTo( v ) {
  657. return Math.sqrt( this.distanceToSquared( v ) );
  658. }
  659. distanceToSquared( v ) {
  660. const dx = this.x - v.x, dy = this.y - v.y;
  661. return dx * dx + dy * dy;
  662. }
  663. manhattanDistanceTo( v ) {
  664. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  665. }
  666. setLength( length ) {
  667. return this.normalize().multiplyScalar( length );
  668. }
  669. lerp( v, alpha ) {
  670. this.x += ( v.x - this.x ) * alpha;
  671. this.y += ( v.y - this.y ) * alpha;
  672. return this;
  673. }
  674. lerpVectors( v1, v2, alpha ) {
  675. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  676. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  677. return this;
  678. }
  679. equals( v ) {
  680. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  681. }
  682. fromArray( array, offset = 0 ) {
  683. this.x = array[ offset ];
  684. this.y = array[ offset + 1 ];
  685. return this;
  686. }
  687. toArray( array = [], offset = 0 ) {
  688. array[ offset ] = this.x;
  689. array[ offset + 1 ] = this.y;
  690. return array;
  691. }
  692. fromBufferAttribute( attribute, index ) {
  693. this.x = attribute.getX( index );
  694. this.y = attribute.getY( index );
  695. return this;
  696. }
  697. rotateAround( center, angle ) {
  698. const c = Math.cos( angle ), s = Math.sin( angle );
  699. const x = this.x - center.x;
  700. const y = this.y - center.y;
  701. this.x = x * c - y * s + center.x;
  702. this.y = x * s + y * c + center.y;
  703. return this;
  704. }
  705. random() {
  706. this.x = Math.random();
  707. this.y = Math.random();
  708. return this;
  709. }
  710. *[ Symbol.iterator ]() {
  711. yield this.x;
  712. yield this.y;
  713. }
  714. }
  715. class Matrix3 {
  716. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  717. Matrix3.prototype.isMatrix3 = true;
  718. this.elements = [
  719. 1, 0, 0,
  720. 0, 1, 0,
  721. 0, 0, 1
  722. ];
  723. if ( n11 !== undefined ) {
  724. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  725. }
  726. }
  727. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  728. const te = this.elements;
  729. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  730. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  731. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  732. return this;
  733. }
  734. identity() {
  735. this.set(
  736. 1, 0, 0,
  737. 0, 1, 0,
  738. 0, 0, 1
  739. );
  740. return this;
  741. }
  742. copy( m ) {
  743. const te = this.elements;
  744. const me = m.elements;
  745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  746. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  747. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  748. return this;
  749. }
  750. extractBasis( xAxis, yAxis, zAxis ) {
  751. xAxis.setFromMatrix3Column( this, 0 );
  752. yAxis.setFromMatrix3Column( this, 1 );
  753. zAxis.setFromMatrix3Column( this, 2 );
  754. return this;
  755. }
  756. setFromMatrix4( m ) {
  757. const me = m.elements;
  758. this.set(
  759. me[ 0 ], me[ 4 ], me[ 8 ],
  760. me[ 1 ], me[ 5 ], me[ 9 ],
  761. me[ 2 ], me[ 6 ], me[ 10 ]
  762. );
  763. return this;
  764. }
  765. multiply( m ) {
  766. return this.multiplyMatrices( this, m );
  767. }
  768. premultiply( m ) {
  769. return this.multiplyMatrices( m, this );
  770. }
  771. multiplyMatrices( a, b ) {
  772. const ae = a.elements;
  773. const be = b.elements;
  774. const te = this.elements;
  775. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  776. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  777. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  778. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  779. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  780. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  781. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  782. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  783. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  784. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  785. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  786. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  787. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  788. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  789. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  790. return this;
  791. }
  792. multiplyScalar( s ) {
  793. const te = this.elements;
  794. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  795. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  796. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  797. return this;
  798. }
  799. determinant() {
  800. const te = this.elements;
  801. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  802. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  803. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  804. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  805. }
  806. invert() {
  807. const te = this.elements,
  808. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  809. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  810. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  811. t11 = n33 * n22 - n32 * n23,
  812. t12 = n32 * n13 - n33 * n12,
  813. t13 = n23 * n12 - n22 * n13,
  814. det = n11 * t11 + n21 * t12 + n31 * t13;
  815. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  816. const detInv = 1 / det;
  817. te[ 0 ] = t11 * detInv;
  818. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  819. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  820. te[ 3 ] = t12 * detInv;
  821. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  822. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  823. te[ 6 ] = t13 * detInv;
  824. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  825. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  826. return this;
  827. }
  828. transpose() {
  829. let tmp;
  830. const m = this.elements;
  831. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  832. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  833. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  834. return this;
  835. }
  836. getNormalMatrix( matrix4 ) {
  837. return this.setFromMatrix4( matrix4 ).invert().transpose();
  838. }
  839. transposeIntoArray( r ) {
  840. const m = this.elements;
  841. r[ 0 ] = m[ 0 ];
  842. r[ 1 ] = m[ 3 ];
  843. r[ 2 ] = m[ 6 ];
  844. r[ 3 ] = m[ 1 ];
  845. r[ 4 ] = m[ 4 ];
  846. r[ 5 ] = m[ 7 ];
  847. r[ 6 ] = m[ 2 ];
  848. r[ 7 ] = m[ 5 ];
  849. r[ 8 ] = m[ 8 ];
  850. return this;
  851. }
  852. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  853. const c = Math.cos( rotation );
  854. const s = Math.sin( rotation );
  855. this.set(
  856. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  857. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  858. 0, 0, 1
  859. );
  860. return this;
  861. }
  862. //
  863. scale( sx, sy ) {
  864. this.premultiply( _m3.makeScale( sx, sy ) );
  865. return this;
  866. }
  867. rotate( theta ) {
  868. this.premultiply( _m3.makeRotation( - theta ) );
  869. return this;
  870. }
  871. translate( tx, ty ) {
  872. this.premultiply( _m3.makeTranslation( tx, ty ) );
  873. return this;
  874. }
  875. // for 2D Transforms
  876. makeTranslation( x, y ) {
  877. if ( x.isVector2 ) {
  878. this.set(
  879. 1, 0, x.x,
  880. 0, 1, x.y,
  881. 0, 0, 1
  882. );
  883. } else {
  884. this.set(
  885. 1, 0, x,
  886. 0, 1, y,
  887. 0, 0, 1
  888. );
  889. }
  890. return this;
  891. }
  892. makeRotation( theta ) {
  893. // counterclockwise
  894. const c = Math.cos( theta );
  895. const s = Math.sin( theta );
  896. this.set(
  897. c, - s, 0,
  898. s, c, 0,
  899. 0, 0, 1
  900. );
  901. return this;
  902. }
  903. makeScale( x, y ) {
  904. this.set(
  905. x, 0, 0,
  906. 0, y, 0,
  907. 0, 0, 1
  908. );
  909. return this;
  910. }
  911. //
  912. equals( matrix ) {
  913. const te = this.elements;
  914. const me = matrix.elements;
  915. for ( let i = 0; i < 9; i ++ ) {
  916. if ( te[ i ] !== me[ i ] ) return false;
  917. }
  918. return true;
  919. }
  920. fromArray( array, offset = 0 ) {
  921. for ( let i = 0; i < 9; i ++ ) {
  922. this.elements[ i ] = array[ i + offset ];
  923. }
  924. return this;
  925. }
  926. toArray( array = [], offset = 0 ) {
  927. const te = this.elements;
  928. array[ offset ] = te[ 0 ];
  929. array[ offset + 1 ] = te[ 1 ];
  930. array[ offset + 2 ] = te[ 2 ];
  931. array[ offset + 3 ] = te[ 3 ];
  932. array[ offset + 4 ] = te[ 4 ];
  933. array[ offset + 5 ] = te[ 5 ];
  934. array[ offset + 6 ] = te[ 6 ];
  935. array[ offset + 7 ] = te[ 7 ];
  936. array[ offset + 8 ] = te[ 8 ];
  937. return array;
  938. }
  939. clone() {
  940. return new this.constructor().fromArray( this.elements );
  941. }
  942. }
  943. const _m3 = /*@__PURE__*/ new Matrix3();
  944. function arrayNeedsUint32$1( array ) {
  945. // assumes larger values usually on last
  946. for ( let i = array.length - 1; i >= 0; -- i ) {
  947. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  948. }
  949. return false;
  950. }
  951. const TYPED_ARRAYS = {
  952. Int8Array: Int8Array,
  953. Uint8Array: Uint8Array,
  954. Uint8ClampedArray: Uint8ClampedArray,
  955. Int16Array: Int16Array,
  956. Uint16Array: Uint16Array,
  957. Int32Array: Int32Array,
  958. Uint32Array: Uint32Array,
  959. Float32Array: Float32Array,
  960. Float64Array: Float64Array
  961. };
  962. function getTypedArray( type, buffer ) {
  963. return new TYPED_ARRAYS[ type ]( buffer );
  964. }
  965. function createElementNS( name ) {
  966. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  967. }
  968. function createCanvasElement() {
  969. const canvas = createElementNS( 'canvas' );
  970. canvas.style.display = 'block';
  971. return canvas;
  972. }
  973. const _cache$2 = {};
  974. function warnOnce( message ) {
  975. if ( message in _cache$2 ) return;
  976. _cache$2[ message ] = true;
  977. console.warn( message );
  978. }
  979. /**
  980. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  981. * or clipping. Based on W3C specifications for sRGB and Display P3,
  982. * and ICC specifications for the D50 connection space. Values in/out
  983. * are _linear_ sRGB and _linear_ Display P3.
  984. *
  985. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  986. *
  987. * Reference:
  988. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  989. */
  990. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  991. 0.8224621, 0.177538, 0.0,
  992. 0.0331941, 0.9668058, 0.0,
  993. 0.0170827, 0.0723974, 0.9105199,
  994. );
  995. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  996. 1.2249401, - 0.2249404, 0.0,
  997. - 0.0420569, 1.0420571, 0.0,
  998. - 0.0196376, - 0.0786361, 1.0982735
  999. );
  1000. /**
  1001. * Defines supported color spaces by transfer function and primaries,
  1002. * and provides conversions to/from the Linear-sRGB reference space.
  1003. */
  1004. const COLOR_SPACES = {
  1005. [ LinearSRGBColorSpace ]: {
  1006. transfer: LinearTransfer,
  1007. primaries: Rec709Primaries,
  1008. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1009. toReference: ( color ) => color,
  1010. fromReference: ( color ) => color,
  1011. },
  1012. [ SRGBColorSpace ]: {
  1013. transfer: SRGBTransfer,
  1014. primaries: Rec709Primaries,
  1015. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1016. toReference: ( color ) => color.convertSRGBToLinear(),
  1017. fromReference: ( color ) => color.convertLinearToSRGB(),
  1018. },
  1019. [ LinearDisplayP3ColorSpace ]: {
  1020. transfer: LinearTransfer,
  1021. primaries: P3Primaries,
  1022. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1023. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1024. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1025. },
  1026. [ DisplayP3ColorSpace ]: {
  1027. transfer: SRGBTransfer,
  1028. primaries: P3Primaries,
  1029. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1030. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1031. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1032. },
  1033. };
  1034. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1035. const ColorManagement = {
  1036. enabled: true,
  1037. _workingColorSpace: LinearSRGBColorSpace,
  1038. get workingColorSpace() {
  1039. return this._workingColorSpace;
  1040. },
  1041. set workingColorSpace( colorSpace ) {
  1042. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1043. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1044. }
  1045. this._workingColorSpace = colorSpace;
  1046. },
  1047. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1048. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1049. return color;
  1050. }
  1051. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1052. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1053. return targetFromReference( sourceToReference( color ) );
  1054. },
  1055. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1056. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1057. },
  1058. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1059. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1060. },
  1061. getPrimaries: function ( colorSpace ) {
  1062. return COLOR_SPACES[ colorSpace ].primaries;
  1063. },
  1064. getTransfer: function ( colorSpace ) {
  1065. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1066. return COLOR_SPACES[ colorSpace ].transfer;
  1067. },
  1068. getLuminanceCoefficients: function ( target, colorSpace = this._workingColorSpace ) {
  1069. return target.fromArray( COLOR_SPACES[ colorSpace ].luminanceCoefficients );
  1070. },
  1071. };
  1072. function SRGBToLinear( c ) {
  1073. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1074. }
  1075. function LinearToSRGB( c ) {
  1076. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1077. }
  1078. let _canvas;
  1079. class ImageUtils {
  1080. static getDataURL( image ) {
  1081. if ( /^data:/i.test( image.src ) ) {
  1082. return image.src;
  1083. }
  1084. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1085. return image.src;
  1086. }
  1087. let canvas;
  1088. if ( image instanceof HTMLCanvasElement ) {
  1089. canvas = image;
  1090. } else {
  1091. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1092. _canvas.width = image.width;
  1093. _canvas.height = image.height;
  1094. const context = _canvas.getContext( '2d' );
  1095. if ( image instanceof ImageData ) {
  1096. context.putImageData( image, 0, 0 );
  1097. } else {
  1098. context.drawImage( image, 0, 0, image.width, image.height );
  1099. }
  1100. canvas = _canvas;
  1101. }
  1102. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1103. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1104. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1105. } else {
  1106. return canvas.toDataURL( 'image/png' );
  1107. }
  1108. }
  1109. static sRGBToLinear( image ) {
  1110. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1111. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1112. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1113. const canvas = createElementNS( 'canvas' );
  1114. canvas.width = image.width;
  1115. canvas.height = image.height;
  1116. const context = canvas.getContext( '2d' );
  1117. context.drawImage( image, 0, 0, image.width, image.height );
  1118. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1119. const data = imageData.data;
  1120. for ( let i = 0; i < data.length; i ++ ) {
  1121. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1122. }
  1123. context.putImageData( imageData, 0, 0 );
  1124. return canvas;
  1125. } else if ( image.data ) {
  1126. const data = image.data.slice( 0 );
  1127. for ( let i = 0; i < data.length; i ++ ) {
  1128. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1129. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1130. } else {
  1131. // assuming float
  1132. data[ i ] = SRGBToLinear( data[ i ] );
  1133. }
  1134. }
  1135. return {
  1136. data: data,
  1137. width: image.width,
  1138. height: image.height
  1139. };
  1140. } else {
  1141. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1142. return image;
  1143. }
  1144. }
  1145. }
  1146. let _sourceId = 0;
  1147. class Source {
  1148. constructor( data = null ) {
  1149. this.isSource = true;
  1150. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1151. this.uuid = generateUUID();
  1152. this.data = data;
  1153. this.dataReady = true;
  1154. this.version = 0;
  1155. }
  1156. set needsUpdate( value ) {
  1157. if ( value === true ) this.version ++;
  1158. }
  1159. toJSON( meta ) {
  1160. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1161. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1162. return meta.images[ this.uuid ];
  1163. }
  1164. const output = {
  1165. uuid: this.uuid,
  1166. url: ''
  1167. };
  1168. const data = this.data;
  1169. if ( data !== null ) {
  1170. let url;
  1171. if ( Array.isArray( data ) ) {
  1172. // cube texture
  1173. url = [];
  1174. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1175. if ( data[ i ].isDataTexture ) {
  1176. url.push( serializeImage( data[ i ].image ) );
  1177. } else {
  1178. url.push( serializeImage( data[ i ] ) );
  1179. }
  1180. }
  1181. } else {
  1182. // texture
  1183. url = serializeImage( data );
  1184. }
  1185. output.url = url;
  1186. }
  1187. if ( ! isRootObject ) {
  1188. meta.images[ this.uuid ] = output;
  1189. }
  1190. return output;
  1191. }
  1192. }
  1193. function serializeImage( image ) {
  1194. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1195. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1196. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1197. // default images
  1198. return ImageUtils.getDataURL( image );
  1199. } else {
  1200. if ( image.data ) {
  1201. // images of DataTexture
  1202. return {
  1203. data: Array.from( image.data ),
  1204. width: image.width,
  1205. height: image.height,
  1206. type: image.data.constructor.name
  1207. };
  1208. } else {
  1209. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1210. return {};
  1211. }
  1212. }
  1213. }
  1214. let _textureId = 0;
  1215. class Texture extends EventDispatcher {
  1216. 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 ) {
  1217. super();
  1218. this.isTexture = true;
  1219. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1220. this.uuid = generateUUID();
  1221. this.name = '';
  1222. this.source = new Source( image );
  1223. this.mipmaps = [];
  1224. this.mapping = mapping;
  1225. this.channel = 0;
  1226. this.wrapS = wrapS;
  1227. this.wrapT = wrapT;
  1228. this.magFilter = magFilter;
  1229. this.minFilter = minFilter;
  1230. this.anisotropy = anisotropy;
  1231. this.format = format;
  1232. this.internalFormat = null;
  1233. this.type = type;
  1234. this.offset = new Vector2( 0, 0 );
  1235. this.repeat = new Vector2( 1, 1 );
  1236. this.center = new Vector2( 0, 0 );
  1237. this.rotation = 0;
  1238. this.matrixAutoUpdate = true;
  1239. this.matrix = new Matrix3();
  1240. this.generateMipmaps = true;
  1241. this.premultiplyAlpha = false;
  1242. this.flipY = true;
  1243. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1244. this.colorSpace = colorSpace;
  1245. this.userData = {};
  1246. this.version = 0;
  1247. this.onUpdate = null;
  1248. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1249. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1250. }
  1251. get image() {
  1252. return this.source.data;
  1253. }
  1254. set image( value = null ) {
  1255. this.source.data = value;
  1256. }
  1257. updateMatrix() {
  1258. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1259. }
  1260. clone() {
  1261. return new this.constructor().copy( this );
  1262. }
  1263. copy( source ) {
  1264. this.name = source.name;
  1265. this.source = source.source;
  1266. this.mipmaps = source.mipmaps.slice( 0 );
  1267. this.mapping = source.mapping;
  1268. this.channel = source.channel;
  1269. this.wrapS = source.wrapS;
  1270. this.wrapT = source.wrapT;
  1271. this.magFilter = source.magFilter;
  1272. this.minFilter = source.minFilter;
  1273. this.anisotropy = source.anisotropy;
  1274. this.format = source.format;
  1275. this.internalFormat = source.internalFormat;
  1276. this.type = source.type;
  1277. this.offset.copy( source.offset );
  1278. this.repeat.copy( source.repeat );
  1279. this.center.copy( source.center );
  1280. this.rotation = source.rotation;
  1281. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1282. this.matrix.copy( source.matrix );
  1283. this.generateMipmaps = source.generateMipmaps;
  1284. this.premultiplyAlpha = source.premultiplyAlpha;
  1285. this.flipY = source.flipY;
  1286. this.unpackAlignment = source.unpackAlignment;
  1287. this.colorSpace = source.colorSpace;
  1288. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1289. this.needsUpdate = true;
  1290. return this;
  1291. }
  1292. toJSON( meta ) {
  1293. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1294. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1295. return meta.textures[ this.uuid ];
  1296. }
  1297. const output = {
  1298. metadata: {
  1299. version: 4.6,
  1300. type: 'Texture',
  1301. generator: 'Texture.toJSON'
  1302. },
  1303. uuid: this.uuid,
  1304. name: this.name,
  1305. image: this.source.toJSON( meta ).uuid,
  1306. mapping: this.mapping,
  1307. channel: this.channel,
  1308. repeat: [ this.repeat.x, this.repeat.y ],
  1309. offset: [ this.offset.x, this.offset.y ],
  1310. center: [ this.center.x, this.center.y ],
  1311. rotation: this.rotation,
  1312. wrap: [ this.wrapS, this.wrapT ],
  1313. format: this.format,
  1314. internalFormat: this.internalFormat,
  1315. type: this.type,
  1316. colorSpace: this.colorSpace,
  1317. minFilter: this.minFilter,
  1318. magFilter: this.magFilter,
  1319. anisotropy: this.anisotropy,
  1320. flipY: this.flipY,
  1321. generateMipmaps: this.generateMipmaps,
  1322. premultiplyAlpha: this.premultiplyAlpha,
  1323. unpackAlignment: this.unpackAlignment
  1324. };
  1325. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1326. if ( ! isRootObject ) {
  1327. meta.textures[ this.uuid ] = output;
  1328. }
  1329. return output;
  1330. }
  1331. dispose() {
  1332. this.dispatchEvent( { type: 'dispose' } );
  1333. }
  1334. transformUv( uv ) {
  1335. if ( this.mapping !== UVMapping ) return uv;
  1336. uv.applyMatrix3( this.matrix );
  1337. if ( uv.x < 0 || uv.x > 1 ) {
  1338. switch ( this.wrapS ) {
  1339. case RepeatWrapping:
  1340. uv.x = uv.x - Math.floor( uv.x );
  1341. break;
  1342. case ClampToEdgeWrapping:
  1343. uv.x = uv.x < 0 ? 0 : 1;
  1344. break;
  1345. case MirroredRepeatWrapping:
  1346. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1347. uv.x = Math.ceil( uv.x ) - uv.x;
  1348. } else {
  1349. uv.x = uv.x - Math.floor( uv.x );
  1350. }
  1351. break;
  1352. }
  1353. }
  1354. if ( uv.y < 0 || uv.y > 1 ) {
  1355. switch ( this.wrapT ) {
  1356. case RepeatWrapping:
  1357. uv.y = uv.y - Math.floor( uv.y );
  1358. break;
  1359. case ClampToEdgeWrapping:
  1360. uv.y = uv.y < 0 ? 0 : 1;
  1361. break;
  1362. case MirroredRepeatWrapping:
  1363. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1364. uv.y = Math.ceil( uv.y ) - uv.y;
  1365. } else {
  1366. uv.y = uv.y - Math.floor( uv.y );
  1367. }
  1368. break;
  1369. }
  1370. }
  1371. if ( this.flipY ) {
  1372. uv.y = 1 - uv.y;
  1373. }
  1374. return uv;
  1375. }
  1376. set needsUpdate( value ) {
  1377. if ( value === true ) {
  1378. this.version ++;
  1379. this.source.needsUpdate = true;
  1380. }
  1381. }
  1382. set needsPMREMUpdate( value ) {
  1383. if ( value === true ) {
  1384. this.pmremVersion ++;
  1385. }
  1386. }
  1387. }
  1388. Texture.DEFAULT_IMAGE = null;
  1389. Texture.DEFAULT_MAPPING = UVMapping;
  1390. Texture.DEFAULT_ANISOTROPY = 1;
  1391. class Vector4 {
  1392. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1393. Vector4.prototype.isVector4 = true;
  1394. this.x = x;
  1395. this.y = y;
  1396. this.z = z;
  1397. this.w = w;
  1398. }
  1399. get width() {
  1400. return this.z;
  1401. }
  1402. set width( value ) {
  1403. this.z = value;
  1404. }
  1405. get height() {
  1406. return this.w;
  1407. }
  1408. set height( value ) {
  1409. this.w = value;
  1410. }
  1411. set( x, y, z, w ) {
  1412. this.x = x;
  1413. this.y = y;
  1414. this.z = z;
  1415. this.w = w;
  1416. return this;
  1417. }
  1418. setScalar( scalar ) {
  1419. this.x = scalar;
  1420. this.y = scalar;
  1421. this.z = scalar;
  1422. this.w = scalar;
  1423. return this;
  1424. }
  1425. setX( x ) {
  1426. this.x = x;
  1427. return this;
  1428. }
  1429. setY( y ) {
  1430. this.y = y;
  1431. return this;
  1432. }
  1433. setZ( z ) {
  1434. this.z = z;
  1435. return this;
  1436. }
  1437. setW( w ) {
  1438. this.w = w;
  1439. return this;
  1440. }
  1441. setComponent( index, value ) {
  1442. switch ( index ) {
  1443. case 0: this.x = value; break;
  1444. case 1: this.y = value; break;
  1445. case 2: this.z = value; break;
  1446. case 3: this.w = value; break;
  1447. default: throw new Error( 'index is out of range: ' + index );
  1448. }
  1449. return this;
  1450. }
  1451. getComponent( index ) {
  1452. switch ( index ) {
  1453. case 0: return this.x;
  1454. case 1: return this.y;
  1455. case 2: return this.z;
  1456. case 3: return this.w;
  1457. default: throw new Error( 'index is out of range: ' + index );
  1458. }
  1459. }
  1460. clone() {
  1461. return new this.constructor( this.x, this.y, this.z, this.w );
  1462. }
  1463. copy( v ) {
  1464. this.x = v.x;
  1465. this.y = v.y;
  1466. this.z = v.z;
  1467. this.w = ( v.w !== undefined ) ? v.w : 1;
  1468. return this;
  1469. }
  1470. add( v ) {
  1471. this.x += v.x;
  1472. this.y += v.y;
  1473. this.z += v.z;
  1474. this.w += v.w;
  1475. return this;
  1476. }
  1477. addScalar( s ) {
  1478. this.x += s;
  1479. this.y += s;
  1480. this.z += s;
  1481. this.w += s;
  1482. return this;
  1483. }
  1484. addVectors( a, b ) {
  1485. this.x = a.x + b.x;
  1486. this.y = a.y + b.y;
  1487. this.z = a.z + b.z;
  1488. this.w = a.w + b.w;
  1489. return this;
  1490. }
  1491. addScaledVector( v, s ) {
  1492. this.x += v.x * s;
  1493. this.y += v.y * s;
  1494. this.z += v.z * s;
  1495. this.w += v.w * s;
  1496. return this;
  1497. }
  1498. sub( v ) {
  1499. this.x -= v.x;
  1500. this.y -= v.y;
  1501. this.z -= v.z;
  1502. this.w -= v.w;
  1503. return this;
  1504. }
  1505. subScalar( s ) {
  1506. this.x -= s;
  1507. this.y -= s;
  1508. this.z -= s;
  1509. this.w -= s;
  1510. return this;
  1511. }
  1512. subVectors( a, b ) {
  1513. this.x = a.x - b.x;
  1514. this.y = a.y - b.y;
  1515. this.z = a.z - b.z;
  1516. this.w = a.w - b.w;
  1517. return this;
  1518. }
  1519. multiply( v ) {
  1520. this.x *= v.x;
  1521. this.y *= v.y;
  1522. this.z *= v.z;
  1523. this.w *= v.w;
  1524. return this;
  1525. }
  1526. multiplyScalar( scalar ) {
  1527. this.x *= scalar;
  1528. this.y *= scalar;
  1529. this.z *= scalar;
  1530. this.w *= scalar;
  1531. return this;
  1532. }
  1533. applyMatrix4( m ) {
  1534. const x = this.x, y = this.y, z = this.z, w = this.w;
  1535. const e = m.elements;
  1536. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1537. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1538. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1539. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1540. return this;
  1541. }
  1542. divideScalar( scalar ) {
  1543. return this.multiplyScalar( 1 / scalar );
  1544. }
  1545. setAxisAngleFromQuaternion( q ) {
  1546. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1547. // q is assumed to be normalized
  1548. this.w = 2 * Math.acos( q.w );
  1549. const s = Math.sqrt( 1 - q.w * q.w );
  1550. if ( s < 0.0001 ) {
  1551. this.x = 1;
  1552. this.y = 0;
  1553. this.z = 0;
  1554. } else {
  1555. this.x = q.x / s;
  1556. this.y = q.y / s;
  1557. this.z = q.z / s;
  1558. }
  1559. return this;
  1560. }
  1561. setAxisAngleFromRotationMatrix( m ) {
  1562. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1563. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1564. let angle, x, y, z; // variables for result
  1565. const epsilon = 0.01, // margin to allow for rounding errors
  1566. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1567. te = m.elements,
  1568. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1569. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1570. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1571. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1572. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1573. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1574. // singularity found
  1575. // first check for identity matrix which must have +1 for all terms
  1576. // in leading diagonal and zero in other terms
  1577. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1578. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1579. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1580. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1581. // this singularity is identity matrix so angle = 0
  1582. this.set( 1, 0, 0, 0 );
  1583. return this; // zero angle, arbitrary axis
  1584. }
  1585. // otherwise this singularity is angle = 180
  1586. angle = Math.PI;
  1587. const xx = ( m11 + 1 ) / 2;
  1588. const yy = ( m22 + 1 ) / 2;
  1589. const zz = ( m33 + 1 ) / 2;
  1590. const xy = ( m12 + m21 ) / 4;
  1591. const xz = ( m13 + m31 ) / 4;
  1592. const yz = ( m23 + m32 ) / 4;
  1593. if ( ( xx > yy ) && ( xx > zz ) ) {
  1594. // m11 is the largest diagonal term
  1595. if ( xx < epsilon ) {
  1596. x = 0;
  1597. y = 0.707106781;
  1598. z = 0.707106781;
  1599. } else {
  1600. x = Math.sqrt( xx );
  1601. y = xy / x;
  1602. z = xz / x;
  1603. }
  1604. } else if ( yy > zz ) {
  1605. // m22 is the largest diagonal term
  1606. if ( yy < epsilon ) {
  1607. x = 0.707106781;
  1608. y = 0;
  1609. z = 0.707106781;
  1610. } else {
  1611. y = Math.sqrt( yy );
  1612. x = xy / y;
  1613. z = yz / y;
  1614. }
  1615. } else {
  1616. // m33 is the largest diagonal term so base result on this
  1617. if ( zz < epsilon ) {
  1618. x = 0.707106781;
  1619. y = 0.707106781;
  1620. z = 0;
  1621. } else {
  1622. z = Math.sqrt( zz );
  1623. x = xz / z;
  1624. y = yz / z;
  1625. }
  1626. }
  1627. this.set( x, y, z, angle );
  1628. return this; // return 180 deg rotation
  1629. }
  1630. // as we have reached here there are no singularities so we can handle normally
  1631. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1632. ( m13 - m31 ) * ( m13 - m31 ) +
  1633. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1634. if ( Math.abs( s ) < 0.001 ) s = 1;
  1635. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1636. // caught by singularity test above, but I've left it in just in case
  1637. this.x = ( m32 - m23 ) / s;
  1638. this.y = ( m13 - m31 ) / s;
  1639. this.z = ( m21 - m12 ) / s;
  1640. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1641. return this;
  1642. }
  1643. setFromMatrixPosition( m ) {
  1644. const e = m.elements;
  1645. this.x = e[ 12 ];
  1646. this.y = e[ 13 ];
  1647. this.z = e[ 14 ];
  1648. this.w = e[ 15 ];
  1649. return this;
  1650. }
  1651. min( v ) {
  1652. this.x = Math.min( this.x, v.x );
  1653. this.y = Math.min( this.y, v.y );
  1654. this.z = Math.min( this.z, v.z );
  1655. this.w = Math.min( this.w, v.w );
  1656. return this;
  1657. }
  1658. max( v ) {
  1659. this.x = Math.max( this.x, v.x );
  1660. this.y = Math.max( this.y, v.y );
  1661. this.z = Math.max( this.z, v.z );
  1662. this.w = Math.max( this.w, v.w );
  1663. return this;
  1664. }
  1665. clamp( min, max ) {
  1666. // assumes min < max, componentwise
  1667. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1668. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1669. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1670. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1671. return this;
  1672. }
  1673. clampScalar( minVal, maxVal ) {
  1674. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1675. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1676. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1677. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1678. return this;
  1679. }
  1680. clampLength( min, max ) {
  1681. const length = this.length();
  1682. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1683. }
  1684. floor() {
  1685. this.x = Math.floor( this.x );
  1686. this.y = Math.floor( this.y );
  1687. this.z = Math.floor( this.z );
  1688. this.w = Math.floor( this.w );
  1689. return this;
  1690. }
  1691. ceil() {
  1692. this.x = Math.ceil( this.x );
  1693. this.y = Math.ceil( this.y );
  1694. this.z = Math.ceil( this.z );
  1695. this.w = Math.ceil( this.w );
  1696. return this;
  1697. }
  1698. round() {
  1699. this.x = Math.round( this.x );
  1700. this.y = Math.round( this.y );
  1701. this.z = Math.round( this.z );
  1702. this.w = Math.round( this.w );
  1703. return this;
  1704. }
  1705. roundToZero() {
  1706. this.x = Math.trunc( this.x );
  1707. this.y = Math.trunc( this.y );
  1708. this.z = Math.trunc( this.z );
  1709. this.w = Math.trunc( this.w );
  1710. return this;
  1711. }
  1712. negate() {
  1713. this.x = - this.x;
  1714. this.y = - this.y;
  1715. this.z = - this.z;
  1716. this.w = - this.w;
  1717. return this;
  1718. }
  1719. dot( v ) {
  1720. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1721. }
  1722. lengthSq() {
  1723. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1724. }
  1725. length() {
  1726. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1727. }
  1728. manhattanLength() {
  1729. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1730. }
  1731. normalize() {
  1732. return this.divideScalar( this.length() || 1 );
  1733. }
  1734. setLength( length ) {
  1735. return this.normalize().multiplyScalar( length );
  1736. }
  1737. lerp( v, alpha ) {
  1738. this.x += ( v.x - this.x ) * alpha;
  1739. this.y += ( v.y - this.y ) * alpha;
  1740. this.z += ( v.z - this.z ) * alpha;
  1741. this.w += ( v.w - this.w ) * alpha;
  1742. return this;
  1743. }
  1744. lerpVectors( v1, v2, alpha ) {
  1745. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1746. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1747. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1748. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1749. return this;
  1750. }
  1751. equals( v ) {
  1752. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1753. }
  1754. fromArray( array, offset = 0 ) {
  1755. this.x = array[ offset ];
  1756. this.y = array[ offset + 1 ];
  1757. this.z = array[ offset + 2 ];
  1758. this.w = array[ offset + 3 ];
  1759. return this;
  1760. }
  1761. toArray( array = [], offset = 0 ) {
  1762. array[ offset ] = this.x;
  1763. array[ offset + 1 ] = this.y;
  1764. array[ offset + 2 ] = this.z;
  1765. array[ offset + 3 ] = this.w;
  1766. return array;
  1767. }
  1768. fromBufferAttribute( attribute, index ) {
  1769. this.x = attribute.getX( index );
  1770. this.y = attribute.getY( index );
  1771. this.z = attribute.getZ( index );
  1772. this.w = attribute.getW( index );
  1773. return this;
  1774. }
  1775. random() {
  1776. this.x = Math.random();
  1777. this.y = Math.random();
  1778. this.z = Math.random();
  1779. this.w = Math.random();
  1780. return this;
  1781. }
  1782. *[ Symbol.iterator ]() {
  1783. yield this.x;
  1784. yield this.y;
  1785. yield this.z;
  1786. yield this.w;
  1787. }
  1788. }
  1789. /*
  1790. In options, we can specify:
  1791. * Texture parameters for an auto-generated target texture
  1792. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1793. */
  1794. class RenderTarget extends EventDispatcher {
  1795. constructor( width = 1, height = 1, options = {} ) {
  1796. super();
  1797. this.isRenderTarget = true;
  1798. this.width = width;
  1799. this.height = height;
  1800. this.depth = 1;
  1801. this.scissor = new Vector4( 0, 0, width, height );
  1802. this.scissorTest = false;
  1803. this.viewport = new Vector4( 0, 0, width, height );
  1804. const image = { width: width, height: height, depth: 1 };
  1805. options = Object.assign( {
  1806. generateMipmaps: false,
  1807. internalFormat: null,
  1808. minFilter: LinearFilter,
  1809. depthBuffer: true,
  1810. stencilBuffer: false,
  1811. resolveDepthBuffer: true,
  1812. resolveStencilBuffer: true,
  1813. depthTexture: null,
  1814. samples: 0,
  1815. count: 1
  1816. }, options );
  1817. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1818. texture.flipY = false;
  1819. texture.generateMipmaps = options.generateMipmaps;
  1820. texture.internalFormat = options.internalFormat;
  1821. this.textures = [];
  1822. const count = options.count;
  1823. for ( let i = 0; i < count; i ++ ) {
  1824. this.textures[ i ] = texture.clone();
  1825. this.textures[ i ].isRenderTargetTexture = true;
  1826. }
  1827. this.depthBuffer = options.depthBuffer;
  1828. this.stencilBuffer = options.stencilBuffer;
  1829. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1830. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1831. this.depthTexture = options.depthTexture;
  1832. this.samples = options.samples;
  1833. }
  1834. get texture() {
  1835. return this.textures[ 0 ];
  1836. }
  1837. set texture( value ) {
  1838. this.textures[ 0 ] = value;
  1839. }
  1840. setSize( width, height, depth = 1 ) {
  1841. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1842. this.width = width;
  1843. this.height = height;
  1844. this.depth = depth;
  1845. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1846. this.textures[ i ].image.width = width;
  1847. this.textures[ i ].image.height = height;
  1848. this.textures[ i ].image.depth = depth;
  1849. }
  1850. this.dispose();
  1851. }
  1852. this.viewport.set( 0, 0, width, height );
  1853. this.scissor.set( 0, 0, width, height );
  1854. }
  1855. clone() {
  1856. return new this.constructor().copy( this );
  1857. }
  1858. copy( source ) {
  1859. this.width = source.width;
  1860. this.height = source.height;
  1861. this.depth = source.depth;
  1862. this.scissor.copy( source.scissor );
  1863. this.scissorTest = source.scissorTest;
  1864. this.viewport.copy( source.viewport );
  1865. this.textures.length = 0;
  1866. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1867. this.textures[ i ] = source.textures[ i ].clone();
  1868. this.textures[ i ].isRenderTargetTexture = true;
  1869. }
  1870. // ensure image object is not shared, see #20328
  1871. const image = Object.assign( {}, source.texture.image );
  1872. this.texture.source = new Source( image );
  1873. this.depthBuffer = source.depthBuffer;
  1874. this.stencilBuffer = source.stencilBuffer;
  1875. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1876. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1877. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1878. this.samples = source.samples;
  1879. return this;
  1880. }
  1881. dispose() {
  1882. this.dispatchEvent( { type: 'dispose' } );
  1883. }
  1884. }
  1885. class WebGLRenderTarget extends RenderTarget {
  1886. constructor( width = 1, height = 1, options = {} ) {
  1887. super( width, height, options );
  1888. this.isWebGLRenderTarget = true;
  1889. }
  1890. }
  1891. class DataArrayTexture extends Texture {
  1892. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1893. super( null );
  1894. this.isDataArrayTexture = true;
  1895. this.image = { data, width, height, depth };
  1896. this.magFilter = NearestFilter;
  1897. this.minFilter = NearestFilter;
  1898. this.wrapR = ClampToEdgeWrapping;
  1899. this.generateMipmaps = false;
  1900. this.flipY = false;
  1901. this.unpackAlignment = 1;
  1902. this.layerUpdates = new Set();
  1903. }
  1904. addLayerUpdate( layerIndex ) {
  1905. this.layerUpdates.add( layerIndex );
  1906. }
  1907. clearLayerUpdates() {
  1908. this.layerUpdates.clear();
  1909. }
  1910. }
  1911. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1912. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1913. super( width, height, options );
  1914. this.isWebGLArrayRenderTarget = true;
  1915. this.depth = depth;
  1916. this.texture = new DataArrayTexture( null, width, height, depth );
  1917. this.texture.isRenderTargetTexture = true;
  1918. }
  1919. }
  1920. class Data3DTexture extends Texture {
  1921. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1922. // We're going to add .setXXX() methods for setting properties later.
  1923. // Users can still set in DataTexture3D directly.
  1924. //
  1925. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1926. // texture.anisotropy = 16;
  1927. //
  1928. // See #14839
  1929. super( null );
  1930. this.isData3DTexture = true;
  1931. this.image = { data, width, height, depth };
  1932. this.magFilter = NearestFilter;
  1933. this.minFilter = NearestFilter;
  1934. this.wrapR = ClampToEdgeWrapping;
  1935. this.generateMipmaps = false;
  1936. this.flipY = false;
  1937. this.unpackAlignment = 1;
  1938. }
  1939. }
  1940. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1941. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1942. super( width, height, options );
  1943. this.isWebGL3DRenderTarget = true;
  1944. this.depth = depth;
  1945. this.texture = new Data3DTexture( null, width, height, depth );
  1946. this.texture.isRenderTargetTexture = true;
  1947. }
  1948. }
  1949. class Quaternion {
  1950. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1951. this.isQuaternion = true;
  1952. this._x = x;
  1953. this._y = y;
  1954. this._z = z;
  1955. this._w = w;
  1956. }
  1957. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1958. // fuzz-free, array-based Quaternion SLERP operation
  1959. let x0 = src0[ srcOffset0 + 0 ],
  1960. y0 = src0[ srcOffset0 + 1 ],
  1961. z0 = src0[ srcOffset0 + 2 ],
  1962. w0 = src0[ srcOffset0 + 3 ];
  1963. const x1 = src1[ srcOffset1 + 0 ],
  1964. y1 = src1[ srcOffset1 + 1 ],
  1965. z1 = src1[ srcOffset1 + 2 ],
  1966. w1 = src1[ srcOffset1 + 3 ];
  1967. if ( t === 0 ) {
  1968. dst[ dstOffset + 0 ] = x0;
  1969. dst[ dstOffset + 1 ] = y0;
  1970. dst[ dstOffset + 2 ] = z0;
  1971. dst[ dstOffset + 3 ] = w0;
  1972. return;
  1973. }
  1974. if ( t === 1 ) {
  1975. dst[ dstOffset + 0 ] = x1;
  1976. dst[ dstOffset + 1 ] = y1;
  1977. dst[ dstOffset + 2 ] = z1;
  1978. dst[ dstOffset + 3 ] = w1;
  1979. return;
  1980. }
  1981. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1982. let s = 1 - t;
  1983. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1984. dir = ( cos >= 0 ? 1 : - 1 ),
  1985. sqrSin = 1 - cos * cos;
  1986. // Skip the Slerp for tiny steps to avoid numeric problems:
  1987. if ( sqrSin > Number.EPSILON ) {
  1988. const sin = Math.sqrt( sqrSin ),
  1989. len = Math.atan2( sin, cos * dir );
  1990. s = Math.sin( s * len ) / sin;
  1991. t = Math.sin( t * len ) / sin;
  1992. }
  1993. const tDir = t * dir;
  1994. x0 = x0 * s + x1 * tDir;
  1995. y0 = y0 * s + y1 * tDir;
  1996. z0 = z0 * s + z1 * tDir;
  1997. w0 = w0 * s + w1 * tDir;
  1998. // Normalize in case we just did a lerp:
  1999. if ( s === 1 - t ) {
  2000. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2001. x0 *= f;
  2002. y0 *= f;
  2003. z0 *= f;
  2004. w0 *= f;
  2005. }
  2006. }
  2007. dst[ dstOffset ] = x0;
  2008. dst[ dstOffset + 1 ] = y0;
  2009. dst[ dstOffset + 2 ] = z0;
  2010. dst[ dstOffset + 3 ] = w0;
  2011. }
  2012. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2013. const x0 = src0[ srcOffset0 ];
  2014. const y0 = src0[ srcOffset0 + 1 ];
  2015. const z0 = src0[ srcOffset0 + 2 ];
  2016. const w0 = src0[ srcOffset0 + 3 ];
  2017. const x1 = src1[ srcOffset1 ];
  2018. const y1 = src1[ srcOffset1 + 1 ];
  2019. const z1 = src1[ srcOffset1 + 2 ];
  2020. const w1 = src1[ srcOffset1 + 3 ];
  2021. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2022. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2023. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2024. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2025. return dst;
  2026. }
  2027. get x() {
  2028. return this._x;
  2029. }
  2030. set x( value ) {
  2031. this._x = value;
  2032. this._onChangeCallback();
  2033. }
  2034. get y() {
  2035. return this._y;
  2036. }
  2037. set y( value ) {
  2038. this._y = value;
  2039. this._onChangeCallback();
  2040. }
  2041. get z() {
  2042. return this._z;
  2043. }
  2044. set z( value ) {
  2045. this._z = value;
  2046. this._onChangeCallback();
  2047. }
  2048. get w() {
  2049. return this._w;
  2050. }
  2051. set w( value ) {
  2052. this._w = value;
  2053. this._onChangeCallback();
  2054. }
  2055. set( x, y, z, w ) {
  2056. this._x = x;
  2057. this._y = y;
  2058. this._z = z;
  2059. this._w = w;
  2060. this._onChangeCallback();
  2061. return this;
  2062. }
  2063. clone() {
  2064. return new this.constructor( this._x, this._y, this._z, this._w );
  2065. }
  2066. copy( quaternion ) {
  2067. this._x = quaternion.x;
  2068. this._y = quaternion.y;
  2069. this._z = quaternion.z;
  2070. this._w = quaternion.w;
  2071. this._onChangeCallback();
  2072. return this;
  2073. }
  2074. setFromEuler( euler, update = true ) {
  2075. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2076. // http://www.mathworks.com/matlabcentral/fileexchange/
  2077. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2078. // content/SpinCalc.m
  2079. const cos = Math.cos;
  2080. const sin = Math.sin;
  2081. const c1 = cos( x / 2 );
  2082. const c2 = cos( y / 2 );
  2083. const c3 = cos( z / 2 );
  2084. const s1 = sin( x / 2 );
  2085. const s2 = sin( y / 2 );
  2086. const s3 = sin( z / 2 );
  2087. switch ( order ) {
  2088. case 'XYZ':
  2089. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2090. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2091. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2092. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2093. break;
  2094. case 'YXZ':
  2095. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2096. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2097. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2098. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2099. break;
  2100. case 'ZXY':
  2101. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2102. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2103. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2104. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2105. break;
  2106. case 'ZYX':
  2107. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2108. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2109. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2110. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2111. break;
  2112. case 'YZX':
  2113. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2114. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2115. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2116. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2117. break;
  2118. case 'XZY':
  2119. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2120. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2121. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2122. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2123. break;
  2124. default:
  2125. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2126. }
  2127. if ( update === true ) this._onChangeCallback();
  2128. return this;
  2129. }
  2130. setFromAxisAngle( axis, angle ) {
  2131. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2132. // assumes axis is normalized
  2133. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2134. this._x = axis.x * s;
  2135. this._y = axis.y * s;
  2136. this._z = axis.z * s;
  2137. this._w = Math.cos( halfAngle );
  2138. this._onChangeCallback();
  2139. return this;
  2140. }
  2141. setFromRotationMatrix( m ) {
  2142. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2143. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2144. const te = m.elements,
  2145. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2146. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2147. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2148. trace = m11 + m22 + m33;
  2149. if ( trace > 0 ) {
  2150. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2151. this._w = 0.25 / s;
  2152. this._x = ( m32 - m23 ) * s;
  2153. this._y = ( m13 - m31 ) * s;
  2154. this._z = ( m21 - m12 ) * s;
  2155. } else if ( m11 > m22 && m11 > m33 ) {
  2156. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2157. this._w = ( m32 - m23 ) / s;
  2158. this._x = 0.25 * s;
  2159. this._y = ( m12 + m21 ) / s;
  2160. this._z = ( m13 + m31 ) / s;
  2161. } else if ( m22 > m33 ) {
  2162. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2163. this._w = ( m13 - m31 ) / s;
  2164. this._x = ( m12 + m21 ) / s;
  2165. this._y = 0.25 * s;
  2166. this._z = ( m23 + m32 ) / s;
  2167. } else {
  2168. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2169. this._w = ( m21 - m12 ) / s;
  2170. this._x = ( m13 + m31 ) / s;
  2171. this._y = ( m23 + m32 ) / s;
  2172. this._z = 0.25 * s;
  2173. }
  2174. this._onChangeCallback();
  2175. return this;
  2176. }
  2177. setFromUnitVectors( vFrom, vTo ) {
  2178. // assumes direction vectors vFrom and vTo are normalized
  2179. let r = vFrom.dot( vTo ) + 1;
  2180. if ( r < Number.EPSILON ) {
  2181. // vFrom and vTo point in opposite directions
  2182. r = 0;
  2183. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2184. this._x = - vFrom.y;
  2185. this._y = vFrom.x;
  2186. this._z = 0;
  2187. this._w = r;
  2188. } else {
  2189. this._x = 0;
  2190. this._y = - vFrom.z;
  2191. this._z = vFrom.y;
  2192. this._w = r;
  2193. }
  2194. } else {
  2195. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2196. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2197. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2198. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2199. this._w = r;
  2200. }
  2201. return this.normalize();
  2202. }
  2203. angleTo( q ) {
  2204. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2205. }
  2206. rotateTowards( q, step ) {
  2207. const angle = this.angleTo( q );
  2208. if ( angle === 0 ) return this;
  2209. const t = Math.min( 1, step / angle );
  2210. this.slerp( q, t );
  2211. return this;
  2212. }
  2213. identity() {
  2214. return this.set( 0, 0, 0, 1 );
  2215. }
  2216. invert() {
  2217. // quaternion is assumed to have unit length
  2218. return this.conjugate();
  2219. }
  2220. conjugate() {
  2221. this._x *= - 1;
  2222. this._y *= - 1;
  2223. this._z *= - 1;
  2224. this._onChangeCallback();
  2225. return this;
  2226. }
  2227. dot( v ) {
  2228. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2229. }
  2230. lengthSq() {
  2231. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2232. }
  2233. length() {
  2234. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2235. }
  2236. normalize() {
  2237. let l = this.length();
  2238. if ( l === 0 ) {
  2239. this._x = 0;
  2240. this._y = 0;
  2241. this._z = 0;
  2242. this._w = 1;
  2243. } else {
  2244. l = 1 / l;
  2245. this._x = this._x * l;
  2246. this._y = this._y * l;
  2247. this._z = this._z * l;
  2248. this._w = this._w * l;
  2249. }
  2250. this._onChangeCallback();
  2251. return this;
  2252. }
  2253. multiply( q ) {
  2254. return this.multiplyQuaternions( this, q );
  2255. }
  2256. premultiply( q ) {
  2257. return this.multiplyQuaternions( q, this );
  2258. }
  2259. multiplyQuaternions( a, b ) {
  2260. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2261. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2262. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2263. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2264. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2265. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2266. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2267. this._onChangeCallback();
  2268. return this;
  2269. }
  2270. slerp( qb, t ) {
  2271. if ( t === 0 ) return this;
  2272. if ( t === 1 ) return this.copy( qb );
  2273. const x = this._x, y = this._y, z = this._z, w = this._w;
  2274. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2275. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2276. if ( cosHalfTheta < 0 ) {
  2277. this._w = - qb._w;
  2278. this._x = - qb._x;
  2279. this._y = - qb._y;
  2280. this._z = - qb._z;
  2281. cosHalfTheta = - cosHalfTheta;
  2282. } else {
  2283. this.copy( qb );
  2284. }
  2285. if ( cosHalfTheta >= 1.0 ) {
  2286. this._w = w;
  2287. this._x = x;
  2288. this._y = y;
  2289. this._z = z;
  2290. return this;
  2291. }
  2292. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2293. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2294. const s = 1 - t;
  2295. this._w = s * w + t * this._w;
  2296. this._x = s * x + t * this._x;
  2297. this._y = s * y + t * this._y;
  2298. this._z = s * z + t * this._z;
  2299. this.normalize(); // normalize calls _onChangeCallback()
  2300. return this;
  2301. }
  2302. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2303. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2304. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2305. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2306. this._w = ( w * ratioA + this._w * ratioB );
  2307. this._x = ( x * ratioA + this._x * ratioB );
  2308. this._y = ( y * ratioA + this._y * ratioB );
  2309. this._z = ( z * ratioA + this._z * ratioB );
  2310. this._onChangeCallback();
  2311. return this;
  2312. }
  2313. slerpQuaternions( qa, qb, t ) {
  2314. return this.copy( qa ).slerp( qb, t );
  2315. }
  2316. random() {
  2317. // sets this quaternion to a uniform random unit quaternnion
  2318. // Ken Shoemake
  2319. // Uniform random rotations
  2320. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2321. const theta1 = 2 * Math.PI * Math.random();
  2322. const theta2 = 2 * Math.PI * Math.random();
  2323. const x0 = Math.random();
  2324. const r1 = Math.sqrt( 1 - x0 );
  2325. const r2 = Math.sqrt( x0 );
  2326. return this.set(
  2327. r1 * Math.sin( theta1 ),
  2328. r1 * Math.cos( theta1 ),
  2329. r2 * Math.sin( theta2 ),
  2330. r2 * Math.cos( theta2 ),
  2331. );
  2332. }
  2333. equals( quaternion ) {
  2334. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2335. }
  2336. fromArray( array, offset = 0 ) {
  2337. this._x = array[ offset ];
  2338. this._y = array[ offset + 1 ];
  2339. this._z = array[ offset + 2 ];
  2340. this._w = array[ offset + 3 ];
  2341. this._onChangeCallback();
  2342. return this;
  2343. }
  2344. toArray( array = [], offset = 0 ) {
  2345. array[ offset ] = this._x;
  2346. array[ offset + 1 ] = this._y;
  2347. array[ offset + 2 ] = this._z;
  2348. array[ offset + 3 ] = this._w;
  2349. return array;
  2350. }
  2351. fromBufferAttribute( attribute, index ) {
  2352. this._x = attribute.getX( index );
  2353. this._y = attribute.getY( index );
  2354. this._z = attribute.getZ( index );
  2355. this._w = attribute.getW( index );
  2356. this._onChangeCallback();
  2357. return this;
  2358. }
  2359. toJSON() {
  2360. return this.toArray();
  2361. }
  2362. _onChange( callback ) {
  2363. this._onChangeCallback = callback;
  2364. return this;
  2365. }
  2366. _onChangeCallback() {}
  2367. *[ Symbol.iterator ]() {
  2368. yield this._x;
  2369. yield this._y;
  2370. yield this._z;
  2371. yield this._w;
  2372. }
  2373. }
  2374. class Vector3 {
  2375. constructor( x = 0, y = 0, z = 0 ) {
  2376. Vector3.prototype.isVector3 = true;
  2377. this.x = x;
  2378. this.y = y;
  2379. this.z = z;
  2380. }
  2381. set( x, y, z ) {
  2382. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2383. this.x = x;
  2384. this.y = y;
  2385. this.z = z;
  2386. return this;
  2387. }
  2388. setScalar( scalar ) {
  2389. this.x = scalar;
  2390. this.y = scalar;
  2391. this.z = scalar;
  2392. return this;
  2393. }
  2394. setX( x ) {
  2395. this.x = x;
  2396. return this;
  2397. }
  2398. setY( y ) {
  2399. this.y = y;
  2400. return this;
  2401. }
  2402. setZ( z ) {
  2403. this.z = z;
  2404. return this;
  2405. }
  2406. setComponent( index, value ) {
  2407. switch ( index ) {
  2408. case 0: this.x = value; break;
  2409. case 1: this.y = value; break;
  2410. case 2: this.z = value; break;
  2411. default: throw new Error( 'index is out of range: ' + index );
  2412. }
  2413. return this;
  2414. }
  2415. getComponent( index ) {
  2416. switch ( index ) {
  2417. case 0: return this.x;
  2418. case 1: return this.y;
  2419. case 2: return this.z;
  2420. default: throw new Error( 'index is out of range: ' + index );
  2421. }
  2422. }
  2423. clone() {
  2424. return new this.constructor( this.x, this.y, this.z );
  2425. }
  2426. copy( v ) {
  2427. this.x = v.x;
  2428. this.y = v.y;
  2429. this.z = v.z;
  2430. return this;
  2431. }
  2432. add( v ) {
  2433. this.x += v.x;
  2434. this.y += v.y;
  2435. this.z += v.z;
  2436. return this;
  2437. }
  2438. addScalar( s ) {
  2439. this.x += s;
  2440. this.y += s;
  2441. this.z += s;
  2442. return this;
  2443. }
  2444. addVectors( a, b ) {
  2445. this.x = a.x + b.x;
  2446. this.y = a.y + b.y;
  2447. this.z = a.z + b.z;
  2448. return this;
  2449. }
  2450. addScaledVector( v, s ) {
  2451. this.x += v.x * s;
  2452. this.y += v.y * s;
  2453. this.z += v.z * s;
  2454. return this;
  2455. }
  2456. sub( v ) {
  2457. this.x -= v.x;
  2458. this.y -= v.y;
  2459. this.z -= v.z;
  2460. return this;
  2461. }
  2462. subScalar( s ) {
  2463. this.x -= s;
  2464. this.y -= s;
  2465. this.z -= s;
  2466. return this;
  2467. }
  2468. subVectors( a, b ) {
  2469. this.x = a.x - b.x;
  2470. this.y = a.y - b.y;
  2471. this.z = a.z - b.z;
  2472. return this;
  2473. }
  2474. multiply( v ) {
  2475. this.x *= v.x;
  2476. this.y *= v.y;
  2477. this.z *= v.z;
  2478. return this;
  2479. }
  2480. multiplyScalar( scalar ) {
  2481. this.x *= scalar;
  2482. this.y *= scalar;
  2483. this.z *= scalar;
  2484. return this;
  2485. }
  2486. multiplyVectors( a, b ) {
  2487. this.x = a.x * b.x;
  2488. this.y = a.y * b.y;
  2489. this.z = a.z * b.z;
  2490. return this;
  2491. }
  2492. applyEuler( euler ) {
  2493. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2494. }
  2495. applyAxisAngle( axis, angle ) {
  2496. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2497. }
  2498. applyMatrix3( m ) {
  2499. const x = this.x, y = this.y, z = this.z;
  2500. const e = m.elements;
  2501. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2502. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2503. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2504. return this;
  2505. }
  2506. applyNormalMatrix( m ) {
  2507. return this.applyMatrix3( m ).normalize();
  2508. }
  2509. applyMatrix4( m ) {
  2510. const x = this.x, y = this.y, z = this.z;
  2511. const e = m.elements;
  2512. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2513. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2514. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2515. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2516. return this;
  2517. }
  2518. applyQuaternion( q ) {
  2519. // quaternion q is assumed to have unit length
  2520. const vx = this.x, vy = this.y, vz = this.z;
  2521. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2522. // t = 2 * cross( q.xyz, v );
  2523. const tx = 2 * ( qy * vz - qz * vy );
  2524. const ty = 2 * ( qz * vx - qx * vz );
  2525. const tz = 2 * ( qx * vy - qy * vx );
  2526. // v + q.w * t + cross( q.xyz, t );
  2527. this.x = vx + qw * tx + qy * tz - qz * ty;
  2528. this.y = vy + qw * ty + qz * tx - qx * tz;
  2529. this.z = vz + qw * tz + qx * ty - qy * tx;
  2530. return this;
  2531. }
  2532. project( camera ) {
  2533. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2534. }
  2535. unproject( camera ) {
  2536. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2537. }
  2538. transformDirection( m ) {
  2539. // input: THREE.Matrix4 affine matrix
  2540. // vector interpreted as a direction
  2541. const x = this.x, y = this.y, z = this.z;
  2542. const e = m.elements;
  2543. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2544. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2545. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2546. return this.normalize();
  2547. }
  2548. divide( v ) {
  2549. this.x /= v.x;
  2550. this.y /= v.y;
  2551. this.z /= v.z;
  2552. return this;
  2553. }
  2554. divideScalar( scalar ) {
  2555. return this.multiplyScalar( 1 / scalar );
  2556. }
  2557. min( v ) {
  2558. this.x = Math.min( this.x, v.x );
  2559. this.y = Math.min( this.y, v.y );
  2560. this.z = Math.min( this.z, v.z );
  2561. return this;
  2562. }
  2563. max( v ) {
  2564. this.x = Math.max( this.x, v.x );
  2565. this.y = Math.max( this.y, v.y );
  2566. this.z = Math.max( this.z, v.z );
  2567. return this;
  2568. }
  2569. clamp( min, max ) {
  2570. // assumes min < max, componentwise
  2571. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2572. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2573. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2574. return this;
  2575. }
  2576. clampScalar( minVal, maxVal ) {
  2577. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2578. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2579. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2580. return this;
  2581. }
  2582. clampLength( min, max ) {
  2583. const length = this.length();
  2584. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2585. }
  2586. floor() {
  2587. this.x = Math.floor( this.x );
  2588. this.y = Math.floor( this.y );
  2589. this.z = Math.floor( this.z );
  2590. return this;
  2591. }
  2592. ceil() {
  2593. this.x = Math.ceil( this.x );
  2594. this.y = Math.ceil( this.y );
  2595. this.z = Math.ceil( this.z );
  2596. return this;
  2597. }
  2598. round() {
  2599. this.x = Math.round( this.x );
  2600. this.y = Math.round( this.y );
  2601. this.z = Math.round( this.z );
  2602. return this;
  2603. }
  2604. roundToZero() {
  2605. this.x = Math.trunc( this.x );
  2606. this.y = Math.trunc( this.y );
  2607. this.z = Math.trunc( this.z );
  2608. return this;
  2609. }
  2610. negate() {
  2611. this.x = - this.x;
  2612. this.y = - this.y;
  2613. this.z = - this.z;
  2614. return this;
  2615. }
  2616. dot( v ) {
  2617. return this.x * v.x + this.y * v.y + this.z * v.z;
  2618. }
  2619. // TODO lengthSquared?
  2620. lengthSq() {
  2621. return this.x * this.x + this.y * this.y + this.z * this.z;
  2622. }
  2623. length() {
  2624. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2625. }
  2626. manhattanLength() {
  2627. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2628. }
  2629. normalize() {
  2630. return this.divideScalar( this.length() || 1 );
  2631. }
  2632. setLength( length ) {
  2633. return this.normalize().multiplyScalar( length );
  2634. }
  2635. lerp( v, alpha ) {
  2636. this.x += ( v.x - this.x ) * alpha;
  2637. this.y += ( v.y - this.y ) * alpha;
  2638. this.z += ( v.z - this.z ) * alpha;
  2639. return this;
  2640. }
  2641. lerpVectors( v1, v2, alpha ) {
  2642. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2643. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2644. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2645. return this;
  2646. }
  2647. cross( v ) {
  2648. return this.crossVectors( this, v );
  2649. }
  2650. crossVectors( a, b ) {
  2651. const ax = a.x, ay = a.y, az = a.z;
  2652. const bx = b.x, by = b.y, bz = b.z;
  2653. this.x = ay * bz - az * by;
  2654. this.y = az * bx - ax * bz;
  2655. this.z = ax * by - ay * bx;
  2656. return this;
  2657. }
  2658. projectOnVector( v ) {
  2659. const denominator = v.lengthSq();
  2660. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2661. const scalar = v.dot( this ) / denominator;
  2662. return this.copy( v ).multiplyScalar( scalar );
  2663. }
  2664. projectOnPlane( planeNormal ) {
  2665. _vector$c.copy( this ).projectOnVector( planeNormal );
  2666. return this.sub( _vector$c );
  2667. }
  2668. reflect( normal ) {
  2669. // reflect incident vector off plane orthogonal to normal
  2670. // normal is assumed to have unit length
  2671. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2672. }
  2673. angleTo( v ) {
  2674. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2675. if ( denominator === 0 ) return Math.PI / 2;
  2676. const theta = this.dot( v ) / denominator;
  2677. // clamp, to handle numerical problems
  2678. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2679. }
  2680. distanceTo( v ) {
  2681. return Math.sqrt( this.distanceToSquared( v ) );
  2682. }
  2683. distanceToSquared( v ) {
  2684. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2685. return dx * dx + dy * dy + dz * dz;
  2686. }
  2687. manhattanDistanceTo( v ) {
  2688. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2689. }
  2690. setFromSpherical( s ) {
  2691. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2692. }
  2693. setFromSphericalCoords( radius, phi, theta ) {
  2694. const sinPhiRadius = Math.sin( phi ) * radius;
  2695. this.x = sinPhiRadius * Math.sin( theta );
  2696. this.y = Math.cos( phi ) * radius;
  2697. this.z = sinPhiRadius * Math.cos( theta );
  2698. return this;
  2699. }
  2700. setFromCylindrical( c ) {
  2701. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2702. }
  2703. setFromCylindricalCoords( radius, theta, y ) {
  2704. this.x = radius * Math.sin( theta );
  2705. this.y = y;
  2706. this.z = radius * Math.cos( theta );
  2707. return this;
  2708. }
  2709. setFromMatrixPosition( m ) {
  2710. const e = m.elements;
  2711. this.x = e[ 12 ];
  2712. this.y = e[ 13 ];
  2713. this.z = e[ 14 ];
  2714. return this;
  2715. }
  2716. setFromMatrixScale( m ) {
  2717. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2718. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2719. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2720. this.x = sx;
  2721. this.y = sy;
  2722. this.z = sz;
  2723. return this;
  2724. }
  2725. setFromMatrixColumn( m, index ) {
  2726. return this.fromArray( m.elements, index * 4 );
  2727. }
  2728. setFromMatrix3Column( m, index ) {
  2729. return this.fromArray( m.elements, index * 3 );
  2730. }
  2731. setFromEuler( e ) {
  2732. this.x = e._x;
  2733. this.y = e._y;
  2734. this.z = e._z;
  2735. return this;
  2736. }
  2737. setFromColor( c ) {
  2738. this.x = c.r;
  2739. this.y = c.g;
  2740. this.z = c.b;
  2741. return this;
  2742. }
  2743. equals( v ) {
  2744. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2745. }
  2746. fromArray( array, offset = 0 ) {
  2747. this.x = array[ offset ];
  2748. this.y = array[ offset + 1 ];
  2749. this.z = array[ offset + 2 ];
  2750. return this;
  2751. }
  2752. toArray( array = [], offset = 0 ) {
  2753. array[ offset ] = this.x;
  2754. array[ offset + 1 ] = this.y;
  2755. array[ offset + 2 ] = this.z;
  2756. return array;
  2757. }
  2758. fromBufferAttribute( attribute, index ) {
  2759. this.x = attribute.getX( index );
  2760. this.y = attribute.getY( index );
  2761. this.z = attribute.getZ( index );
  2762. return this;
  2763. }
  2764. random() {
  2765. this.x = Math.random();
  2766. this.y = Math.random();
  2767. this.z = Math.random();
  2768. return this;
  2769. }
  2770. randomDirection() {
  2771. // https://mathworld.wolfram.com/SpherePointPicking.html
  2772. const theta = Math.random() * Math.PI * 2;
  2773. const u = Math.random() * 2 - 1;
  2774. const c = Math.sqrt( 1 - u * u );
  2775. this.x = c * Math.cos( theta );
  2776. this.y = u;
  2777. this.z = c * Math.sin( theta );
  2778. return this;
  2779. }
  2780. *[ Symbol.iterator ]() {
  2781. yield this.x;
  2782. yield this.y;
  2783. yield this.z;
  2784. }
  2785. }
  2786. const _vector$c = /*@__PURE__*/ new Vector3();
  2787. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2788. class Box3 {
  2789. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2790. this.isBox3 = true;
  2791. this.min = min;
  2792. this.max = max;
  2793. }
  2794. set( min, max ) {
  2795. this.min.copy( min );
  2796. this.max.copy( max );
  2797. return this;
  2798. }
  2799. setFromArray( array ) {
  2800. this.makeEmpty();
  2801. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2802. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2803. }
  2804. return this;
  2805. }
  2806. setFromBufferAttribute( attribute ) {
  2807. this.makeEmpty();
  2808. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2809. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2810. }
  2811. return this;
  2812. }
  2813. setFromPoints( points ) {
  2814. this.makeEmpty();
  2815. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2816. this.expandByPoint( points[ i ] );
  2817. }
  2818. return this;
  2819. }
  2820. setFromCenterAndSize( center, size ) {
  2821. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2822. this.min.copy( center ).sub( halfSize );
  2823. this.max.copy( center ).add( halfSize );
  2824. return this;
  2825. }
  2826. setFromObject( object, precise = false ) {
  2827. this.makeEmpty();
  2828. return this.expandByObject( object, precise );
  2829. }
  2830. clone() {
  2831. return new this.constructor().copy( this );
  2832. }
  2833. copy( box ) {
  2834. this.min.copy( box.min );
  2835. this.max.copy( box.max );
  2836. return this;
  2837. }
  2838. makeEmpty() {
  2839. this.min.x = this.min.y = this.min.z = + Infinity;
  2840. this.max.x = this.max.y = this.max.z = - Infinity;
  2841. return this;
  2842. }
  2843. isEmpty() {
  2844. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2845. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2846. }
  2847. getCenter( target ) {
  2848. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2849. }
  2850. getSize( target ) {
  2851. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2852. }
  2853. expandByPoint( point ) {
  2854. this.min.min( point );
  2855. this.max.max( point );
  2856. return this;
  2857. }
  2858. expandByVector( vector ) {
  2859. this.min.sub( vector );
  2860. this.max.add( vector );
  2861. return this;
  2862. }
  2863. expandByScalar( scalar ) {
  2864. this.min.addScalar( - scalar );
  2865. this.max.addScalar( scalar );
  2866. return this;
  2867. }
  2868. expandByObject( object, precise = false ) {
  2869. // Computes the world-axis-aligned bounding box of an object (including its children),
  2870. // accounting for both the object's, and children's, world transforms
  2871. object.updateWorldMatrix( false, false );
  2872. const geometry = object.geometry;
  2873. if ( geometry !== undefined ) {
  2874. const positionAttribute = geometry.getAttribute( 'position' );
  2875. // precise AABB computation based on vertex data requires at least a position attribute.
  2876. // instancing isn't supported so far and uses the normal (conservative) code path.
  2877. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2878. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2879. if ( object.isMesh === true ) {
  2880. object.getVertexPosition( i, _vector$b );
  2881. } else {
  2882. _vector$b.fromBufferAttribute( positionAttribute, i );
  2883. }
  2884. _vector$b.applyMatrix4( object.matrixWorld );
  2885. this.expandByPoint( _vector$b );
  2886. }
  2887. } else {
  2888. if ( object.boundingBox !== undefined ) {
  2889. // object-level bounding box
  2890. if ( object.boundingBox === null ) {
  2891. object.computeBoundingBox();
  2892. }
  2893. _box$4.copy( object.boundingBox );
  2894. } else {
  2895. // geometry-level bounding box
  2896. if ( geometry.boundingBox === null ) {
  2897. geometry.computeBoundingBox();
  2898. }
  2899. _box$4.copy( geometry.boundingBox );
  2900. }
  2901. _box$4.applyMatrix4( object.matrixWorld );
  2902. this.union( _box$4 );
  2903. }
  2904. }
  2905. const children = object.children;
  2906. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2907. this.expandByObject( children[ i ], precise );
  2908. }
  2909. return this;
  2910. }
  2911. containsPoint( point ) {
  2912. return point.x >= this.min.x && point.x <= this.max.x &&
  2913. point.y >= this.min.y && point.y <= this.max.y &&
  2914. point.z >= this.min.z && point.z <= this.max.z;
  2915. }
  2916. containsBox( box ) {
  2917. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2918. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2919. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2920. }
  2921. getParameter( point, target ) {
  2922. // This can potentially have a divide by zero if the box
  2923. // has a size dimension of 0.
  2924. return target.set(
  2925. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2926. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2927. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2928. );
  2929. }
  2930. intersectsBox( box ) {
  2931. // using 6 splitting planes to rule out intersections.
  2932. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2933. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2934. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2935. }
  2936. intersectsSphere( sphere ) {
  2937. // Find the point on the AABB closest to the sphere center.
  2938. this.clampPoint( sphere.center, _vector$b );
  2939. // If that point is inside the sphere, the AABB and sphere intersect.
  2940. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2941. }
  2942. intersectsPlane( plane ) {
  2943. // We compute the minimum and maximum dot product values. If those values
  2944. // are on the same side (back or front) of the plane, then there is no intersection.
  2945. let min, max;
  2946. if ( plane.normal.x > 0 ) {
  2947. min = plane.normal.x * this.min.x;
  2948. max = plane.normal.x * this.max.x;
  2949. } else {
  2950. min = plane.normal.x * this.max.x;
  2951. max = plane.normal.x * this.min.x;
  2952. }
  2953. if ( plane.normal.y > 0 ) {
  2954. min += plane.normal.y * this.min.y;
  2955. max += plane.normal.y * this.max.y;
  2956. } else {
  2957. min += plane.normal.y * this.max.y;
  2958. max += plane.normal.y * this.min.y;
  2959. }
  2960. if ( plane.normal.z > 0 ) {
  2961. min += plane.normal.z * this.min.z;
  2962. max += plane.normal.z * this.max.z;
  2963. } else {
  2964. min += plane.normal.z * this.max.z;
  2965. max += plane.normal.z * this.min.z;
  2966. }
  2967. return ( min <= - plane.constant && max >= - plane.constant );
  2968. }
  2969. intersectsTriangle( triangle ) {
  2970. if ( this.isEmpty() ) {
  2971. return false;
  2972. }
  2973. // compute box center and extents
  2974. this.getCenter( _center );
  2975. _extents.subVectors( this.max, _center );
  2976. // translate triangle to aabb origin
  2977. _v0$2.subVectors( triangle.a, _center );
  2978. _v1$7.subVectors( triangle.b, _center );
  2979. _v2$4.subVectors( triangle.c, _center );
  2980. // compute edge vectors for triangle
  2981. _f0.subVectors( _v1$7, _v0$2 );
  2982. _f1.subVectors( _v2$4, _v1$7 );
  2983. _f2.subVectors( _v0$2, _v2$4 );
  2984. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2985. // 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
  2986. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2987. let axes = [
  2988. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2989. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2990. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2991. ];
  2992. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2993. return false;
  2994. }
  2995. // test 3 face normals from the aabb
  2996. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2997. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2998. return false;
  2999. }
  3000. // finally testing the face normal of the triangle
  3001. // use already existing triangle edge vectors here
  3002. _triangleNormal.crossVectors( _f0, _f1 );
  3003. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3004. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3005. }
  3006. clampPoint( point, target ) {
  3007. return target.copy( point ).clamp( this.min, this.max );
  3008. }
  3009. distanceToPoint( point ) {
  3010. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3011. }
  3012. getBoundingSphere( target ) {
  3013. if ( this.isEmpty() ) {
  3014. target.makeEmpty();
  3015. } else {
  3016. this.getCenter( target.center );
  3017. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3018. }
  3019. return target;
  3020. }
  3021. intersect( box ) {
  3022. this.min.max( box.min );
  3023. this.max.min( box.max );
  3024. // 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.
  3025. if ( this.isEmpty() ) this.makeEmpty();
  3026. return this;
  3027. }
  3028. union( box ) {
  3029. this.min.min( box.min );
  3030. this.max.max( box.max );
  3031. return this;
  3032. }
  3033. applyMatrix4( matrix ) {
  3034. // transform of empty box is an empty box.
  3035. if ( this.isEmpty() ) return this;
  3036. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3037. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3038. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3039. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3040. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3041. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3042. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3043. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3044. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3045. this.setFromPoints( _points );
  3046. return this;
  3047. }
  3048. translate( offset ) {
  3049. this.min.add( offset );
  3050. this.max.add( offset );
  3051. return this;
  3052. }
  3053. equals( box ) {
  3054. return box.min.equals( this.min ) && box.max.equals( this.max );
  3055. }
  3056. }
  3057. const _points = [
  3058. /*@__PURE__*/ new Vector3(),
  3059. /*@__PURE__*/ new Vector3(),
  3060. /*@__PURE__*/ new Vector3(),
  3061. /*@__PURE__*/ new Vector3(),
  3062. /*@__PURE__*/ new Vector3(),
  3063. /*@__PURE__*/ new Vector3(),
  3064. /*@__PURE__*/ new Vector3(),
  3065. /*@__PURE__*/ new Vector3()
  3066. ];
  3067. const _vector$b = /*@__PURE__*/ new Vector3();
  3068. const _box$4 = /*@__PURE__*/ new Box3();
  3069. // triangle centered vertices
  3070. const _v0$2 = /*@__PURE__*/ new Vector3();
  3071. const _v1$7 = /*@__PURE__*/ new Vector3();
  3072. const _v2$4 = /*@__PURE__*/ new Vector3();
  3073. // triangle edge vectors
  3074. const _f0 = /*@__PURE__*/ new Vector3();
  3075. const _f1 = /*@__PURE__*/ new Vector3();
  3076. const _f2 = /*@__PURE__*/ new Vector3();
  3077. const _center = /*@__PURE__*/ new Vector3();
  3078. const _extents = /*@__PURE__*/ new Vector3();
  3079. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3080. const _testAxis = /*@__PURE__*/ new Vector3();
  3081. function satForAxes( axes, v0, v1, v2, extents ) {
  3082. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3083. _testAxis.fromArray( axes, i );
  3084. // project the aabb onto the separating axis
  3085. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3086. // project all 3 vertices of the triangle onto the separating axis
  3087. const p0 = v0.dot( _testAxis );
  3088. const p1 = v1.dot( _testAxis );
  3089. const p2 = v2.dot( _testAxis );
  3090. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3091. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3092. // points of the projected triangle are outside the projected half-length of the aabb
  3093. // the axis is separating and we can exit
  3094. return false;
  3095. }
  3096. }
  3097. return true;
  3098. }
  3099. const _box$3 = /*@__PURE__*/ new Box3();
  3100. const _v1$6 = /*@__PURE__*/ new Vector3();
  3101. const _v2$3 = /*@__PURE__*/ new Vector3();
  3102. class Sphere {
  3103. constructor( center = new Vector3(), radius = - 1 ) {
  3104. this.isSphere = true;
  3105. this.center = center;
  3106. this.radius = radius;
  3107. }
  3108. set( center, radius ) {
  3109. this.center.copy( center );
  3110. this.radius = radius;
  3111. return this;
  3112. }
  3113. setFromPoints( points, optionalCenter ) {
  3114. const center = this.center;
  3115. if ( optionalCenter !== undefined ) {
  3116. center.copy( optionalCenter );
  3117. } else {
  3118. _box$3.setFromPoints( points ).getCenter( center );
  3119. }
  3120. let maxRadiusSq = 0;
  3121. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3122. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3123. }
  3124. this.radius = Math.sqrt( maxRadiusSq );
  3125. return this;
  3126. }
  3127. copy( sphere ) {
  3128. this.center.copy( sphere.center );
  3129. this.radius = sphere.radius;
  3130. return this;
  3131. }
  3132. isEmpty() {
  3133. return ( this.radius < 0 );
  3134. }
  3135. makeEmpty() {
  3136. this.center.set( 0, 0, 0 );
  3137. this.radius = - 1;
  3138. return this;
  3139. }
  3140. containsPoint( point ) {
  3141. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3142. }
  3143. distanceToPoint( point ) {
  3144. return ( point.distanceTo( this.center ) - this.radius );
  3145. }
  3146. intersectsSphere( sphere ) {
  3147. const radiusSum = this.radius + sphere.radius;
  3148. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3149. }
  3150. intersectsBox( box ) {
  3151. return box.intersectsSphere( this );
  3152. }
  3153. intersectsPlane( plane ) {
  3154. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3155. }
  3156. clampPoint( point, target ) {
  3157. const deltaLengthSq = this.center.distanceToSquared( point );
  3158. target.copy( point );
  3159. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3160. target.sub( this.center ).normalize();
  3161. target.multiplyScalar( this.radius ).add( this.center );
  3162. }
  3163. return target;
  3164. }
  3165. getBoundingBox( target ) {
  3166. if ( this.isEmpty() ) {
  3167. // Empty sphere produces empty bounding box
  3168. target.makeEmpty();
  3169. return target;
  3170. }
  3171. target.set( this.center, this.center );
  3172. target.expandByScalar( this.radius );
  3173. return target;
  3174. }
  3175. applyMatrix4( matrix ) {
  3176. this.center.applyMatrix4( matrix );
  3177. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3178. return this;
  3179. }
  3180. translate( offset ) {
  3181. this.center.add( offset );
  3182. return this;
  3183. }
  3184. expandByPoint( point ) {
  3185. if ( this.isEmpty() ) {
  3186. this.center.copy( point );
  3187. this.radius = 0;
  3188. return this;
  3189. }
  3190. _v1$6.subVectors( point, this.center );
  3191. const lengthSq = _v1$6.lengthSq();
  3192. if ( lengthSq > ( this.radius * this.radius ) ) {
  3193. // calculate the minimal sphere
  3194. const length = Math.sqrt( lengthSq );
  3195. const delta = ( length - this.radius ) * 0.5;
  3196. this.center.addScaledVector( _v1$6, delta / length );
  3197. this.radius += delta;
  3198. }
  3199. return this;
  3200. }
  3201. union( sphere ) {
  3202. if ( sphere.isEmpty() ) {
  3203. return this;
  3204. }
  3205. if ( this.isEmpty() ) {
  3206. this.copy( sphere );
  3207. return this;
  3208. }
  3209. if ( this.center.equals( sphere.center ) === true ) {
  3210. this.radius = Math.max( this.radius, sphere.radius );
  3211. } else {
  3212. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3213. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3214. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3215. }
  3216. return this;
  3217. }
  3218. equals( sphere ) {
  3219. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3220. }
  3221. clone() {
  3222. return new this.constructor().copy( this );
  3223. }
  3224. }
  3225. const _vector$a = /*@__PURE__*/ new Vector3();
  3226. const _segCenter = /*@__PURE__*/ new Vector3();
  3227. const _segDir = /*@__PURE__*/ new Vector3();
  3228. const _diff = /*@__PURE__*/ new Vector3();
  3229. const _edge1 = /*@__PURE__*/ new Vector3();
  3230. const _edge2 = /*@__PURE__*/ new Vector3();
  3231. const _normal$2 = /*@__PURE__*/ new Vector3();
  3232. class Ray {
  3233. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3234. this.origin = origin;
  3235. this.direction = direction;
  3236. }
  3237. set( origin, direction ) {
  3238. this.origin.copy( origin );
  3239. this.direction.copy( direction );
  3240. return this;
  3241. }
  3242. copy( ray ) {
  3243. this.origin.copy( ray.origin );
  3244. this.direction.copy( ray.direction );
  3245. return this;
  3246. }
  3247. at( t, target ) {
  3248. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3249. }
  3250. lookAt( v ) {
  3251. this.direction.copy( v ).sub( this.origin ).normalize();
  3252. return this;
  3253. }
  3254. recast( t ) {
  3255. this.origin.copy( this.at( t, _vector$a ) );
  3256. return this;
  3257. }
  3258. closestPointToPoint( point, target ) {
  3259. target.subVectors( point, this.origin );
  3260. const directionDistance = target.dot( this.direction );
  3261. if ( directionDistance < 0 ) {
  3262. return target.copy( this.origin );
  3263. }
  3264. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3265. }
  3266. distanceToPoint( point ) {
  3267. return Math.sqrt( this.distanceSqToPoint( point ) );
  3268. }
  3269. distanceSqToPoint( point ) {
  3270. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3271. // point behind the ray
  3272. if ( directionDistance < 0 ) {
  3273. return this.origin.distanceToSquared( point );
  3274. }
  3275. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3276. return _vector$a.distanceToSquared( point );
  3277. }
  3278. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3279. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3280. // It returns the min distance between the ray and the segment
  3281. // defined by v0 and v1
  3282. // It can also set two optional targets :
  3283. // - The closest point on the ray
  3284. // - The closest point on the segment
  3285. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3286. _segDir.copy( v1 ).sub( v0 ).normalize();
  3287. _diff.copy( this.origin ).sub( _segCenter );
  3288. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3289. const a01 = - this.direction.dot( _segDir );
  3290. const b0 = _diff.dot( this.direction );
  3291. const b1 = - _diff.dot( _segDir );
  3292. const c = _diff.lengthSq();
  3293. const det = Math.abs( 1 - a01 * a01 );
  3294. let s0, s1, sqrDist, extDet;
  3295. if ( det > 0 ) {
  3296. // The ray and segment are not parallel.
  3297. s0 = a01 * b1 - b0;
  3298. s1 = a01 * b0 - b1;
  3299. extDet = segExtent * det;
  3300. if ( s0 >= 0 ) {
  3301. if ( s1 >= - extDet ) {
  3302. if ( s1 <= extDet ) {
  3303. // region 0
  3304. // Minimum at interior points of ray and segment.
  3305. const invDet = 1 / det;
  3306. s0 *= invDet;
  3307. s1 *= invDet;
  3308. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3309. } else {
  3310. // region 1
  3311. s1 = segExtent;
  3312. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3313. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3314. }
  3315. } else {
  3316. // region 5
  3317. s1 = - segExtent;
  3318. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3319. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3320. }
  3321. } else {
  3322. if ( s1 <= - extDet ) {
  3323. // region 4
  3324. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3325. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3326. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3327. } else if ( s1 <= extDet ) {
  3328. // region 3
  3329. s0 = 0;
  3330. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3331. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3332. } else {
  3333. // region 2
  3334. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3335. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3337. }
  3338. }
  3339. } else {
  3340. // Ray and segment are parallel.
  3341. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3342. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3343. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3344. }
  3345. if ( optionalPointOnRay ) {
  3346. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3347. }
  3348. if ( optionalPointOnSegment ) {
  3349. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3350. }
  3351. return sqrDist;
  3352. }
  3353. intersectSphere( sphere, target ) {
  3354. _vector$a.subVectors( sphere.center, this.origin );
  3355. const tca = _vector$a.dot( this.direction );
  3356. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3357. const radius2 = sphere.radius * sphere.radius;
  3358. if ( d2 > radius2 ) return null;
  3359. const thc = Math.sqrt( radius2 - d2 );
  3360. // t0 = first intersect point - entrance on front of sphere
  3361. const t0 = tca - thc;
  3362. // t1 = second intersect point - exit point on back of sphere
  3363. const t1 = tca + thc;
  3364. // test to see if t1 is behind the ray - if so, return null
  3365. if ( t1 < 0 ) return null;
  3366. // test to see if t0 is behind the ray:
  3367. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3368. // in order to always return an intersect point that is in front of the ray.
  3369. if ( t0 < 0 ) return this.at( t1, target );
  3370. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3371. return this.at( t0, target );
  3372. }
  3373. intersectsSphere( sphere ) {
  3374. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3375. }
  3376. distanceToPlane( plane ) {
  3377. const denominator = plane.normal.dot( this.direction );
  3378. if ( denominator === 0 ) {
  3379. // line is coplanar, return origin
  3380. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3381. return 0;
  3382. }
  3383. // Null is preferable to undefined since undefined means.... it is undefined
  3384. return null;
  3385. }
  3386. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3387. // Return if the ray never intersects the plane
  3388. return t >= 0 ? t : null;
  3389. }
  3390. intersectPlane( plane, target ) {
  3391. const t = this.distanceToPlane( plane );
  3392. if ( t === null ) {
  3393. return null;
  3394. }
  3395. return this.at( t, target );
  3396. }
  3397. intersectsPlane( plane ) {
  3398. // check if the ray lies on the plane first
  3399. const distToPoint = plane.distanceToPoint( this.origin );
  3400. if ( distToPoint === 0 ) {
  3401. return true;
  3402. }
  3403. const denominator = plane.normal.dot( this.direction );
  3404. if ( denominator * distToPoint < 0 ) {
  3405. return true;
  3406. }
  3407. // ray origin is behind the plane (and is pointing behind it)
  3408. return false;
  3409. }
  3410. intersectBox( box, target ) {
  3411. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3412. const invdirx = 1 / this.direction.x,
  3413. invdiry = 1 / this.direction.y,
  3414. invdirz = 1 / this.direction.z;
  3415. const origin = this.origin;
  3416. if ( invdirx >= 0 ) {
  3417. tmin = ( box.min.x - origin.x ) * invdirx;
  3418. tmax = ( box.max.x - origin.x ) * invdirx;
  3419. } else {
  3420. tmin = ( box.max.x - origin.x ) * invdirx;
  3421. tmax = ( box.min.x - origin.x ) * invdirx;
  3422. }
  3423. if ( invdiry >= 0 ) {
  3424. tymin = ( box.min.y - origin.y ) * invdiry;
  3425. tymax = ( box.max.y - origin.y ) * invdiry;
  3426. } else {
  3427. tymin = ( box.max.y - origin.y ) * invdiry;
  3428. tymax = ( box.min.y - origin.y ) * invdiry;
  3429. }
  3430. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3431. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3432. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3433. if ( invdirz >= 0 ) {
  3434. tzmin = ( box.min.z - origin.z ) * invdirz;
  3435. tzmax = ( box.max.z - origin.z ) * invdirz;
  3436. } else {
  3437. tzmin = ( box.max.z - origin.z ) * invdirz;
  3438. tzmax = ( box.min.z - origin.z ) * invdirz;
  3439. }
  3440. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3441. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3442. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3443. //return point closest to the ray (positive side)
  3444. if ( tmax < 0 ) return null;
  3445. return this.at( tmin >= 0 ? tmin : tmax, target );
  3446. }
  3447. intersectsBox( box ) {
  3448. return this.intersectBox( box, _vector$a ) !== null;
  3449. }
  3450. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3451. // Compute the offset origin, edges, and normal.
  3452. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3453. _edge1.subVectors( b, a );
  3454. _edge2.subVectors( c, a );
  3455. _normal$2.crossVectors( _edge1, _edge2 );
  3456. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3457. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3458. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3459. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3460. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3461. let DdN = this.direction.dot( _normal$2 );
  3462. let sign;
  3463. if ( DdN > 0 ) {
  3464. if ( backfaceCulling ) return null;
  3465. sign = 1;
  3466. } else if ( DdN < 0 ) {
  3467. sign = - 1;
  3468. DdN = - DdN;
  3469. } else {
  3470. return null;
  3471. }
  3472. _diff.subVectors( this.origin, a );
  3473. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3474. // b1 < 0, no intersection
  3475. if ( DdQxE2 < 0 ) {
  3476. return null;
  3477. }
  3478. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3479. // b2 < 0, no intersection
  3480. if ( DdE1xQ < 0 ) {
  3481. return null;
  3482. }
  3483. // b1+b2 > 1, no intersection
  3484. if ( DdQxE2 + DdE1xQ > DdN ) {
  3485. return null;
  3486. }
  3487. // Line intersects triangle, check if ray does.
  3488. const QdN = - sign * _diff.dot( _normal$2 );
  3489. // t < 0, no intersection
  3490. if ( QdN < 0 ) {
  3491. return null;
  3492. }
  3493. // Ray intersects triangle.
  3494. return this.at( QdN / DdN, target );
  3495. }
  3496. applyMatrix4( matrix4 ) {
  3497. this.origin.applyMatrix4( matrix4 );
  3498. this.direction.transformDirection( matrix4 );
  3499. return this;
  3500. }
  3501. equals( ray ) {
  3502. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3503. }
  3504. clone() {
  3505. return new this.constructor().copy( this );
  3506. }
  3507. }
  3508. class Matrix4 {
  3509. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3510. Matrix4.prototype.isMatrix4 = true;
  3511. this.elements = [
  3512. 1, 0, 0, 0,
  3513. 0, 1, 0, 0,
  3514. 0, 0, 1, 0,
  3515. 0, 0, 0, 1
  3516. ];
  3517. if ( n11 !== undefined ) {
  3518. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3519. }
  3520. }
  3521. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3522. const te = this.elements;
  3523. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3524. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3525. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3526. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3527. return this;
  3528. }
  3529. identity() {
  3530. this.set(
  3531. 1, 0, 0, 0,
  3532. 0, 1, 0, 0,
  3533. 0, 0, 1, 0,
  3534. 0, 0, 0, 1
  3535. );
  3536. return this;
  3537. }
  3538. clone() {
  3539. return new Matrix4().fromArray( this.elements );
  3540. }
  3541. copy( m ) {
  3542. const te = this.elements;
  3543. const me = m.elements;
  3544. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3545. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3546. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3547. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3548. return this;
  3549. }
  3550. copyPosition( m ) {
  3551. const te = this.elements, me = m.elements;
  3552. te[ 12 ] = me[ 12 ];
  3553. te[ 13 ] = me[ 13 ];
  3554. te[ 14 ] = me[ 14 ];
  3555. return this;
  3556. }
  3557. setFromMatrix3( m ) {
  3558. const me = m.elements;
  3559. this.set(
  3560. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3561. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3562. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3563. 0, 0, 0, 1
  3564. );
  3565. return this;
  3566. }
  3567. extractBasis( xAxis, yAxis, zAxis ) {
  3568. xAxis.setFromMatrixColumn( this, 0 );
  3569. yAxis.setFromMatrixColumn( this, 1 );
  3570. zAxis.setFromMatrixColumn( this, 2 );
  3571. return this;
  3572. }
  3573. makeBasis( xAxis, yAxis, zAxis ) {
  3574. this.set(
  3575. xAxis.x, yAxis.x, zAxis.x, 0,
  3576. xAxis.y, yAxis.y, zAxis.y, 0,
  3577. xAxis.z, yAxis.z, zAxis.z, 0,
  3578. 0, 0, 0, 1
  3579. );
  3580. return this;
  3581. }
  3582. extractRotation( m ) {
  3583. // this method does not support reflection matrices
  3584. const te = this.elements;
  3585. const me = m.elements;
  3586. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3587. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3588. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3589. te[ 0 ] = me[ 0 ] * scaleX;
  3590. te[ 1 ] = me[ 1 ] * scaleX;
  3591. te[ 2 ] = me[ 2 ] * scaleX;
  3592. te[ 3 ] = 0;
  3593. te[ 4 ] = me[ 4 ] * scaleY;
  3594. te[ 5 ] = me[ 5 ] * scaleY;
  3595. te[ 6 ] = me[ 6 ] * scaleY;
  3596. te[ 7 ] = 0;
  3597. te[ 8 ] = me[ 8 ] * scaleZ;
  3598. te[ 9 ] = me[ 9 ] * scaleZ;
  3599. te[ 10 ] = me[ 10 ] * scaleZ;
  3600. te[ 11 ] = 0;
  3601. te[ 12 ] = 0;
  3602. te[ 13 ] = 0;
  3603. te[ 14 ] = 0;
  3604. te[ 15 ] = 1;
  3605. return this;
  3606. }
  3607. makeRotationFromEuler( euler ) {
  3608. const te = this.elements;
  3609. const x = euler.x, y = euler.y, z = euler.z;
  3610. const a = Math.cos( x ), b = Math.sin( x );
  3611. const c = Math.cos( y ), d = Math.sin( y );
  3612. const e = Math.cos( z ), f = Math.sin( z );
  3613. if ( euler.order === 'XYZ' ) {
  3614. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3615. te[ 0 ] = c * e;
  3616. te[ 4 ] = - c * f;
  3617. te[ 8 ] = d;
  3618. te[ 1 ] = af + be * d;
  3619. te[ 5 ] = ae - bf * d;
  3620. te[ 9 ] = - b * c;
  3621. te[ 2 ] = bf - ae * d;
  3622. te[ 6 ] = be + af * d;
  3623. te[ 10 ] = a * c;
  3624. } else if ( euler.order === 'YXZ' ) {
  3625. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3626. te[ 0 ] = ce + df * b;
  3627. te[ 4 ] = de * b - cf;
  3628. te[ 8 ] = a * d;
  3629. te[ 1 ] = a * f;
  3630. te[ 5 ] = a * e;
  3631. te[ 9 ] = - b;
  3632. te[ 2 ] = cf * b - de;
  3633. te[ 6 ] = df + ce * b;
  3634. te[ 10 ] = a * c;
  3635. } else if ( euler.order === 'ZXY' ) {
  3636. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3637. te[ 0 ] = ce - df * b;
  3638. te[ 4 ] = - a * f;
  3639. te[ 8 ] = de + cf * b;
  3640. te[ 1 ] = cf + de * b;
  3641. te[ 5 ] = a * e;
  3642. te[ 9 ] = df - ce * b;
  3643. te[ 2 ] = - a * d;
  3644. te[ 6 ] = b;
  3645. te[ 10 ] = a * c;
  3646. } else if ( euler.order === 'ZYX' ) {
  3647. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3648. te[ 0 ] = c * e;
  3649. te[ 4 ] = be * d - af;
  3650. te[ 8 ] = ae * d + bf;
  3651. te[ 1 ] = c * f;
  3652. te[ 5 ] = bf * d + ae;
  3653. te[ 9 ] = af * d - be;
  3654. te[ 2 ] = - d;
  3655. te[ 6 ] = b * c;
  3656. te[ 10 ] = a * c;
  3657. } else if ( euler.order === 'YZX' ) {
  3658. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3659. te[ 0 ] = c * e;
  3660. te[ 4 ] = bd - ac * f;
  3661. te[ 8 ] = bc * f + ad;
  3662. te[ 1 ] = f;
  3663. te[ 5 ] = a * e;
  3664. te[ 9 ] = - b * e;
  3665. te[ 2 ] = - d * e;
  3666. te[ 6 ] = ad * f + bc;
  3667. te[ 10 ] = ac - bd * f;
  3668. } else if ( euler.order === 'XZY' ) {
  3669. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3670. te[ 0 ] = c * e;
  3671. te[ 4 ] = - f;
  3672. te[ 8 ] = d * e;
  3673. te[ 1 ] = ac * f + bd;
  3674. te[ 5 ] = a * e;
  3675. te[ 9 ] = ad * f - bc;
  3676. te[ 2 ] = bc * f - ad;
  3677. te[ 6 ] = b * e;
  3678. te[ 10 ] = bd * f + ac;
  3679. }
  3680. // bottom row
  3681. te[ 3 ] = 0;
  3682. te[ 7 ] = 0;
  3683. te[ 11 ] = 0;
  3684. // last column
  3685. te[ 12 ] = 0;
  3686. te[ 13 ] = 0;
  3687. te[ 14 ] = 0;
  3688. te[ 15 ] = 1;
  3689. return this;
  3690. }
  3691. makeRotationFromQuaternion( q ) {
  3692. return this.compose( _zero, q, _one );
  3693. }
  3694. lookAt( eye, target, up ) {
  3695. const te = this.elements;
  3696. _z.subVectors( eye, target );
  3697. if ( _z.lengthSq() === 0 ) {
  3698. // eye and target are in the same position
  3699. _z.z = 1;
  3700. }
  3701. _z.normalize();
  3702. _x.crossVectors( up, _z );
  3703. if ( _x.lengthSq() === 0 ) {
  3704. // up and z are parallel
  3705. if ( Math.abs( up.z ) === 1 ) {
  3706. _z.x += 0.0001;
  3707. } else {
  3708. _z.z += 0.0001;
  3709. }
  3710. _z.normalize();
  3711. _x.crossVectors( up, _z );
  3712. }
  3713. _x.normalize();
  3714. _y.crossVectors( _z, _x );
  3715. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3716. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3717. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3718. return this;
  3719. }
  3720. multiply( m ) {
  3721. return this.multiplyMatrices( this, m );
  3722. }
  3723. premultiply( m ) {
  3724. return this.multiplyMatrices( m, this );
  3725. }
  3726. multiplyMatrices( a, b ) {
  3727. const ae = a.elements;
  3728. const be = b.elements;
  3729. const te = this.elements;
  3730. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3731. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3732. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3733. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3734. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3735. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3736. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3737. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3738. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3739. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3740. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3741. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3742. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3743. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3744. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3745. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3746. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3747. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3748. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3749. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3750. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3751. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3752. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3753. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3754. return this;
  3755. }
  3756. multiplyScalar( s ) {
  3757. const te = this.elements;
  3758. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3759. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3760. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3761. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3762. return this;
  3763. }
  3764. determinant() {
  3765. const te = this.elements;
  3766. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3767. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3768. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3769. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3770. //TODO: make this more efficient
  3771. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3772. return (
  3773. n41 * (
  3774. + n14 * n23 * n32
  3775. - n13 * n24 * n32
  3776. - n14 * n22 * n33
  3777. + n12 * n24 * n33
  3778. + n13 * n22 * n34
  3779. - n12 * n23 * n34
  3780. ) +
  3781. n42 * (
  3782. + n11 * n23 * n34
  3783. - n11 * n24 * n33
  3784. + n14 * n21 * n33
  3785. - n13 * n21 * n34
  3786. + n13 * n24 * n31
  3787. - n14 * n23 * n31
  3788. ) +
  3789. n43 * (
  3790. + n11 * n24 * n32
  3791. - n11 * n22 * n34
  3792. - n14 * n21 * n32
  3793. + n12 * n21 * n34
  3794. + n14 * n22 * n31
  3795. - n12 * n24 * n31
  3796. ) +
  3797. n44 * (
  3798. - n13 * n22 * n31
  3799. - n11 * n23 * n32
  3800. + n11 * n22 * n33
  3801. + n13 * n21 * n32
  3802. - n12 * n21 * n33
  3803. + n12 * n23 * n31
  3804. )
  3805. );
  3806. }
  3807. transpose() {
  3808. const te = this.elements;
  3809. let tmp;
  3810. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3811. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3812. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3813. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3814. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3815. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3816. return this;
  3817. }
  3818. setPosition( x, y, z ) {
  3819. const te = this.elements;
  3820. if ( x.isVector3 ) {
  3821. te[ 12 ] = x.x;
  3822. te[ 13 ] = x.y;
  3823. te[ 14 ] = x.z;
  3824. } else {
  3825. te[ 12 ] = x;
  3826. te[ 13 ] = y;
  3827. te[ 14 ] = z;
  3828. }
  3829. return this;
  3830. }
  3831. invert() {
  3832. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3833. const te = this.elements,
  3834. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3835. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3836. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3837. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3838. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3839. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3840. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3841. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3842. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3843. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3844. const detInv = 1 / det;
  3845. te[ 0 ] = t11 * detInv;
  3846. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3847. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3848. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3849. te[ 4 ] = t12 * detInv;
  3850. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3851. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3852. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3853. te[ 8 ] = t13 * detInv;
  3854. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3855. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3856. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3857. te[ 12 ] = t14 * detInv;
  3858. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3859. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3860. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3861. return this;
  3862. }
  3863. scale( v ) {
  3864. const te = this.elements;
  3865. const x = v.x, y = v.y, z = v.z;
  3866. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3867. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3868. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3869. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3870. return this;
  3871. }
  3872. getMaxScaleOnAxis() {
  3873. const te = this.elements;
  3874. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3875. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3876. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3877. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3878. }
  3879. makeTranslation( x, y, z ) {
  3880. if ( x.isVector3 ) {
  3881. this.set(
  3882. 1, 0, 0, x.x,
  3883. 0, 1, 0, x.y,
  3884. 0, 0, 1, x.z,
  3885. 0, 0, 0, 1
  3886. );
  3887. } else {
  3888. this.set(
  3889. 1, 0, 0, x,
  3890. 0, 1, 0, y,
  3891. 0, 0, 1, z,
  3892. 0, 0, 0, 1
  3893. );
  3894. }
  3895. return this;
  3896. }
  3897. makeRotationX( theta ) {
  3898. const c = Math.cos( theta ), s = Math.sin( theta );
  3899. this.set(
  3900. 1, 0, 0, 0,
  3901. 0, c, - s, 0,
  3902. 0, s, c, 0,
  3903. 0, 0, 0, 1
  3904. );
  3905. return this;
  3906. }
  3907. makeRotationY( theta ) {
  3908. const c = Math.cos( theta ), s = Math.sin( theta );
  3909. this.set(
  3910. c, 0, s, 0,
  3911. 0, 1, 0, 0,
  3912. - s, 0, c, 0,
  3913. 0, 0, 0, 1
  3914. );
  3915. return this;
  3916. }
  3917. makeRotationZ( theta ) {
  3918. const c = Math.cos( theta ), s = Math.sin( theta );
  3919. this.set(
  3920. c, - s, 0, 0,
  3921. s, c, 0, 0,
  3922. 0, 0, 1, 0,
  3923. 0, 0, 0, 1
  3924. );
  3925. return this;
  3926. }
  3927. makeRotationAxis( axis, angle ) {
  3928. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3929. const c = Math.cos( angle );
  3930. const s = Math.sin( angle );
  3931. const t = 1 - c;
  3932. const x = axis.x, y = axis.y, z = axis.z;
  3933. const tx = t * x, ty = t * y;
  3934. this.set(
  3935. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3936. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3937. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3938. 0, 0, 0, 1
  3939. );
  3940. return this;
  3941. }
  3942. makeScale( x, y, z ) {
  3943. this.set(
  3944. x, 0, 0, 0,
  3945. 0, y, 0, 0,
  3946. 0, 0, z, 0,
  3947. 0, 0, 0, 1
  3948. );
  3949. return this;
  3950. }
  3951. makeShear( xy, xz, yx, yz, zx, zy ) {
  3952. this.set(
  3953. 1, yx, zx, 0,
  3954. xy, 1, zy, 0,
  3955. xz, yz, 1, 0,
  3956. 0, 0, 0, 1
  3957. );
  3958. return this;
  3959. }
  3960. compose( position, quaternion, scale ) {
  3961. const te = this.elements;
  3962. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3963. const x2 = x + x, y2 = y + y, z2 = z + z;
  3964. const xx = x * x2, xy = x * y2, xz = x * z2;
  3965. const yy = y * y2, yz = y * z2, zz = z * z2;
  3966. const wx = w * x2, wy = w * y2, wz = w * z2;
  3967. const sx = scale.x, sy = scale.y, sz = scale.z;
  3968. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3969. te[ 1 ] = ( xy + wz ) * sx;
  3970. te[ 2 ] = ( xz - wy ) * sx;
  3971. te[ 3 ] = 0;
  3972. te[ 4 ] = ( xy - wz ) * sy;
  3973. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3974. te[ 6 ] = ( yz + wx ) * sy;
  3975. te[ 7 ] = 0;
  3976. te[ 8 ] = ( xz + wy ) * sz;
  3977. te[ 9 ] = ( yz - wx ) * sz;
  3978. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3979. te[ 11 ] = 0;
  3980. te[ 12 ] = position.x;
  3981. te[ 13 ] = position.y;
  3982. te[ 14 ] = position.z;
  3983. te[ 15 ] = 1;
  3984. return this;
  3985. }
  3986. decompose( position, quaternion, scale ) {
  3987. const te = this.elements;
  3988. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3989. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3990. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3991. // if determine is negative, we need to invert one scale
  3992. const det = this.determinant();
  3993. if ( det < 0 ) sx = - sx;
  3994. position.x = te[ 12 ];
  3995. position.y = te[ 13 ];
  3996. position.z = te[ 14 ];
  3997. // scale the rotation part
  3998. _m1$2.copy( this );
  3999. const invSX = 1 / sx;
  4000. const invSY = 1 / sy;
  4001. const invSZ = 1 / sz;
  4002. _m1$2.elements[ 0 ] *= invSX;
  4003. _m1$2.elements[ 1 ] *= invSX;
  4004. _m1$2.elements[ 2 ] *= invSX;
  4005. _m1$2.elements[ 4 ] *= invSY;
  4006. _m1$2.elements[ 5 ] *= invSY;
  4007. _m1$2.elements[ 6 ] *= invSY;
  4008. _m1$2.elements[ 8 ] *= invSZ;
  4009. _m1$2.elements[ 9 ] *= invSZ;
  4010. _m1$2.elements[ 10 ] *= invSZ;
  4011. quaternion.setFromRotationMatrix( _m1$2 );
  4012. scale.x = sx;
  4013. scale.y = sy;
  4014. scale.z = sz;
  4015. return this;
  4016. }
  4017. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4018. const te = this.elements;
  4019. const x = 2 * near / ( right - left );
  4020. const y = 2 * near / ( top - bottom );
  4021. const a = ( right + left ) / ( right - left );
  4022. const b = ( top + bottom ) / ( top - bottom );
  4023. let c, d;
  4024. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4025. c = - ( far + near ) / ( far - near );
  4026. d = ( - 2 * far * near ) / ( far - near );
  4027. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4028. c = - far / ( far - near );
  4029. d = ( - far * near ) / ( far - near );
  4030. } else {
  4031. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4032. }
  4033. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4034. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4035. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4036. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4037. return this;
  4038. }
  4039. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4040. const te = this.elements;
  4041. const w = 1.0 / ( right - left );
  4042. const h = 1.0 / ( top - bottom );
  4043. const p = 1.0 / ( far - near );
  4044. const x = ( right + left ) * w;
  4045. const y = ( top + bottom ) * h;
  4046. let z, zInv;
  4047. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4048. z = ( far + near ) * p;
  4049. zInv = - 2 * p;
  4050. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4051. z = near * p;
  4052. zInv = - 1 * p;
  4053. } else {
  4054. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4055. }
  4056. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4057. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4058. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4059. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4060. return this;
  4061. }
  4062. equals( matrix ) {
  4063. const te = this.elements;
  4064. const me = matrix.elements;
  4065. for ( let i = 0; i < 16; i ++ ) {
  4066. if ( te[ i ] !== me[ i ] ) return false;
  4067. }
  4068. return true;
  4069. }
  4070. fromArray( array, offset = 0 ) {
  4071. for ( let i = 0; i < 16; i ++ ) {
  4072. this.elements[ i ] = array[ i + offset ];
  4073. }
  4074. return this;
  4075. }
  4076. toArray( array = [], offset = 0 ) {
  4077. const te = this.elements;
  4078. array[ offset ] = te[ 0 ];
  4079. array[ offset + 1 ] = te[ 1 ];
  4080. array[ offset + 2 ] = te[ 2 ];
  4081. array[ offset + 3 ] = te[ 3 ];
  4082. array[ offset + 4 ] = te[ 4 ];
  4083. array[ offset + 5 ] = te[ 5 ];
  4084. array[ offset + 6 ] = te[ 6 ];
  4085. array[ offset + 7 ] = te[ 7 ];
  4086. array[ offset + 8 ] = te[ 8 ];
  4087. array[ offset + 9 ] = te[ 9 ];
  4088. array[ offset + 10 ] = te[ 10 ];
  4089. array[ offset + 11 ] = te[ 11 ];
  4090. array[ offset + 12 ] = te[ 12 ];
  4091. array[ offset + 13 ] = te[ 13 ];
  4092. array[ offset + 14 ] = te[ 14 ];
  4093. array[ offset + 15 ] = te[ 15 ];
  4094. return array;
  4095. }
  4096. }
  4097. const _v1$5 = /*@__PURE__*/ new Vector3();
  4098. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4099. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4100. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4101. const _x = /*@__PURE__*/ new Vector3();
  4102. const _y = /*@__PURE__*/ new Vector3();
  4103. const _z = /*@__PURE__*/ new Vector3();
  4104. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4105. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4106. class Euler {
  4107. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4108. this.isEuler = true;
  4109. this._x = x;
  4110. this._y = y;
  4111. this._z = z;
  4112. this._order = order;
  4113. }
  4114. get x() {
  4115. return this._x;
  4116. }
  4117. set x( value ) {
  4118. this._x = value;
  4119. this._onChangeCallback();
  4120. }
  4121. get y() {
  4122. return this._y;
  4123. }
  4124. set y( value ) {
  4125. this._y = value;
  4126. this._onChangeCallback();
  4127. }
  4128. get z() {
  4129. return this._z;
  4130. }
  4131. set z( value ) {
  4132. this._z = value;
  4133. this._onChangeCallback();
  4134. }
  4135. get order() {
  4136. return this._order;
  4137. }
  4138. set order( value ) {
  4139. this._order = value;
  4140. this._onChangeCallback();
  4141. }
  4142. set( x, y, z, order = this._order ) {
  4143. this._x = x;
  4144. this._y = y;
  4145. this._z = z;
  4146. this._order = order;
  4147. this._onChangeCallback();
  4148. return this;
  4149. }
  4150. clone() {
  4151. return new this.constructor( this._x, this._y, this._z, this._order );
  4152. }
  4153. copy( euler ) {
  4154. this._x = euler._x;
  4155. this._y = euler._y;
  4156. this._z = euler._z;
  4157. this._order = euler._order;
  4158. this._onChangeCallback();
  4159. return this;
  4160. }
  4161. setFromRotationMatrix( m, order = this._order, update = true ) {
  4162. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4163. const te = m.elements;
  4164. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4165. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4166. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4167. switch ( order ) {
  4168. case 'XYZ':
  4169. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4170. if ( Math.abs( m13 ) < 0.9999999 ) {
  4171. this._x = Math.atan2( - m23, m33 );
  4172. this._z = Math.atan2( - m12, m11 );
  4173. } else {
  4174. this._x = Math.atan2( m32, m22 );
  4175. this._z = 0;
  4176. }
  4177. break;
  4178. case 'YXZ':
  4179. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4180. if ( Math.abs( m23 ) < 0.9999999 ) {
  4181. this._y = Math.atan2( m13, m33 );
  4182. this._z = Math.atan2( m21, m22 );
  4183. } else {
  4184. this._y = Math.atan2( - m31, m11 );
  4185. this._z = 0;
  4186. }
  4187. break;
  4188. case 'ZXY':
  4189. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4190. if ( Math.abs( m32 ) < 0.9999999 ) {
  4191. this._y = Math.atan2( - m31, m33 );
  4192. this._z = Math.atan2( - m12, m22 );
  4193. } else {
  4194. this._y = 0;
  4195. this._z = Math.atan2( m21, m11 );
  4196. }
  4197. break;
  4198. case 'ZYX':
  4199. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4200. if ( Math.abs( m31 ) < 0.9999999 ) {
  4201. this._x = Math.atan2( m32, m33 );
  4202. this._z = Math.atan2( m21, m11 );
  4203. } else {
  4204. this._x = 0;
  4205. this._z = Math.atan2( - m12, m22 );
  4206. }
  4207. break;
  4208. case 'YZX':
  4209. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4210. if ( Math.abs( m21 ) < 0.9999999 ) {
  4211. this._x = Math.atan2( - m23, m22 );
  4212. this._y = Math.atan2( - m31, m11 );
  4213. } else {
  4214. this._x = 0;
  4215. this._y = Math.atan2( m13, m33 );
  4216. }
  4217. break;
  4218. case 'XZY':
  4219. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4220. if ( Math.abs( m12 ) < 0.9999999 ) {
  4221. this._x = Math.atan2( m32, m22 );
  4222. this._y = Math.atan2( m13, m11 );
  4223. } else {
  4224. this._x = Math.atan2( - m23, m33 );
  4225. this._y = 0;
  4226. }
  4227. break;
  4228. default:
  4229. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4230. }
  4231. this._order = order;
  4232. if ( update === true ) this._onChangeCallback();
  4233. return this;
  4234. }
  4235. setFromQuaternion( q, order, update ) {
  4236. _matrix$2.makeRotationFromQuaternion( q );
  4237. return this.setFromRotationMatrix( _matrix$2, order, update );
  4238. }
  4239. setFromVector3( v, order = this._order ) {
  4240. return this.set( v.x, v.y, v.z, order );
  4241. }
  4242. reorder( newOrder ) {
  4243. // WARNING: this discards revolution information -bhouston
  4244. _quaternion$3.setFromEuler( this );
  4245. return this.setFromQuaternion( _quaternion$3, newOrder );
  4246. }
  4247. equals( euler ) {
  4248. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4249. }
  4250. fromArray( array ) {
  4251. this._x = array[ 0 ];
  4252. this._y = array[ 1 ];
  4253. this._z = array[ 2 ];
  4254. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4255. this._onChangeCallback();
  4256. return this;
  4257. }
  4258. toArray( array = [], offset = 0 ) {
  4259. array[ offset ] = this._x;
  4260. array[ offset + 1 ] = this._y;
  4261. array[ offset + 2 ] = this._z;
  4262. array[ offset + 3 ] = this._order;
  4263. return array;
  4264. }
  4265. _onChange( callback ) {
  4266. this._onChangeCallback = callback;
  4267. return this;
  4268. }
  4269. _onChangeCallback() {}
  4270. *[ Symbol.iterator ]() {
  4271. yield this._x;
  4272. yield this._y;
  4273. yield this._z;
  4274. yield this._order;
  4275. }
  4276. }
  4277. Euler.DEFAULT_ORDER = 'XYZ';
  4278. class Layers {
  4279. constructor() {
  4280. this.mask = 1 | 0;
  4281. }
  4282. set( channel ) {
  4283. this.mask = ( 1 << channel | 0 ) >>> 0;
  4284. }
  4285. enable( channel ) {
  4286. this.mask |= 1 << channel | 0;
  4287. }
  4288. enableAll() {
  4289. this.mask = 0xffffffff | 0;
  4290. }
  4291. toggle( channel ) {
  4292. this.mask ^= 1 << channel | 0;
  4293. }
  4294. disable( channel ) {
  4295. this.mask &= ~ ( 1 << channel | 0 );
  4296. }
  4297. disableAll() {
  4298. this.mask = 0;
  4299. }
  4300. test( layers ) {
  4301. return ( this.mask & layers.mask ) !== 0;
  4302. }
  4303. isEnabled( channel ) {
  4304. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4305. }
  4306. }
  4307. let _object3DId = 0;
  4308. const _v1$4 = /*@__PURE__*/ new Vector3();
  4309. const _q1 = /*@__PURE__*/ new Quaternion();
  4310. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4311. const _target$1 = /*@__PURE__*/ new Vector3();
  4312. const _position$3 = /*@__PURE__*/ new Vector3();
  4313. const _scale$2 = /*@__PURE__*/ new Vector3();
  4314. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4315. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4316. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4317. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4318. const _addedEvent = { type: 'added' };
  4319. const _removedEvent = { type: 'removed' };
  4320. const _childaddedEvent = { type: 'childadded', child: null };
  4321. const _childremovedEvent = { type: 'childremoved', child: null };
  4322. class Object3D extends EventDispatcher {
  4323. constructor() {
  4324. super();
  4325. this.isObject3D = true;
  4326. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4327. this.uuid = generateUUID();
  4328. this.name = '';
  4329. this.type = 'Object3D';
  4330. this.parent = null;
  4331. this.children = [];
  4332. this.up = Object3D.DEFAULT_UP.clone();
  4333. const position = new Vector3();
  4334. const rotation = new Euler();
  4335. const quaternion = new Quaternion();
  4336. const scale = new Vector3( 1, 1, 1 );
  4337. function onRotationChange() {
  4338. quaternion.setFromEuler( rotation, false );
  4339. }
  4340. function onQuaternionChange() {
  4341. rotation.setFromQuaternion( quaternion, undefined, false );
  4342. }
  4343. rotation._onChange( onRotationChange );
  4344. quaternion._onChange( onQuaternionChange );
  4345. Object.defineProperties( this, {
  4346. position: {
  4347. configurable: true,
  4348. enumerable: true,
  4349. value: position
  4350. },
  4351. rotation: {
  4352. configurable: true,
  4353. enumerable: true,
  4354. value: rotation
  4355. },
  4356. quaternion: {
  4357. configurable: true,
  4358. enumerable: true,
  4359. value: quaternion
  4360. },
  4361. scale: {
  4362. configurable: true,
  4363. enumerable: true,
  4364. value: scale
  4365. },
  4366. modelViewMatrix: {
  4367. value: new Matrix4()
  4368. },
  4369. normalMatrix: {
  4370. value: new Matrix3()
  4371. }
  4372. } );
  4373. this.matrix = new Matrix4();
  4374. this.matrixWorld = new Matrix4();
  4375. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4376. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4377. this.matrixWorldNeedsUpdate = false;
  4378. this.layers = new Layers();
  4379. this.visible = true;
  4380. this.castShadow = false;
  4381. this.receiveShadow = false;
  4382. this.frustumCulled = true;
  4383. this.renderOrder = 0;
  4384. this.animations = [];
  4385. this.userData = {};
  4386. }
  4387. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4388. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4389. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4390. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4391. applyMatrix4( matrix ) {
  4392. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4393. this.matrix.premultiply( matrix );
  4394. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4395. }
  4396. applyQuaternion( q ) {
  4397. this.quaternion.premultiply( q );
  4398. return this;
  4399. }
  4400. setRotationFromAxisAngle( axis, angle ) {
  4401. // assumes axis is normalized
  4402. this.quaternion.setFromAxisAngle( axis, angle );
  4403. }
  4404. setRotationFromEuler( euler ) {
  4405. this.quaternion.setFromEuler( euler, true );
  4406. }
  4407. setRotationFromMatrix( m ) {
  4408. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4409. this.quaternion.setFromRotationMatrix( m );
  4410. }
  4411. setRotationFromQuaternion( q ) {
  4412. // assumes q is normalized
  4413. this.quaternion.copy( q );
  4414. }
  4415. rotateOnAxis( axis, angle ) {
  4416. // rotate object on axis in object space
  4417. // axis is assumed to be normalized
  4418. _q1.setFromAxisAngle( axis, angle );
  4419. this.quaternion.multiply( _q1 );
  4420. return this;
  4421. }
  4422. rotateOnWorldAxis( axis, angle ) {
  4423. // rotate object on axis in world space
  4424. // axis is assumed to be normalized
  4425. // method assumes no rotated parent
  4426. _q1.setFromAxisAngle( axis, angle );
  4427. this.quaternion.premultiply( _q1 );
  4428. return this;
  4429. }
  4430. rotateX( angle ) {
  4431. return this.rotateOnAxis( _xAxis, angle );
  4432. }
  4433. rotateY( angle ) {
  4434. return this.rotateOnAxis( _yAxis, angle );
  4435. }
  4436. rotateZ( angle ) {
  4437. return this.rotateOnAxis( _zAxis, angle );
  4438. }
  4439. translateOnAxis( axis, distance ) {
  4440. // translate object by distance along axis in object space
  4441. // axis is assumed to be normalized
  4442. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4443. this.position.add( _v1$4.multiplyScalar( distance ) );
  4444. return this;
  4445. }
  4446. translateX( distance ) {
  4447. return this.translateOnAxis( _xAxis, distance );
  4448. }
  4449. translateY( distance ) {
  4450. return this.translateOnAxis( _yAxis, distance );
  4451. }
  4452. translateZ( distance ) {
  4453. return this.translateOnAxis( _zAxis, distance );
  4454. }
  4455. localToWorld( vector ) {
  4456. this.updateWorldMatrix( true, false );
  4457. return vector.applyMatrix4( this.matrixWorld );
  4458. }
  4459. worldToLocal( vector ) {
  4460. this.updateWorldMatrix( true, false );
  4461. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4462. }
  4463. lookAt( x, y, z ) {
  4464. // This method does not support objects having non-uniformly-scaled parent(s)
  4465. if ( x.isVector3 ) {
  4466. _target$1.copy( x );
  4467. } else {
  4468. _target$1.set( x, y, z );
  4469. }
  4470. const parent = this.parent;
  4471. this.updateWorldMatrix( true, false );
  4472. _position$3.setFromMatrixPosition( this.matrixWorld );
  4473. if ( this.isCamera || this.isLight ) {
  4474. _m1$1.lookAt( _position$3, _target$1, this.up );
  4475. } else {
  4476. _m1$1.lookAt( _target$1, _position$3, this.up );
  4477. }
  4478. this.quaternion.setFromRotationMatrix( _m1$1 );
  4479. if ( parent ) {
  4480. _m1$1.extractRotation( parent.matrixWorld );
  4481. _q1.setFromRotationMatrix( _m1$1 );
  4482. this.quaternion.premultiply( _q1.invert() );
  4483. }
  4484. }
  4485. add( object ) {
  4486. if ( arguments.length > 1 ) {
  4487. for ( let i = 0; i < arguments.length; i ++ ) {
  4488. this.add( arguments[ i ] );
  4489. }
  4490. return this;
  4491. }
  4492. if ( object === this ) {
  4493. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4494. return this;
  4495. }
  4496. if ( object && object.isObject3D ) {
  4497. object.removeFromParent();
  4498. object.parent = this;
  4499. this.children.push( object );
  4500. object.dispatchEvent( _addedEvent );
  4501. _childaddedEvent.child = object;
  4502. this.dispatchEvent( _childaddedEvent );
  4503. _childaddedEvent.child = null;
  4504. } else {
  4505. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4506. }
  4507. return this;
  4508. }
  4509. remove( object ) {
  4510. if ( arguments.length > 1 ) {
  4511. for ( let i = 0; i < arguments.length; i ++ ) {
  4512. this.remove( arguments[ i ] );
  4513. }
  4514. return this;
  4515. }
  4516. const index = this.children.indexOf( object );
  4517. if ( index !== - 1 ) {
  4518. object.parent = null;
  4519. this.children.splice( index, 1 );
  4520. object.dispatchEvent( _removedEvent );
  4521. _childremovedEvent.child = object;
  4522. this.dispatchEvent( _childremovedEvent );
  4523. _childremovedEvent.child = null;
  4524. }
  4525. return this;
  4526. }
  4527. removeFromParent() {
  4528. const parent = this.parent;
  4529. if ( parent !== null ) {
  4530. parent.remove( this );
  4531. }
  4532. return this;
  4533. }
  4534. clear() {
  4535. return this.remove( ... this.children );
  4536. }
  4537. attach( object ) {
  4538. // adds object as a child of this, while maintaining the object's world transform
  4539. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4540. this.updateWorldMatrix( true, false );
  4541. _m1$1.copy( this.matrixWorld ).invert();
  4542. if ( object.parent !== null ) {
  4543. object.parent.updateWorldMatrix( true, false );
  4544. _m1$1.multiply( object.parent.matrixWorld );
  4545. }
  4546. object.applyMatrix4( _m1$1 );
  4547. object.removeFromParent();
  4548. object.parent = this;
  4549. this.children.push( object );
  4550. object.updateWorldMatrix( false, true );
  4551. object.dispatchEvent( _addedEvent );
  4552. _childaddedEvent.child = object;
  4553. this.dispatchEvent( _childaddedEvent );
  4554. _childaddedEvent.child = null;
  4555. return this;
  4556. }
  4557. getObjectById( id ) {
  4558. return this.getObjectByProperty( 'id', id );
  4559. }
  4560. getObjectByName( name ) {
  4561. return this.getObjectByProperty( 'name', name );
  4562. }
  4563. getObjectByProperty( name, value ) {
  4564. if ( this[ name ] === value ) return this;
  4565. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4566. const child = this.children[ i ];
  4567. const object = child.getObjectByProperty( name, value );
  4568. if ( object !== undefined ) {
  4569. return object;
  4570. }
  4571. }
  4572. return undefined;
  4573. }
  4574. getObjectsByProperty( name, value, result = [] ) {
  4575. if ( this[ name ] === value ) result.push( this );
  4576. const children = this.children;
  4577. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4578. children[ i ].getObjectsByProperty( name, value, result );
  4579. }
  4580. return result;
  4581. }
  4582. getWorldPosition( target ) {
  4583. this.updateWorldMatrix( true, false );
  4584. return target.setFromMatrixPosition( this.matrixWorld );
  4585. }
  4586. getWorldQuaternion( target ) {
  4587. this.updateWorldMatrix( true, false );
  4588. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4589. return target;
  4590. }
  4591. getWorldScale( target ) {
  4592. this.updateWorldMatrix( true, false );
  4593. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4594. return target;
  4595. }
  4596. getWorldDirection( target ) {
  4597. this.updateWorldMatrix( true, false );
  4598. const e = this.matrixWorld.elements;
  4599. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4600. }
  4601. raycast( /* raycaster, intersects */ ) {}
  4602. traverse( callback ) {
  4603. callback( this );
  4604. const children = this.children;
  4605. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4606. children[ i ].traverse( callback );
  4607. }
  4608. }
  4609. traverseVisible( callback ) {
  4610. if ( this.visible === false ) return;
  4611. callback( this );
  4612. const children = this.children;
  4613. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4614. children[ i ].traverseVisible( callback );
  4615. }
  4616. }
  4617. traverseAncestors( callback ) {
  4618. const parent = this.parent;
  4619. if ( parent !== null ) {
  4620. callback( parent );
  4621. parent.traverseAncestors( callback );
  4622. }
  4623. }
  4624. updateMatrix() {
  4625. this.matrix.compose( this.position, this.quaternion, this.scale );
  4626. this.matrixWorldNeedsUpdate = true;
  4627. }
  4628. updateMatrixWorld( force ) {
  4629. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4630. if ( this.matrixWorldNeedsUpdate || force ) {
  4631. if ( this.matrixWorldAutoUpdate === true ) {
  4632. if ( this.parent === null ) {
  4633. this.matrixWorld.copy( this.matrix );
  4634. } else {
  4635. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4636. }
  4637. }
  4638. this.matrixWorldNeedsUpdate = false;
  4639. force = true;
  4640. }
  4641. // make sure descendants are updated if required
  4642. const children = this.children;
  4643. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4644. const child = children[ i ];
  4645. child.updateMatrixWorld( force );
  4646. }
  4647. }
  4648. updateWorldMatrix( updateParents, updateChildren ) {
  4649. const parent = this.parent;
  4650. if ( updateParents === true && parent !== null ) {
  4651. parent.updateWorldMatrix( true, false );
  4652. }
  4653. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4654. if ( this.matrixWorldAutoUpdate === true ) {
  4655. if ( this.parent === null ) {
  4656. this.matrixWorld.copy( this.matrix );
  4657. } else {
  4658. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4659. }
  4660. }
  4661. // make sure descendants are updated
  4662. if ( updateChildren === true ) {
  4663. const children = this.children;
  4664. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4665. const child = children[ i ];
  4666. child.updateWorldMatrix( false, true );
  4667. }
  4668. }
  4669. }
  4670. toJSON( meta ) {
  4671. // meta is a string when called from JSON.stringify
  4672. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4673. const output = {};
  4674. // meta is a hash used to collect geometries, materials.
  4675. // not providing it implies that this is the root object
  4676. // being serialized.
  4677. if ( isRootObject ) {
  4678. // initialize meta obj
  4679. meta = {
  4680. geometries: {},
  4681. materials: {},
  4682. textures: {},
  4683. images: {},
  4684. shapes: {},
  4685. skeletons: {},
  4686. animations: {},
  4687. nodes: {}
  4688. };
  4689. output.metadata = {
  4690. version: 4.6,
  4691. type: 'Object',
  4692. generator: 'Object3D.toJSON'
  4693. };
  4694. }
  4695. // standard Object3D serialization
  4696. const object = {};
  4697. object.uuid = this.uuid;
  4698. object.type = this.type;
  4699. if ( this.name !== '' ) object.name = this.name;
  4700. if ( this.castShadow === true ) object.castShadow = true;
  4701. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4702. if ( this.visible === false ) object.visible = false;
  4703. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4704. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4705. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4706. object.layers = this.layers.mask;
  4707. object.matrix = this.matrix.toArray();
  4708. object.up = this.up.toArray();
  4709. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4710. // object specific properties
  4711. if ( this.isInstancedMesh ) {
  4712. object.type = 'InstancedMesh';
  4713. object.count = this.count;
  4714. object.instanceMatrix = this.instanceMatrix.toJSON();
  4715. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4716. }
  4717. if ( this.isBatchedMesh ) {
  4718. object.type = 'BatchedMesh';
  4719. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4720. object.sortObjects = this.sortObjects;
  4721. object.drawRanges = this._drawRanges;
  4722. object.reservedRanges = this._reservedRanges;
  4723. object.visibility = this._visibility;
  4724. object.active = this._active;
  4725. object.bounds = this._bounds.map( bound => ( {
  4726. boxInitialized: bound.boxInitialized,
  4727. boxMin: bound.box.min.toArray(),
  4728. boxMax: bound.box.max.toArray(),
  4729. sphereInitialized: bound.sphereInitialized,
  4730. sphereRadius: bound.sphere.radius,
  4731. sphereCenter: bound.sphere.center.toArray()
  4732. } ) );
  4733. object.maxInstanceCount = this._maxInstanceCount;
  4734. object.maxVertexCount = this._maxVertexCount;
  4735. object.maxIndexCount = this._maxIndexCount;
  4736. object.geometryInitialized = this._geometryInitialized;
  4737. object.geometryCount = this._geometryCount;
  4738. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4739. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4740. if ( this.boundingSphere !== null ) {
  4741. object.boundingSphere = {
  4742. center: object.boundingSphere.center.toArray(),
  4743. radius: object.boundingSphere.radius
  4744. };
  4745. }
  4746. if ( this.boundingBox !== null ) {
  4747. object.boundingBox = {
  4748. min: object.boundingBox.min.toArray(),
  4749. max: object.boundingBox.max.toArray()
  4750. };
  4751. }
  4752. }
  4753. //
  4754. function serialize( library, element ) {
  4755. if ( library[ element.uuid ] === undefined ) {
  4756. library[ element.uuid ] = element.toJSON( meta );
  4757. }
  4758. return element.uuid;
  4759. }
  4760. if ( this.isScene ) {
  4761. if ( this.background ) {
  4762. if ( this.background.isColor ) {
  4763. object.background = this.background.toJSON();
  4764. } else if ( this.background.isTexture ) {
  4765. object.background = this.background.toJSON( meta ).uuid;
  4766. }
  4767. }
  4768. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4769. object.environment = this.environment.toJSON( meta ).uuid;
  4770. }
  4771. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4772. object.geometry = serialize( meta.geometries, this.geometry );
  4773. const parameters = this.geometry.parameters;
  4774. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4775. const shapes = parameters.shapes;
  4776. if ( Array.isArray( shapes ) ) {
  4777. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4778. const shape = shapes[ i ];
  4779. serialize( meta.shapes, shape );
  4780. }
  4781. } else {
  4782. serialize( meta.shapes, shapes );
  4783. }
  4784. }
  4785. }
  4786. if ( this.isSkinnedMesh ) {
  4787. object.bindMode = this.bindMode;
  4788. object.bindMatrix = this.bindMatrix.toArray();
  4789. if ( this.skeleton !== undefined ) {
  4790. serialize( meta.skeletons, this.skeleton );
  4791. object.skeleton = this.skeleton.uuid;
  4792. }
  4793. }
  4794. if ( this.material !== undefined ) {
  4795. if ( Array.isArray( this.material ) ) {
  4796. const uuids = [];
  4797. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4798. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4799. }
  4800. object.material = uuids;
  4801. } else {
  4802. object.material = serialize( meta.materials, this.material );
  4803. }
  4804. }
  4805. //
  4806. if ( this.children.length > 0 ) {
  4807. object.children = [];
  4808. for ( let i = 0; i < this.children.length; i ++ ) {
  4809. object.children.push( this.children[ i ].toJSON( meta ).object );
  4810. }
  4811. }
  4812. //
  4813. if ( this.animations.length > 0 ) {
  4814. object.animations = [];
  4815. for ( let i = 0; i < this.animations.length; i ++ ) {
  4816. const animation = this.animations[ i ];
  4817. object.animations.push( serialize( meta.animations, animation ) );
  4818. }
  4819. }
  4820. if ( isRootObject ) {
  4821. const geometries = extractFromCache( meta.geometries );
  4822. const materials = extractFromCache( meta.materials );
  4823. const textures = extractFromCache( meta.textures );
  4824. const images = extractFromCache( meta.images );
  4825. const shapes = extractFromCache( meta.shapes );
  4826. const skeletons = extractFromCache( meta.skeletons );
  4827. const animations = extractFromCache( meta.animations );
  4828. const nodes = extractFromCache( meta.nodes );
  4829. if ( geometries.length > 0 ) output.geometries = geometries;
  4830. if ( materials.length > 0 ) output.materials = materials;
  4831. if ( textures.length > 0 ) output.textures = textures;
  4832. if ( images.length > 0 ) output.images = images;
  4833. if ( shapes.length > 0 ) output.shapes = shapes;
  4834. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4835. if ( animations.length > 0 ) output.animations = animations;
  4836. if ( nodes.length > 0 ) output.nodes = nodes;
  4837. }
  4838. output.object = object;
  4839. return output;
  4840. // extract data from the cache hash
  4841. // remove metadata on each item
  4842. // and return as array
  4843. function extractFromCache( cache ) {
  4844. const values = [];
  4845. for ( const key in cache ) {
  4846. const data = cache[ key ];
  4847. delete data.metadata;
  4848. values.push( data );
  4849. }
  4850. return values;
  4851. }
  4852. }
  4853. clone( recursive ) {
  4854. return new this.constructor().copy( this, recursive );
  4855. }
  4856. copy( source, recursive = true ) {
  4857. this.name = source.name;
  4858. this.up.copy( source.up );
  4859. this.position.copy( source.position );
  4860. this.rotation.order = source.rotation.order;
  4861. this.quaternion.copy( source.quaternion );
  4862. this.scale.copy( source.scale );
  4863. this.matrix.copy( source.matrix );
  4864. this.matrixWorld.copy( source.matrixWorld );
  4865. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4866. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4867. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4868. this.layers.mask = source.layers.mask;
  4869. this.visible = source.visible;
  4870. this.castShadow = source.castShadow;
  4871. this.receiveShadow = source.receiveShadow;
  4872. this.frustumCulled = source.frustumCulled;
  4873. this.renderOrder = source.renderOrder;
  4874. this.animations = source.animations.slice();
  4875. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4876. if ( recursive === true ) {
  4877. for ( let i = 0; i < source.children.length; i ++ ) {
  4878. const child = source.children[ i ];
  4879. this.add( child.clone() );
  4880. }
  4881. }
  4882. return this;
  4883. }
  4884. }
  4885. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4886. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4887. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4888. const _v0$1 = /*@__PURE__*/ new Vector3();
  4889. const _v1$3 = /*@__PURE__*/ new Vector3();
  4890. const _v2$2 = /*@__PURE__*/ new Vector3();
  4891. const _v3$2 = /*@__PURE__*/ new Vector3();
  4892. const _vab = /*@__PURE__*/ new Vector3();
  4893. const _vac = /*@__PURE__*/ new Vector3();
  4894. const _vbc = /*@__PURE__*/ new Vector3();
  4895. const _vap = /*@__PURE__*/ new Vector3();
  4896. const _vbp = /*@__PURE__*/ new Vector3();
  4897. const _vcp = /*@__PURE__*/ new Vector3();
  4898. const _v40 = /*@__PURE__*/ new Vector4();
  4899. const _v41 = /*@__PURE__*/ new Vector4();
  4900. const _v42 = /*@__PURE__*/ new Vector4();
  4901. class Triangle {
  4902. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4903. this.a = a;
  4904. this.b = b;
  4905. this.c = c;
  4906. }
  4907. static getNormal( a, b, c, target ) {
  4908. target.subVectors( c, b );
  4909. _v0$1.subVectors( a, b );
  4910. target.cross( _v0$1 );
  4911. const targetLengthSq = target.lengthSq();
  4912. if ( targetLengthSq > 0 ) {
  4913. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4914. }
  4915. return target.set( 0, 0, 0 );
  4916. }
  4917. // static/instance method to calculate barycentric coordinates
  4918. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4919. static getBarycoord( point, a, b, c, target ) {
  4920. _v0$1.subVectors( c, a );
  4921. _v1$3.subVectors( b, a );
  4922. _v2$2.subVectors( point, a );
  4923. const dot00 = _v0$1.dot( _v0$1 );
  4924. const dot01 = _v0$1.dot( _v1$3 );
  4925. const dot02 = _v0$1.dot( _v2$2 );
  4926. const dot11 = _v1$3.dot( _v1$3 );
  4927. const dot12 = _v1$3.dot( _v2$2 );
  4928. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4929. // collinear or singular triangle
  4930. if ( denom === 0 ) {
  4931. target.set( 0, 0, 0 );
  4932. return null;
  4933. }
  4934. const invDenom = 1 / denom;
  4935. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4936. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4937. // barycentric coordinates must always sum to 1
  4938. return target.set( 1 - u - v, v, u );
  4939. }
  4940. static containsPoint( point, a, b, c ) {
  4941. // if the triangle is degenerate then we can't contain a point
  4942. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4943. return false;
  4944. }
  4945. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4946. }
  4947. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4948. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4949. target.x = 0;
  4950. target.y = 0;
  4951. if ( 'z' in target ) target.z = 0;
  4952. if ( 'w' in target ) target.w = 0;
  4953. return null;
  4954. }
  4955. target.setScalar( 0 );
  4956. target.addScaledVector( v1, _v3$2.x );
  4957. target.addScaledVector( v2, _v3$2.y );
  4958. target.addScaledVector( v3, _v3$2.z );
  4959. return target;
  4960. }
  4961. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  4962. _v40.setScalar( 0 );
  4963. _v41.setScalar( 0 );
  4964. _v42.setScalar( 0 );
  4965. _v40.fromBufferAttribute( attr, i1 );
  4966. _v41.fromBufferAttribute( attr, i2 );
  4967. _v42.fromBufferAttribute( attr, i3 );
  4968. target.setScalar( 0 );
  4969. target.addScaledVector( _v40, barycoord.x );
  4970. target.addScaledVector( _v41, barycoord.y );
  4971. target.addScaledVector( _v42, barycoord.z );
  4972. return target;
  4973. }
  4974. static isFrontFacing( a, b, c, direction ) {
  4975. _v0$1.subVectors( c, b );
  4976. _v1$3.subVectors( a, b );
  4977. // strictly front facing
  4978. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4979. }
  4980. set( a, b, c ) {
  4981. this.a.copy( a );
  4982. this.b.copy( b );
  4983. this.c.copy( c );
  4984. return this;
  4985. }
  4986. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4987. this.a.copy( points[ i0 ] );
  4988. this.b.copy( points[ i1 ] );
  4989. this.c.copy( points[ i2 ] );
  4990. return this;
  4991. }
  4992. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4993. this.a.fromBufferAttribute( attribute, i0 );
  4994. this.b.fromBufferAttribute( attribute, i1 );
  4995. this.c.fromBufferAttribute( attribute, i2 );
  4996. return this;
  4997. }
  4998. clone() {
  4999. return new this.constructor().copy( this );
  5000. }
  5001. copy( triangle ) {
  5002. this.a.copy( triangle.a );
  5003. this.b.copy( triangle.b );
  5004. this.c.copy( triangle.c );
  5005. return this;
  5006. }
  5007. getArea() {
  5008. _v0$1.subVectors( this.c, this.b );
  5009. _v1$3.subVectors( this.a, this.b );
  5010. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5011. }
  5012. getMidpoint( target ) {
  5013. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5014. }
  5015. getNormal( target ) {
  5016. return Triangle.getNormal( this.a, this.b, this.c, target );
  5017. }
  5018. getPlane( target ) {
  5019. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5020. }
  5021. getBarycoord( point, target ) {
  5022. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5023. }
  5024. getInterpolation( point, v1, v2, v3, target ) {
  5025. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5026. }
  5027. containsPoint( point ) {
  5028. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5029. }
  5030. isFrontFacing( direction ) {
  5031. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5032. }
  5033. intersectsBox( box ) {
  5034. return box.intersectsTriangle( this );
  5035. }
  5036. closestPointToPoint( p, target ) {
  5037. const a = this.a, b = this.b, c = this.c;
  5038. let v, w;
  5039. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5040. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5041. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5042. // basically, we're distinguishing which of the voronoi regions of the triangle
  5043. // the point lies in with the minimum amount of redundant computation.
  5044. _vab.subVectors( b, a );
  5045. _vac.subVectors( c, a );
  5046. _vap.subVectors( p, a );
  5047. const d1 = _vab.dot( _vap );
  5048. const d2 = _vac.dot( _vap );
  5049. if ( d1 <= 0 && d2 <= 0 ) {
  5050. // vertex region of A; barycentric coords (1, 0, 0)
  5051. return target.copy( a );
  5052. }
  5053. _vbp.subVectors( p, b );
  5054. const d3 = _vab.dot( _vbp );
  5055. const d4 = _vac.dot( _vbp );
  5056. if ( d3 >= 0 && d4 <= d3 ) {
  5057. // vertex region of B; barycentric coords (0, 1, 0)
  5058. return target.copy( b );
  5059. }
  5060. const vc = d1 * d4 - d3 * d2;
  5061. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5062. v = d1 / ( d1 - d3 );
  5063. // edge region of AB; barycentric coords (1-v, v, 0)
  5064. return target.copy( a ).addScaledVector( _vab, v );
  5065. }
  5066. _vcp.subVectors( p, c );
  5067. const d5 = _vab.dot( _vcp );
  5068. const d6 = _vac.dot( _vcp );
  5069. if ( d6 >= 0 && d5 <= d6 ) {
  5070. // vertex region of C; barycentric coords (0, 0, 1)
  5071. return target.copy( c );
  5072. }
  5073. const vb = d5 * d2 - d1 * d6;
  5074. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5075. w = d2 / ( d2 - d6 );
  5076. // edge region of AC; barycentric coords (1-w, 0, w)
  5077. return target.copy( a ).addScaledVector( _vac, w );
  5078. }
  5079. const va = d3 * d6 - d5 * d4;
  5080. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5081. _vbc.subVectors( c, b );
  5082. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5083. // edge region of BC; barycentric coords (0, 1-w, w)
  5084. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5085. }
  5086. // face region
  5087. const denom = 1 / ( va + vb + vc );
  5088. // u = va * denom
  5089. v = vb * denom;
  5090. w = vc * denom;
  5091. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5092. }
  5093. equals( triangle ) {
  5094. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5095. }
  5096. }
  5097. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5098. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5099. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5100. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5101. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5102. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5103. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5104. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5105. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5106. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5107. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5108. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5109. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5110. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5111. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5112. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5113. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5114. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5115. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5116. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5117. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5118. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5119. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5120. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5121. const _hslA = { h: 0, s: 0, l: 0 };
  5122. const _hslB = { h: 0, s: 0, l: 0 };
  5123. function hue2rgb( p, q, t ) {
  5124. if ( t < 0 ) t += 1;
  5125. if ( t > 1 ) t -= 1;
  5126. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5127. if ( t < 1 / 2 ) return q;
  5128. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5129. return p;
  5130. }
  5131. class Color {
  5132. constructor( r, g, b ) {
  5133. this.isColor = true;
  5134. this.r = 1;
  5135. this.g = 1;
  5136. this.b = 1;
  5137. return this.set( r, g, b );
  5138. }
  5139. set( r, g, b ) {
  5140. if ( g === undefined && b === undefined ) {
  5141. // r is THREE.Color, hex or string
  5142. const value = r;
  5143. if ( value && value.isColor ) {
  5144. this.copy( value );
  5145. } else if ( typeof value === 'number' ) {
  5146. this.setHex( value );
  5147. } else if ( typeof value === 'string' ) {
  5148. this.setStyle( value );
  5149. }
  5150. } else {
  5151. this.setRGB( r, g, b );
  5152. }
  5153. return this;
  5154. }
  5155. setScalar( scalar ) {
  5156. this.r = scalar;
  5157. this.g = scalar;
  5158. this.b = scalar;
  5159. return this;
  5160. }
  5161. setHex( hex, colorSpace = SRGBColorSpace ) {
  5162. hex = Math.floor( hex );
  5163. this.r = ( hex >> 16 & 255 ) / 255;
  5164. this.g = ( hex >> 8 & 255 ) / 255;
  5165. this.b = ( hex & 255 ) / 255;
  5166. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5167. return this;
  5168. }
  5169. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5170. this.r = r;
  5171. this.g = g;
  5172. this.b = b;
  5173. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5174. return this;
  5175. }
  5176. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5177. // h,s,l ranges are in 0.0 - 1.0
  5178. h = euclideanModulo( h, 1 );
  5179. s = clamp$1( s, 0, 1 );
  5180. l = clamp$1( l, 0, 1 );
  5181. if ( s === 0 ) {
  5182. this.r = this.g = this.b = l;
  5183. } else {
  5184. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5185. const q = ( 2 * l ) - p;
  5186. this.r = hue2rgb( q, p, h + 1 / 3 );
  5187. this.g = hue2rgb( q, p, h );
  5188. this.b = hue2rgb( q, p, h - 1 / 3 );
  5189. }
  5190. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5191. return this;
  5192. }
  5193. setStyle( style, colorSpace = SRGBColorSpace ) {
  5194. function handleAlpha( string ) {
  5195. if ( string === undefined ) return;
  5196. if ( parseFloat( string ) < 1 ) {
  5197. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5198. }
  5199. }
  5200. let m;
  5201. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5202. // rgb / hsl
  5203. let color;
  5204. const name = m[ 1 ];
  5205. const components = m[ 2 ];
  5206. switch ( name ) {
  5207. case 'rgb':
  5208. case 'rgba':
  5209. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5210. // rgb(255,0,0) rgba(255,0,0,0.5)
  5211. handleAlpha( color[ 4 ] );
  5212. return this.setRGB(
  5213. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5214. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5215. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5216. colorSpace
  5217. );
  5218. }
  5219. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5220. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5221. handleAlpha( color[ 4 ] );
  5222. return this.setRGB(
  5223. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5224. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5225. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5226. colorSpace
  5227. );
  5228. }
  5229. break;
  5230. case 'hsl':
  5231. case 'hsla':
  5232. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5233. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5234. handleAlpha( color[ 4 ] );
  5235. return this.setHSL(
  5236. parseFloat( color[ 1 ] ) / 360,
  5237. parseFloat( color[ 2 ] ) / 100,
  5238. parseFloat( color[ 3 ] ) / 100,
  5239. colorSpace
  5240. );
  5241. }
  5242. break;
  5243. default:
  5244. console.warn( 'THREE.Color: Unknown color model ' + style );
  5245. }
  5246. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5247. // hex color
  5248. const hex = m[ 1 ];
  5249. const size = hex.length;
  5250. if ( size === 3 ) {
  5251. // #ff0
  5252. return this.setRGB(
  5253. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5254. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5255. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5256. colorSpace
  5257. );
  5258. } else if ( size === 6 ) {
  5259. // #ff0000
  5260. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5261. } else {
  5262. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5263. }
  5264. } else if ( style && style.length > 0 ) {
  5265. return this.setColorName( style, colorSpace );
  5266. }
  5267. return this;
  5268. }
  5269. setColorName( style, colorSpace = SRGBColorSpace ) {
  5270. // color keywords
  5271. const hex = _colorKeywords[ style.toLowerCase() ];
  5272. if ( hex !== undefined ) {
  5273. // red
  5274. this.setHex( hex, colorSpace );
  5275. } else {
  5276. // unknown color
  5277. console.warn( 'THREE.Color: Unknown color ' + style );
  5278. }
  5279. return this;
  5280. }
  5281. clone() {
  5282. return new this.constructor( this.r, this.g, this.b );
  5283. }
  5284. copy( color ) {
  5285. this.r = color.r;
  5286. this.g = color.g;
  5287. this.b = color.b;
  5288. return this;
  5289. }
  5290. copySRGBToLinear( color ) {
  5291. this.r = SRGBToLinear( color.r );
  5292. this.g = SRGBToLinear( color.g );
  5293. this.b = SRGBToLinear( color.b );
  5294. return this;
  5295. }
  5296. copyLinearToSRGB( color ) {
  5297. this.r = LinearToSRGB( color.r );
  5298. this.g = LinearToSRGB( color.g );
  5299. this.b = LinearToSRGB( color.b );
  5300. return this;
  5301. }
  5302. convertSRGBToLinear() {
  5303. this.copySRGBToLinear( this );
  5304. return this;
  5305. }
  5306. convertLinearToSRGB() {
  5307. this.copyLinearToSRGB( this );
  5308. return this;
  5309. }
  5310. getHex( colorSpace = SRGBColorSpace ) {
  5311. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5312. return Math.round( clamp$1( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp$1( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp$1( _color.b * 255, 0, 255 ) );
  5313. }
  5314. getHexString( colorSpace = SRGBColorSpace ) {
  5315. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5316. }
  5317. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5318. // h,s,l ranges are in 0.0 - 1.0
  5319. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5320. const r = _color.r, g = _color.g, b = _color.b;
  5321. const max = Math.max( r, g, b );
  5322. const min = Math.min( r, g, b );
  5323. let hue, saturation;
  5324. const lightness = ( min + max ) / 2.0;
  5325. if ( min === max ) {
  5326. hue = 0;
  5327. saturation = 0;
  5328. } else {
  5329. const delta = max - min;
  5330. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5331. switch ( max ) {
  5332. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5333. case g: hue = ( b - r ) / delta + 2; break;
  5334. case b: hue = ( r - g ) / delta + 4; break;
  5335. }
  5336. hue /= 6;
  5337. }
  5338. target.h = hue;
  5339. target.s = saturation;
  5340. target.l = lightness;
  5341. return target;
  5342. }
  5343. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5344. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5345. target.r = _color.r;
  5346. target.g = _color.g;
  5347. target.b = _color.b;
  5348. return target;
  5349. }
  5350. getStyle( colorSpace = SRGBColorSpace ) {
  5351. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5352. const r = _color.r, g = _color.g, b = _color.b;
  5353. if ( colorSpace !== SRGBColorSpace ) {
  5354. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5355. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5356. }
  5357. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5358. }
  5359. offsetHSL( h, s, l ) {
  5360. this.getHSL( _hslA );
  5361. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5362. }
  5363. add( color ) {
  5364. this.r += color.r;
  5365. this.g += color.g;
  5366. this.b += color.b;
  5367. return this;
  5368. }
  5369. addColors( color1, color2 ) {
  5370. this.r = color1.r + color2.r;
  5371. this.g = color1.g + color2.g;
  5372. this.b = color1.b + color2.b;
  5373. return this;
  5374. }
  5375. addScalar( s ) {
  5376. this.r += s;
  5377. this.g += s;
  5378. this.b += s;
  5379. return this;
  5380. }
  5381. sub( color ) {
  5382. this.r = Math.max( 0, this.r - color.r );
  5383. this.g = Math.max( 0, this.g - color.g );
  5384. this.b = Math.max( 0, this.b - color.b );
  5385. return this;
  5386. }
  5387. multiply( color ) {
  5388. this.r *= color.r;
  5389. this.g *= color.g;
  5390. this.b *= color.b;
  5391. return this;
  5392. }
  5393. multiplyScalar( s ) {
  5394. this.r *= s;
  5395. this.g *= s;
  5396. this.b *= s;
  5397. return this;
  5398. }
  5399. lerp( color, alpha ) {
  5400. this.r += ( color.r - this.r ) * alpha;
  5401. this.g += ( color.g - this.g ) * alpha;
  5402. this.b += ( color.b - this.b ) * alpha;
  5403. return this;
  5404. }
  5405. lerpColors( color1, color2, alpha ) {
  5406. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5407. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5408. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5409. return this;
  5410. }
  5411. lerpHSL( color, alpha ) {
  5412. this.getHSL( _hslA );
  5413. color.getHSL( _hslB );
  5414. const h = lerp( _hslA.h, _hslB.h, alpha );
  5415. const s = lerp( _hslA.s, _hslB.s, alpha );
  5416. const l = lerp( _hslA.l, _hslB.l, alpha );
  5417. this.setHSL( h, s, l );
  5418. return this;
  5419. }
  5420. setFromVector3( v ) {
  5421. this.r = v.x;
  5422. this.g = v.y;
  5423. this.b = v.z;
  5424. return this;
  5425. }
  5426. applyMatrix3( m ) {
  5427. const r = this.r, g = this.g, b = this.b;
  5428. const e = m.elements;
  5429. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5430. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5431. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5432. return this;
  5433. }
  5434. equals( c ) {
  5435. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5436. }
  5437. fromArray( array, offset = 0 ) {
  5438. this.r = array[ offset ];
  5439. this.g = array[ offset + 1 ];
  5440. this.b = array[ offset + 2 ];
  5441. return this;
  5442. }
  5443. toArray( array = [], offset = 0 ) {
  5444. array[ offset ] = this.r;
  5445. array[ offset + 1 ] = this.g;
  5446. array[ offset + 2 ] = this.b;
  5447. return array;
  5448. }
  5449. fromBufferAttribute( attribute, index ) {
  5450. this.r = attribute.getX( index );
  5451. this.g = attribute.getY( index );
  5452. this.b = attribute.getZ( index );
  5453. return this;
  5454. }
  5455. toJSON() {
  5456. return this.getHex();
  5457. }
  5458. *[ Symbol.iterator ]() {
  5459. yield this.r;
  5460. yield this.g;
  5461. yield this.b;
  5462. }
  5463. }
  5464. const _color = /*@__PURE__*/ new Color();
  5465. Color.NAMES = _colorKeywords;
  5466. let _materialId = 0;
  5467. class Material extends EventDispatcher {
  5468. constructor() {
  5469. super();
  5470. this.isMaterial = true;
  5471. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5472. this.uuid = generateUUID();
  5473. this.name = '';
  5474. this.type = 'Material';
  5475. this.blending = NormalBlending;
  5476. this.side = FrontSide;
  5477. this.vertexColors = false;
  5478. this.opacity = 1;
  5479. this.transparent = false;
  5480. this.alphaHash = false;
  5481. this.blendSrc = SrcAlphaFactor;
  5482. this.blendDst = OneMinusSrcAlphaFactor;
  5483. this.blendEquation = AddEquation;
  5484. this.blendSrcAlpha = null;
  5485. this.blendDstAlpha = null;
  5486. this.blendEquationAlpha = null;
  5487. this.blendColor = new Color( 0, 0, 0 );
  5488. this.blendAlpha = 0;
  5489. this.depthFunc = LessEqualDepth;
  5490. this.depthTest = true;
  5491. this.depthWrite = true;
  5492. this.stencilWriteMask = 0xff;
  5493. this.stencilFunc = AlwaysStencilFunc;
  5494. this.stencilRef = 0;
  5495. this.stencilFuncMask = 0xff;
  5496. this.stencilFail = KeepStencilOp;
  5497. this.stencilZFail = KeepStencilOp;
  5498. this.stencilZPass = KeepStencilOp;
  5499. this.stencilWrite = false;
  5500. this.clippingPlanes = null;
  5501. this.clipIntersection = false;
  5502. this.clipShadows = false;
  5503. this.shadowSide = null;
  5504. this.colorWrite = true;
  5505. this.precision = null; // override the renderer's default precision for this material
  5506. this.polygonOffset = false;
  5507. this.polygonOffsetFactor = 0;
  5508. this.polygonOffsetUnits = 0;
  5509. this.dithering = false;
  5510. this.alphaToCoverage = false;
  5511. this.premultipliedAlpha = false;
  5512. this.forceSinglePass = false;
  5513. this.visible = true;
  5514. this.toneMapped = true;
  5515. this.userData = {};
  5516. this.version = 0;
  5517. this._alphaTest = 0;
  5518. }
  5519. get alphaTest() {
  5520. return this._alphaTest;
  5521. }
  5522. set alphaTest( value ) {
  5523. if ( this._alphaTest > 0 !== value > 0 ) {
  5524. this.version ++;
  5525. }
  5526. this._alphaTest = value;
  5527. }
  5528. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5529. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5530. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5531. customProgramCacheKey() {
  5532. return this.onBeforeCompile.toString();
  5533. }
  5534. setValues( values ) {
  5535. if ( values === undefined ) return;
  5536. for ( const key in values ) {
  5537. const newValue = values[ key ];
  5538. if ( newValue === undefined ) {
  5539. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5540. continue;
  5541. }
  5542. const currentValue = this[ key ];
  5543. if ( currentValue === undefined ) {
  5544. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5545. continue;
  5546. }
  5547. if ( currentValue && currentValue.isColor ) {
  5548. currentValue.set( newValue );
  5549. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5550. currentValue.copy( newValue );
  5551. } else {
  5552. this[ key ] = newValue;
  5553. }
  5554. }
  5555. }
  5556. toJSON( meta ) {
  5557. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5558. if ( isRootObject ) {
  5559. meta = {
  5560. textures: {},
  5561. images: {}
  5562. };
  5563. }
  5564. const data = {
  5565. metadata: {
  5566. version: 4.6,
  5567. type: 'Material',
  5568. generator: 'Material.toJSON'
  5569. }
  5570. };
  5571. // standard Material serialization
  5572. data.uuid = this.uuid;
  5573. data.type = this.type;
  5574. if ( this.name !== '' ) data.name = this.name;
  5575. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5576. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5577. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5578. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5579. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5580. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5581. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5582. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5583. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5584. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5585. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5586. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5587. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5588. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5589. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5590. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5591. }
  5592. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5593. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5594. }
  5595. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5596. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5597. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5598. }
  5599. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5600. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5601. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5602. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5603. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5604. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5605. }
  5606. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5607. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5608. }
  5609. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5610. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5611. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5612. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5613. }
  5614. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5615. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5616. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5617. if ( this.lightMap && this.lightMap.isTexture ) {
  5618. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5619. data.lightMapIntensity = this.lightMapIntensity;
  5620. }
  5621. if ( this.aoMap && this.aoMap.isTexture ) {
  5622. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5623. data.aoMapIntensity = this.aoMapIntensity;
  5624. }
  5625. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5626. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5627. data.bumpScale = this.bumpScale;
  5628. }
  5629. if ( this.normalMap && this.normalMap.isTexture ) {
  5630. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5631. data.normalMapType = this.normalMapType;
  5632. data.normalScale = this.normalScale.toArray();
  5633. }
  5634. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5635. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5636. data.displacementScale = this.displacementScale;
  5637. data.displacementBias = this.displacementBias;
  5638. }
  5639. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5640. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5641. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5642. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5643. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5644. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5645. if ( this.envMap && this.envMap.isTexture ) {
  5646. data.envMap = this.envMap.toJSON( meta ).uuid;
  5647. if ( this.combine !== undefined ) data.combine = this.combine;
  5648. }
  5649. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5650. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5651. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5652. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5653. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5654. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5655. }
  5656. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5657. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5658. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5659. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5660. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5661. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5662. if ( this.size !== undefined ) data.size = this.size;
  5663. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5664. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5665. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5666. if ( this.side !== FrontSide ) data.side = this.side;
  5667. if ( this.vertexColors === true ) data.vertexColors = true;
  5668. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5669. if ( this.transparent === true ) data.transparent = true;
  5670. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5671. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5672. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5673. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5674. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5675. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5676. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5677. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5678. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5679. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5680. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5681. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5682. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5683. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5684. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5685. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5686. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5687. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5688. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5689. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5690. // rotation (SpriteMaterial)
  5691. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5692. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5693. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5694. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5695. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5696. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5697. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5698. if ( this.scale !== undefined ) data.scale = this.scale;
  5699. if ( this.dithering === true ) data.dithering = true;
  5700. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5701. if ( this.alphaHash === true ) data.alphaHash = true;
  5702. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5703. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5704. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5705. if ( this.wireframe === true ) data.wireframe = true;
  5706. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5707. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5708. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5709. if ( this.flatShading === true ) data.flatShading = true;
  5710. if ( this.visible === false ) data.visible = false;
  5711. if ( this.toneMapped === false ) data.toneMapped = false;
  5712. if ( this.fog === false ) data.fog = false;
  5713. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5714. // TODO: Copied from Object3D.toJSON
  5715. function extractFromCache( cache ) {
  5716. const values = [];
  5717. for ( const key in cache ) {
  5718. const data = cache[ key ];
  5719. delete data.metadata;
  5720. values.push( data );
  5721. }
  5722. return values;
  5723. }
  5724. if ( isRootObject ) {
  5725. const textures = extractFromCache( meta.textures );
  5726. const images = extractFromCache( meta.images );
  5727. if ( textures.length > 0 ) data.textures = textures;
  5728. if ( images.length > 0 ) data.images = images;
  5729. }
  5730. return data;
  5731. }
  5732. clone() {
  5733. return new this.constructor().copy( this );
  5734. }
  5735. copy( source ) {
  5736. this.name = source.name;
  5737. this.blending = source.blending;
  5738. this.side = source.side;
  5739. this.vertexColors = source.vertexColors;
  5740. this.opacity = source.opacity;
  5741. this.transparent = source.transparent;
  5742. this.blendSrc = source.blendSrc;
  5743. this.blendDst = source.blendDst;
  5744. this.blendEquation = source.blendEquation;
  5745. this.blendSrcAlpha = source.blendSrcAlpha;
  5746. this.blendDstAlpha = source.blendDstAlpha;
  5747. this.blendEquationAlpha = source.blendEquationAlpha;
  5748. this.blendColor.copy( source.blendColor );
  5749. this.blendAlpha = source.blendAlpha;
  5750. this.depthFunc = source.depthFunc;
  5751. this.depthTest = source.depthTest;
  5752. this.depthWrite = source.depthWrite;
  5753. this.stencilWriteMask = source.stencilWriteMask;
  5754. this.stencilFunc = source.stencilFunc;
  5755. this.stencilRef = source.stencilRef;
  5756. this.stencilFuncMask = source.stencilFuncMask;
  5757. this.stencilFail = source.stencilFail;
  5758. this.stencilZFail = source.stencilZFail;
  5759. this.stencilZPass = source.stencilZPass;
  5760. this.stencilWrite = source.stencilWrite;
  5761. const srcPlanes = source.clippingPlanes;
  5762. let dstPlanes = null;
  5763. if ( srcPlanes !== null ) {
  5764. const n = srcPlanes.length;
  5765. dstPlanes = new Array( n );
  5766. for ( let i = 0; i !== n; ++ i ) {
  5767. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5768. }
  5769. }
  5770. this.clippingPlanes = dstPlanes;
  5771. this.clipIntersection = source.clipIntersection;
  5772. this.clipShadows = source.clipShadows;
  5773. this.shadowSide = source.shadowSide;
  5774. this.colorWrite = source.colorWrite;
  5775. this.precision = source.precision;
  5776. this.polygonOffset = source.polygonOffset;
  5777. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5778. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5779. this.dithering = source.dithering;
  5780. this.alphaTest = source.alphaTest;
  5781. this.alphaHash = source.alphaHash;
  5782. this.alphaToCoverage = source.alphaToCoverage;
  5783. this.premultipliedAlpha = source.premultipliedAlpha;
  5784. this.forceSinglePass = source.forceSinglePass;
  5785. this.visible = source.visible;
  5786. this.toneMapped = source.toneMapped;
  5787. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5788. return this;
  5789. }
  5790. dispose() {
  5791. this.dispatchEvent( { type: 'dispose' } );
  5792. }
  5793. set needsUpdate( value ) {
  5794. if ( value === true ) this.version ++;
  5795. }
  5796. onBuild( /* shaderobject, renderer */ ) {
  5797. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5798. }
  5799. }
  5800. class MeshBasicMaterial extends Material {
  5801. constructor( parameters ) {
  5802. super();
  5803. this.isMeshBasicMaterial = true;
  5804. this.type = 'MeshBasicMaterial';
  5805. this.color = new Color( 0xffffff ); // emissive
  5806. this.map = null;
  5807. this.lightMap = null;
  5808. this.lightMapIntensity = 1.0;
  5809. this.aoMap = null;
  5810. this.aoMapIntensity = 1.0;
  5811. this.specularMap = null;
  5812. this.alphaMap = null;
  5813. this.envMap = null;
  5814. this.envMapRotation = new Euler();
  5815. this.combine = MultiplyOperation;
  5816. this.reflectivity = 1;
  5817. this.refractionRatio = 0.98;
  5818. this.wireframe = false;
  5819. this.wireframeLinewidth = 1;
  5820. this.wireframeLinecap = 'round';
  5821. this.wireframeLinejoin = 'round';
  5822. this.fog = true;
  5823. this.setValues( parameters );
  5824. }
  5825. copy( source ) {
  5826. super.copy( source );
  5827. this.color.copy( source.color );
  5828. this.map = source.map;
  5829. this.lightMap = source.lightMap;
  5830. this.lightMapIntensity = source.lightMapIntensity;
  5831. this.aoMap = source.aoMap;
  5832. this.aoMapIntensity = source.aoMapIntensity;
  5833. this.specularMap = source.specularMap;
  5834. this.alphaMap = source.alphaMap;
  5835. this.envMap = source.envMap;
  5836. this.envMapRotation.copy( source.envMapRotation );
  5837. this.combine = source.combine;
  5838. this.reflectivity = source.reflectivity;
  5839. this.refractionRatio = source.refractionRatio;
  5840. this.wireframe = source.wireframe;
  5841. this.wireframeLinewidth = source.wireframeLinewidth;
  5842. this.wireframeLinecap = source.wireframeLinecap;
  5843. this.wireframeLinejoin = source.wireframeLinejoin;
  5844. this.fog = source.fog;
  5845. return this;
  5846. }
  5847. }
  5848. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5849. const _tables = /*@__PURE__*/ _generateTables();
  5850. function _generateTables() {
  5851. // float32 to float16 helpers
  5852. const buffer = new ArrayBuffer( 4 );
  5853. const floatView = new Float32Array( buffer );
  5854. const uint32View = new Uint32Array( buffer );
  5855. const baseTable = new Uint32Array( 512 );
  5856. const shiftTable = new Uint32Array( 512 );
  5857. for ( let i = 0; i < 256; ++ i ) {
  5858. const e = i - 127;
  5859. // very small number (0, -0)
  5860. if ( e < - 27 ) {
  5861. baseTable[ i ] = 0x0000;
  5862. baseTable[ i | 0x100 ] = 0x8000;
  5863. shiftTable[ i ] = 24;
  5864. shiftTable[ i | 0x100 ] = 24;
  5865. // small number (denorm)
  5866. } else if ( e < - 14 ) {
  5867. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5868. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5869. shiftTable[ i ] = - e - 1;
  5870. shiftTable[ i | 0x100 ] = - e - 1;
  5871. // normal number
  5872. } else if ( e <= 15 ) {
  5873. baseTable[ i ] = ( e + 15 ) << 10;
  5874. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5875. shiftTable[ i ] = 13;
  5876. shiftTable[ i | 0x100 ] = 13;
  5877. // large number (Infinity, -Infinity)
  5878. } else if ( e < 128 ) {
  5879. baseTable[ i ] = 0x7c00;
  5880. baseTable[ i | 0x100 ] = 0xfc00;
  5881. shiftTable[ i ] = 24;
  5882. shiftTable[ i | 0x100 ] = 24;
  5883. // stay (NaN, Infinity, -Infinity)
  5884. } else {
  5885. baseTable[ i ] = 0x7c00;
  5886. baseTable[ i | 0x100 ] = 0xfc00;
  5887. shiftTable[ i ] = 13;
  5888. shiftTable[ i | 0x100 ] = 13;
  5889. }
  5890. }
  5891. // float16 to float32 helpers
  5892. const mantissaTable = new Uint32Array( 2048 );
  5893. const exponentTable = new Uint32Array( 64 );
  5894. const offsetTable = new Uint32Array( 64 );
  5895. for ( let i = 1; i < 1024; ++ i ) {
  5896. let m = i << 13; // zero pad mantissa bits
  5897. let e = 0; // zero exponent
  5898. // normalized
  5899. while ( ( m & 0x00800000 ) === 0 ) {
  5900. m <<= 1;
  5901. e -= 0x00800000; // decrement exponent
  5902. }
  5903. m &= ~ 0x00800000; // clear leading 1 bit
  5904. e += 0x38800000; // adjust bias
  5905. mantissaTable[ i ] = m | e;
  5906. }
  5907. for ( let i = 1024; i < 2048; ++ i ) {
  5908. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5909. }
  5910. for ( let i = 1; i < 31; ++ i ) {
  5911. exponentTable[ i ] = i << 23;
  5912. }
  5913. exponentTable[ 31 ] = 0x47800000;
  5914. exponentTable[ 32 ] = 0x80000000;
  5915. for ( let i = 33; i < 63; ++ i ) {
  5916. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5917. }
  5918. exponentTable[ 63 ] = 0xc7800000;
  5919. for ( let i = 1; i < 64; ++ i ) {
  5920. if ( i !== 32 ) {
  5921. offsetTable[ i ] = 1024;
  5922. }
  5923. }
  5924. return {
  5925. floatView: floatView,
  5926. uint32View: uint32View,
  5927. baseTable: baseTable,
  5928. shiftTable: shiftTable,
  5929. mantissaTable: mantissaTable,
  5930. exponentTable: exponentTable,
  5931. offsetTable: offsetTable
  5932. };
  5933. }
  5934. // float32 to float16
  5935. function toHalfFloat( val ) {
  5936. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5937. val = clamp$1( val, - 65504, 65504 );
  5938. _tables.floatView[ 0 ] = val;
  5939. const f = _tables.uint32View[ 0 ];
  5940. const e = ( f >> 23 ) & 0x1ff;
  5941. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5942. }
  5943. // float16 to float32
  5944. function fromHalfFloat( val ) {
  5945. const m = val >> 10;
  5946. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5947. return _tables.floatView[ 0 ];
  5948. }
  5949. const DataUtils = {
  5950. toHalfFloat: toHalfFloat,
  5951. fromHalfFloat: fromHalfFloat,
  5952. };
  5953. const _vector$9 = /*@__PURE__*/ new Vector3();
  5954. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5955. class BufferAttribute {
  5956. constructor( array, itemSize, normalized = false ) {
  5957. if ( Array.isArray( array ) ) {
  5958. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5959. }
  5960. this.isBufferAttribute = true;
  5961. this.name = '';
  5962. this.array = array;
  5963. this.itemSize = itemSize;
  5964. this.count = array !== undefined ? array.length / itemSize : 0;
  5965. this.normalized = normalized;
  5966. this.usage = StaticDrawUsage;
  5967. this.updateRanges = [];
  5968. this.gpuType = FloatType;
  5969. this.version = 0;
  5970. }
  5971. onUploadCallback() {}
  5972. set needsUpdate( value ) {
  5973. if ( value === true ) this.version ++;
  5974. }
  5975. setUsage( value ) {
  5976. this.usage = value;
  5977. return this;
  5978. }
  5979. addUpdateRange( start, count ) {
  5980. this.updateRanges.push( { start, count } );
  5981. }
  5982. clearUpdateRanges() {
  5983. this.updateRanges.length = 0;
  5984. }
  5985. copy( source ) {
  5986. this.name = source.name;
  5987. this.array = new source.array.constructor( source.array );
  5988. this.itemSize = source.itemSize;
  5989. this.count = source.count;
  5990. this.normalized = source.normalized;
  5991. this.usage = source.usage;
  5992. this.gpuType = source.gpuType;
  5993. return this;
  5994. }
  5995. copyAt( index1, attribute, index2 ) {
  5996. index1 *= this.itemSize;
  5997. index2 *= attribute.itemSize;
  5998. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5999. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6000. }
  6001. return this;
  6002. }
  6003. copyArray( array ) {
  6004. this.array.set( array );
  6005. return this;
  6006. }
  6007. applyMatrix3( m ) {
  6008. if ( this.itemSize === 2 ) {
  6009. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6010. _vector2$1.fromBufferAttribute( this, i );
  6011. _vector2$1.applyMatrix3( m );
  6012. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6013. }
  6014. } else if ( this.itemSize === 3 ) {
  6015. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6016. _vector$9.fromBufferAttribute( this, i );
  6017. _vector$9.applyMatrix3( m );
  6018. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6019. }
  6020. }
  6021. return this;
  6022. }
  6023. applyMatrix4( m ) {
  6024. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6025. _vector$9.fromBufferAttribute( this, i );
  6026. _vector$9.applyMatrix4( m );
  6027. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6028. }
  6029. return this;
  6030. }
  6031. applyNormalMatrix( m ) {
  6032. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6033. _vector$9.fromBufferAttribute( this, i );
  6034. _vector$9.applyNormalMatrix( m );
  6035. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6036. }
  6037. return this;
  6038. }
  6039. transformDirection( m ) {
  6040. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6041. _vector$9.fromBufferAttribute( this, i );
  6042. _vector$9.transformDirection( m );
  6043. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6044. }
  6045. return this;
  6046. }
  6047. set( value, offset = 0 ) {
  6048. // Matching BufferAttribute constructor, do not normalize the array.
  6049. this.array.set( value, offset );
  6050. return this;
  6051. }
  6052. getComponent( index, component ) {
  6053. let value = this.array[ index * this.itemSize + component ];
  6054. if ( this.normalized ) value = denormalize( value, this.array );
  6055. return value;
  6056. }
  6057. setComponent( index, component, value ) {
  6058. if ( this.normalized ) value = normalize$1( value, this.array );
  6059. this.array[ index * this.itemSize + component ] = value;
  6060. return this;
  6061. }
  6062. getX( index ) {
  6063. let x = this.array[ index * this.itemSize ];
  6064. if ( this.normalized ) x = denormalize( x, this.array );
  6065. return x;
  6066. }
  6067. setX( index, x ) {
  6068. if ( this.normalized ) x = normalize$1( x, this.array );
  6069. this.array[ index * this.itemSize ] = x;
  6070. return this;
  6071. }
  6072. getY( index ) {
  6073. let y = this.array[ index * this.itemSize + 1 ];
  6074. if ( this.normalized ) y = denormalize( y, this.array );
  6075. return y;
  6076. }
  6077. setY( index, y ) {
  6078. if ( this.normalized ) y = normalize$1( y, this.array );
  6079. this.array[ index * this.itemSize + 1 ] = y;
  6080. return this;
  6081. }
  6082. getZ( index ) {
  6083. let z = this.array[ index * this.itemSize + 2 ];
  6084. if ( this.normalized ) z = denormalize( z, this.array );
  6085. return z;
  6086. }
  6087. setZ( index, z ) {
  6088. if ( this.normalized ) z = normalize$1( z, this.array );
  6089. this.array[ index * this.itemSize + 2 ] = z;
  6090. return this;
  6091. }
  6092. getW( index ) {
  6093. let w = this.array[ index * this.itemSize + 3 ];
  6094. if ( this.normalized ) w = denormalize( w, this.array );
  6095. return w;
  6096. }
  6097. setW( index, w ) {
  6098. if ( this.normalized ) w = normalize$1( w, this.array );
  6099. this.array[ index * this.itemSize + 3 ] = w;
  6100. return this;
  6101. }
  6102. setXY( index, x, y ) {
  6103. index *= this.itemSize;
  6104. if ( this.normalized ) {
  6105. x = normalize$1( x, this.array );
  6106. y = normalize$1( y, this.array );
  6107. }
  6108. this.array[ index + 0 ] = x;
  6109. this.array[ index + 1 ] = y;
  6110. return this;
  6111. }
  6112. setXYZ( index, x, y, z ) {
  6113. index *= this.itemSize;
  6114. if ( this.normalized ) {
  6115. x = normalize$1( x, this.array );
  6116. y = normalize$1( y, this.array );
  6117. z = normalize$1( z, this.array );
  6118. }
  6119. this.array[ index + 0 ] = x;
  6120. this.array[ index + 1 ] = y;
  6121. this.array[ index + 2 ] = z;
  6122. return this;
  6123. }
  6124. setXYZW( index, x, y, z, w ) {
  6125. index *= this.itemSize;
  6126. if ( this.normalized ) {
  6127. x = normalize$1( x, this.array );
  6128. y = normalize$1( y, this.array );
  6129. z = normalize$1( z, this.array );
  6130. w = normalize$1( w, this.array );
  6131. }
  6132. this.array[ index + 0 ] = x;
  6133. this.array[ index + 1 ] = y;
  6134. this.array[ index + 2 ] = z;
  6135. this.array[ index + 3 ] = w;
  6136. return this;
  6137. }
  6138. onUpload( callback ) {
  6139. this.onUploadCallback = callback;
  6140. return this;
  6141. }
  6142. clone() {
  6143. return new this.constructor( this.array, this.itemSize ).copy( this );
  6144. }
  6145. toJSON() {
  6146. const data = {
  6147. itemSize: this.itemSize,
  6148. type: this.array.constructor.name,
  6149. array: Array.from( this.array ),
  6150. normalized: this.normalized
  6151. };
  6152. if ( this.name !== '' ) data.name = this.name;
  6153. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6154. return data;
  6155. }
  6156. }
  6157. //
  6158. class Int8BufferAttribute extends BufferAttribute {
  6159. constructor( array, itemSize, normalized ) {
  6160. super( new Int8Array( array ), itemSize, normalized );
  6161. }
  6162. }
  6163. class Uint8BufferAttribute extends BufferAttribute {
  6164. constructor( array, itemSize, normalized ) {
  6165. super( new Uint8Array( array ), itemSize, normalized );
  6166. }
  6167. }
  6168. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6169. constructor( array, itemSize, normalized ) {
  6170. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6171. }
  6172. }
  6173. class Int16BufferAttribute extends BufferAttribute {
  6174. constructor( array, itemSize, normalized ) {
  6175. super( new Int16Array( array ), itemSize, normalized );
  6176. }
  6177. }
  6178. class Uint16BufferAttribute extends BufferAttribute {
  6179. constructor( array, itemSize, normalized ) {
  6180. super( new Uint16Array( array ), itemSize, normalized );
  6181. }
  6182. }
  6183. class Int32BufferAttribute extends BufferAttribute {
  6184. constructor( array, itemSize, normalized ) {
  6185. super( new Int32Array( array ), itemSize, normalized );
  6186. }
  6187. }
  6188. class Uint32BufferAttribute extends BufferAttribute {
  6189. constructor( array, itemSize, normalized ) {
  6190. super( new Uint32Array( array ), itemSize, normalized );
  6191. }
  6192. }
  6193. class Float16BufferAttribute extends BufferAttribute {
  6194. constructor( array, itemSize, normalized ) {
  6195. super( new Uint16Array( array ), itemSize, normalized );
  6196. this.isFloat16BufferAttribute = true;
  6197. }
  6198. getX( index ) {
  6199. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6200. if ( this.normalized ) x = denormalize( x, this.array );
  6201. return x;
  6202. }
  6203. setX( index, x ) {
  6204. if ( this.normalized ) x = normalize$1( x, this.array );
  6205. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6206. return this;
  6207. }
  6208. getY( index ) {
  6209. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6210. if ( this.normalized ) y = denormalize( y, this.array );
  6211. return y;
  6212. }
  6213. setY( index, y ) {
  6214. if ( this.normalized ) y = normalize$1( y, this.array );
  6215. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6216. return this;
  6217. }
  6218. getZ( index ) {
  6219. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6220. if ( this.normalized ) z = denormalize( z, this.array );
  6221. return z;
  6222. }
  6223. setZ( index, z ) {
  6224. if ( this.normalized ) z = normalize$1( z, this.array );
  6225. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6226. return this;
  6227. }
  6228. getW( index ) {
  6229. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6230. if ( this.normalized ) w = denormalize( w, this.array );
  6231. return w;
  6232. }
  6233. setW( index, w ) {
  6234. if ( this.normalized ) w = normalize$1( w, this.array );
  6235. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6236. return this;
  6237. }
  6238. setXY( index, x, y ) {
  6239. index *= this.itemSize;
  6240. if ( this.normalized ) {
  6241. x = normalize$1( x, this.array );
  6242. y = normalize$1( y, this.array );
  6243. }
  6244. this.array[ index + 0 ] = toHalfFloat( x );
  6245. this.array[ index + 1 ] = toHalfFloat( y );
  6246. return this;
  6247. }
  6248. setXYZ( index, x, y, z ) {
  6249. index *= this.itemSize;
  6250. if ( this.normalized ) {
  6251. x = normalize$1( x, this.array );
  6252. y = normalize$1( y, this.array );
  6253. z = normalize$1( z, this.array );
  6254. }
  6255. this.array[ index + 0 ] = toHalfFloat( x );
  6256. this.array[ index + 1 ] = toHalfFloat( y );
  6257. this.array[ index + 2 ] = toHalfFloat( z );
  6258. return this;
  6259. }
  6260. setXYZW( index, x, y, z, w ) {
  6261. index *= this.itemSize;
  6262. if ( this.normalized ) {
  6263. x = normalize$1( x, this.array );
  6264. y = normalize$1( y, this.array );
  6265. z = normalize$1( z, this.array );
  6266. w = normalize$1( w, this.array );
  6267. }
  6268. this.array[ index + 0 ] = toHalfFloat( x );
  6269. this.array[ index + 1 ] = toHalfFloat( y );
  6270. this.array[ index + 2 ] = toHalfFloat( z );
  6271. this.array[ index + 3 ] = toHalfFloat( w );
  6272. return this;
  6273. }
  6274. }
  6275. class Float32BufferAttribute extends BufferAttribute {
  6276. constructor( array, itemSize, normalized ) {
  6277. super( new Float32Array( array ), itemSize, normalized );
  6278. }
  6279. }
  6280. let _id$9 = 0;
  6281. const _m1 = /*@__PURE__*/ new Matrix4();
  6282. const _obj = /*@__PURE__*/ new Object3D();
  6283. const _offset = /*@__PURE__*/ new Vector3();
  6284. const _box$2 = /*@__PURE__*/ new Box3();
  6285. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6286. const _vector$8 = /*@__PURE__*/ new Vector3();
  6287. class BufferGeometry extends EventDispatcher {
  6288. constructor() {
  6289. super();
  6290. this.isBufferGeometry = true;
  6291. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6292. this.uuid = generateUUID();
  6293. this.name = '';
  6294. this.type = 'BufferGeometry';
  6295. this.index = null;
  6296. this.attributes = {};
  6297. this.morphAttributes = {};
  6298. this.morphTargetsRelative = false;
  6299. this.groups = [];
  6300. this.boundingBox = null;
  6301. this.boundingSphere = null;
  6302. this.drawRange = { start: 0, count: Infinity };
  6303. this.userData = {};
  6304. }
  6305. getIndex() {
  6306. return this.index;
  6307. }
  6308. setIndex( index ) {
  6309. if ( Array.isArray( index ) ) {
  6310. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6311. } else {
  6312. this.index = index;
  6313. }
  6314. return this;
  6315. }
  6316. getAttribute( name ) {
  6317. return this.attributes[ name ];
  6318. }
  6319. setAttribute( name, attribute ) {
  6320. this.attributes[ name ] = attribute;
  6321. return this;
  6322. }
  6323. deleteAttribute( name ) {
  6324. delete this.attributes[ name ];
  6325. return this;
  6326. }
  6327. hasAttribute( name ) {
  6328. return this.attributes[ name ] !== undefined;
  6329. }
  6330. addGroup( start, count, materialIndex = 0 ) {
  6331. this.groups.push( {
  6332. start: start,
  6333. count: count,
  6334. materialIndex: materialIndex
  6335. } );
  6336. }
  6337. clearGroups() {
  6338. this.groups = [];
  6339. }
  6340. setDrawRange( start, count ) {
  6341. this.drawRange.start = start;
  6342. this.drawRange.count = count;
  6343. }
  6344. applyMatrix4( matrix ) {
  6345. const position = this.attributes.position;
  6346. if ( position !== undefined ) {
  6347. position.applyMatrix4( matrix );
  6348. position.needsUpdate = true;
  6349. }
  6350. const normal = this.attributes.normal;
  6351. if ( normal !== undefined ) {
  6352. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6353. normal.applyNormalMatrix( normalMatrix );
  6354. normal.needsUpdate = true;
  6355. }
  6356. const tangent = this.attributes.tangent;
  6357. if ( tangent !== undefined ) {
  6358. tangent.transformDirection( matrix );
  6359. tangent.needsUpdate = true;
  6360. }
  6361. if ( this.boundingBox !== null ) {
  6362. this.computeBoundingBox();
  6363. }
  6364. if ( this.boundingSphere !== null ) {
  6365. this.computeBoundingSphere();
  6366. }
  6367. return this;
  6368. }
  6369. applyQuaternion( q ) {
  6370. _m1.makeRotationFromQuaternion( q );
  6371. this.applyMatrix4( _m1 );
  6372. return this;
  6373. }
  6374. rotateX( angle ) {
  6375. // rotate geometry around world x-axis
  6376. _m1.makeRotationX( angle );
  6377. this.applyMatrix4( _m1 );
  6378. return this;
  6379. }
  6380. rotateY( angle ) {
  6381. // rotate geometry around world y-axis
  6382. _m1.makeRotationY( angle );
  6383. this.applyMatrix4( _m1 );
  6384. return this;
  6385. }
  6386. rotateZ( angle ) {
  6387. // rotate geometry around world z-axis
  6388. _m1.makeRotationZ( angle );
  6389. this.applyMatrix4( _m1 );
  6390. return this;
  6391. }
  6392. translate( x, y, z ) {
  6393. // translate geometry
  6394. _m1.makeTranslation( x, y, z );
  6395. this.applyMatrix4( _m1 );
  6396. return this;
  6397. }
  6398. scale( x, y, z ) {
  6399. // scale geometry
  6400. _m1.makeScale( x, y, z );
  6401. this.applyMatrix4( _m1 );
  6402. return this;
  6403. }
  6404. lookAt( vector ) {
  6405. _obj.lookAt( vector );
  6406. _obj.updateMatrix();
  6407. this.applyMatrix4( _obj.matrix );
  6408. return this;
  6409. }
  6410. center() {
  6411. this.computeBoundingBox();
  6412. this.boundingBox.getCenter( _offset ).negate();
  6413. this.translate( _offset.x, _offset.y, _offset.z );
  6414. return this;
  6415. }
  6416. setFromPoints( points ) {
  6417. const position = [];
  6418. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6419. const point = points[ i ];
  6420. position.push( point.x, point.y, point.z || 0 );
  6421. }
  6422. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6423. return this;
  6424. }
  6425. computeBoundingBox() {
  6426. if ( this.boundingBox === null ) {
  6427. this.boundingBox = new Box3();
  6428. }
  6429. const position = this.attributes.position;
  6430. const morphAttributesPosition = this.morphAttributes.position;
  6431. if ( position && position.isGLBufferAttribute ) {
  6432. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6433. this.boundingBox.set(
  6434. new Vector3( - Infinity, - Infinity, - Infinity ),
  6435. new Vector3( + Infinity, + Infinity, + Infinity )
  6436. );
  6437. return;
  6438. }
  6439. if ( position !== undefined ) {
  6440. this.boundingBox.setFromBufferAttribute( position );
  6441. // process morph attributes if present
  6442. if ( morphAttributesPosition ) {
  6443. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6444. const morphAttribute = morphAttributesPosition[ i ];
  6445. _box$2.setFromBufferAttribute( morphAttribute );
  6446. if ( this.morphTargetsRelative ) {
  6447. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6448. this.boundingBox.expandByPoint( _vector$8 );
  6449. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6450. this.boundingBox.expandByPoint( _vector$8 );
  6451. } else {
  6452. this.boundingBox.expandByPoint( _box$2.min );
  6453. this.boundingBox.expandByPoint( _box$2.max );
  6454. }
  6455. }
  6456. }
  6457. } else {
  6458. this.boundingBox.makeEmpty();
  6459. }
  6460. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6461. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6462. }
  6463. }
  6464. computeBoundingSphere() {
  6465. if ( this.boundingSphere === null ) {
  6466. this.boundingSphere = new Sphere();
  6467. }
  6468. const position = this.attributes.position;
  6469. const morphAttributesPosition = this.morphAttributes.position;
  6470. if ( position && position.isGLBufferAttribute ) {
  6471. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6472. this.boundingSphere.set( new Vector3(), Infinity );
  6473. return;
  6474. }
  6475. if ( position ) {
  6476. // first, find the center of the bounding sphere
  6477. const center = this.boundingSphere.center;
  6478. _box$2.setFromBufferAttribute( position );
  6479. // process morph attributes if present
  6480. if ( morphAttributesPosition ) {
  6481. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6482. const morphAttribute = morphAttributesPosition[ i ];
  6483. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6484. if ( this.morphTargetsRelative ) {
  6485. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6486. _box$2.expandByPoint( _vector$8 );
  6487. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6488. _box$2.expandByPoint( _vector$8 );
  6489. } else {
  6490. _box$2.expandByPoint( _boxMorphTargets.min );
  6491. _box$2.expandByPoint( _boxMorphTargets.max );
  6492. }
  6493. }
  6494. }
  6495. _box$2.getCenter( center );
  6496. // second, try to find a boundingSphere with a radius smaller than the
  6497. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6498. let maxRadiusSq = 0;
  6499. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6500. _vector$8.fromBufferAttribute( position, i );
  6501. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6502. }
  6503. // process morph attributes if present
  6504. if ( morphAttributesPosition ) {
  6505. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6506. const morphAttribute = morphAttributesPosition[ i ];
  6507. const morphTargetsRelative = this.morphTargetsRelative;
  6508. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6509. _vector$8.fromBufferAttribute( morphAttribute, j );
  6510. if ( morphTargetsRelative ) {
  6511. _offset.fromBufferAttribute( position, j );
  6512. _vector$8.add( _offset );
  6513. }
  6514. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6515. }
  6516. }
  6517. }
  6518. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6519. if ( isNaN( this.boundingSphere.radius ) ) {
  6520. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6521. }
  6522. }
  6523. }
  6524. computeTangents() {
  6525. const index = this.index;
  6526. const attributes = this.attributes;
  6527. // based on http://www.terathon.com/code/tangent.html
  6528. // (per vertex tangents)
  6529. if ( index === null ||
  6530. attributes.position === undefined ||
  6531. attributes.normal === undefined ||
  6532. attributes.uv === undefined ) {
  6533. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6534. return;
  6535. }
  6536. const positionAttribute = attributes.position;
  6537. const normalAttribute = attributes.normal;
  6538. const uvAttribute = attributes.uv;
  6539. if ( this.hasAttribute( 'tangent' ) === false ) {
  6540. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6541. }
  6542. const tangentAttribute = this.getAttribute( 'tangent' );
  6543. const tan1 = [], tan2 = [];
  6544. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6545. tan1[ i ] = new Vector3();
  6546. tan2[ i ] = new Vector3();
  6547. }
  6548. const vA = new Vector3(),
  6549. vB = new Vector3(),
  6550. vC = new Vector3(),
  6551. uvA = new Vector2(),
  6552. uvB = new Vector2(),
  6553. uvC = new Vector2(),
  6554. sdir = new Vector3(),
  6555. tdir = new Vector3();
  6556. function handleTriangle( a, b, c ) {
  6557. vA.fromBufferAttribute( positionAttribute, a );
  6558. vB.fromBufferAttribute( positionAttribute, b );
  6559. vC.fromBufferAttribute( positionAttribute, c );
  6560. uvA.fromBufferAttribute( uvAttribute, a );
  6561. uvB.fromBufferAttribute( uvAttribute, b );
  6562. uvC.fromBufferAttribute( uvAttribute, c );
  6563. vB.sub( vA );
  6564. vC.sub( vA );
  6565. uvB.sub( uvA );
  6566. uvC.sub( uvA );
  6567. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6568. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6569. if ( ! isFinite( r ) ) return;
  6570. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6571. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6572. tan1[ a ].add( sdir );
  6573. tan1[ b ].add( sdir );
  6574. tan1[ c ].add( sdir );
  6575. tan2[ a ].add( tdir );
  6576. tan2[ b ].add( tdir );
  6577. tan2[ c ].add( tdir );
  6578. }
  6579. let groups = this.groups;
  6580. if ( groups.length === 0 ) {
  6581. groups = [ {
  6582. start: 0,
  6583. count: index.count
  6584. } ];
  6585. }
  6586. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6587. const group = groups[ i ];
  6588. const start = group.start;
  6589. const count = group.count;
  6590. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6591. handleTriangle(
  6592. index.getX( j + 0 ),
  6593. index.getX( j + 1 ),
  6594. index.getX( j + 2 )
  6595. );
  6596. }
  6597. }
  6598. const tmp = new Vector3(), tmp2 = new Vector3();
  6599. const n = new Vector3(), n2 = new Vector3();
  6600. function handleVertex( v ) {
  6601. n.fromBufferAttribute( normalAttribute, v );
  6602. n2.copy( n );
  6603. const t = tan1[ v ];
  6604. // Gram-Schmidt orthogonalize
  6605. tmp.copy( t );
  6606. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6607. // Calculate handedness
  6608. tmp2.crossVectors( n2, t );
  6609. const test = tmp2.dot( tan2[ v ] );
  6610. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6611. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6612. }
  6613. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6614. const group = groups[ i ];
  6615. const start = group.start;
  6616. const count = group.count;
  6617. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6618. handleVertex( index.getX( j + 0 ) );
  6619. handleVertex( index.getX( j + 1 ) );
  6620. handleVertex( index.getX( j + 2 ) );
  6621. }
  6622. }
  6623. }
  6624. computeVertexNormals() {
  6625. const index = this.index;
  6626. const positionAttribute = this.getAttribute( 'position' );
  6627. if ( positionAttribute !== undefined ) {
  6628. let normalAttribute = this.getAttribute( 'normal' );
  6629. if ( normalAttribute === undefined ) {
  6630. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6631. this.setAttribute( 'normal', normalAttribute );
  6632. } else {
  6633. // reset existing normals to zero
  6634. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6635. normalAttribute.setXYZ( i, 0, 0, 0 );
  6636. }
  6637. }
  6638. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6639. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6640. const cb = new Vector3(), ab = new Vector3();
  6641. // indexed elements
  6642. if ( index ) {
  6643. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6644. const vA = index.getX( i + 0 );
  6645. const vB = index.getX( i + 1 );
  6646. const vC = index.getX( i + 2 );
  6647. pA.fromBufferAttribute( positionAttribute, vA );
  6648. pB.fromBufferAttribute( positionAttribute, vB );
  6649. pC.fromBufferAttribute( positionAttribute, vC );
  6650. cb.subVectors( pC, pB );
  6651. ab.subVectors( pA, pB );
  6652. cb.cross( ab );
  6653. nA.fromBufferAttribute( normalAttribute, vA );
  6654. nB.fromBufferAttribute( normalAttribute, vB );
  6655. nC.fromBufferAttribute( normalAttribute, vC );
  6656. nA.add( cb );
  6657. nB.add( cb );
  6658. nC.add( cb );
  6659. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6660. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6661. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6662. }
  6663. } else {
  6664. // non-indexed elements (unconnected triangle soup)
  6665. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6666. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6667. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6668. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6669. cb.subVectors( pC, pB );
  6670. ab.subVectors( pA, pB );
  6671. cb.cross( ab );
  6672. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6673. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6674. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6675. }
  6676. }
  6677. this.normalizeNormals();
  6678. normalAttribute.needsUpdate = true;
  6679. }
  6680. }
  6681. normalizeNormals() {
  6682. const normals = this.attributes.normal;
  6683. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6684. _vector$8.fromBufferAttribute( normals, i );
  6685. _vector$8.normalize();
  6686. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6687. }
  6688. }
  6689. toNonIndexed() {
  6690. function convertBufferAttribute( attribute, indices ) {
  6691. const array = attribute.array;
  6692. const itemSize = attribute.itemSize;
  6693. const normalized = attribute.normalized;
  6694. const array2 = new array.constructor( indices.length * itemSize );
  6695. let index = 0, index2 = 0;
  6696. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6697. if ( attribute.isInterleavedBufferAttribute ) {
  6698. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6699. } else {
  6700. index = indices[ i ] * itemSize;
  6701. }
  6702. for ( let j = 0; j < itemSize; j ++ ) {
  6703. array2[ index2 ++ ] = array[ index ++ ];
  6704. }
  6705. }
  6706. return new BufferAttribute( array2, itemSize, normalized );
  6707. }
  6708. //
  6709. if ( this.index === null ) {
  6710. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6711. return this;
  6712. }
  6713. const geometry2 = new BufferGeometry();
  6714. const indices = this.index.array;
  6715. const attributes = this.attributes;
  6716. // attributes
  6717. for ( const name in attributes ) {
  6718. const attribute = attributes[ name ];
  6719. const newAttribute = convertBufferAttribute( attribute, indices );
  6720. geometry2.setAttribute( name, newAttribute );
  6721. }
  6722. // morph attributes
  6723. const morphAttributes = this.morphAttributes;
  6724. for ( const name in morphAttributes ) {
  6725. const morphArray = [];
  6726. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6727. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6728. const attribute = morphAttribute[ i ];
  6729. const newAttribute = convertBufferAttribute( attribute, indices );
  6730. morphArray.push( newAttribute );
  6731. }
  6732. geometry2.morphAttributes[ name ] = morphArray;
  6733. }
  6734. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6735. // groups
  6736. const groups = this.groups;
  6737. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6738. const group = groups[ i ];
  6739. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6740. }
  6741. return geometry2;
  6742. }
  6743. toJSON() {
  6744. const data = {
  6745. metadata: {
  6746. version: 4.6,
  6747. type: 'BufferGeometry',
  6748. generator: 'BufferGeometry.toJSON'
  6749. }
  6750. };
  6751. // standard BufferGeometry serialization
  6752. data.uuid = this.uuid;
  6753. data.type = this.type;
  6754. if ( this.name !== '' ) data.name = this.name;
  6755. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6756. if ( this.parameters !== undefined ) {
  6757. const parameters = this.parameters;
  6758. for ( const key in parameters ) {
  6759. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6760. }
  6761. return data;
  6762. }
  6763. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6764. data.data = { attributes: {} };
  6765. const index = this.index;
  6766. if ( index !== null ) {
  6767. data.data.index = {
  6768. type: index.array.constructor.name,
  6769. array: Array.prototype.slice.call( index.array )
  6770. };
  6771. }
  6772. const attributes = this.attributes;
  6773. for ( const key in attributes ) {
  6774. const attribute = attributes[ key ];
  6775. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6776. }
  6777. const morphAttributes = {};
  6778. let hasMorphAttributes = false;
  6779. for ( const key in this.morphAttributes ) {
  6780. const attributeArray = this.morphAttributes[ key ];
  6781. const array = [];
  6782. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6783. const attribute = attributeArray[ i ];
  6784. array.push( attribute.toJSON( data.data ) );
  6785. }
  6786. if ( array.length > 0 ) {
  6787. morphAttributes[ key ] = array;
  6788. hasMorphAttributes = true;
  6789. }
  6790. }
  6791. if ( hasMorphAttributes ) {
  6792. data.data.morphAttributes = morphAttributes;
  6793. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6794. }
  6795. const groups = this.groups;
  6796. if ( groups.length > 0 ) {
  6797. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6798. }
  6799. const boundingSphere = this.boundingSphere;
  6800. if ( boundingSphere !== null ) {
  6801. data.data.boundingSphere = {
  6802. center: boundingSphere.center.toArray(),
  6803. radius: boundingSphere.radius
  6804. };
  6805. }
  6806. return data;
  6807. }
  6808. clone() {
  6809. return new this.constructor().copy( this );
  6810. }
  6811. copy( source ) {
  6812. // reset
  6813. this.index = null;
  6814. this.attributes = {};
  6815. this.morphAttributes = {};
  6816. this.groups = [];
  6817. this.boundingBox = null;
  6818. this.boundingSphere = null;
  6819. // used for storing cloned, shared data
  6820. const data = {};
  6821. // name
  6822. this.name = source.name;
  6823. // index
  6824. const index = source.index;
  6825. if ( index !== null ) {
  6826. this.setIndex( index.clone( data ) );
  6827. }
  6828. // attributes
  6829. const attributes = source.attributes;
  6830. for ( const name in attributes ) {
  6831. const attribute = attributes[ name ];
  6832. this.setAttribute( name, attribute.clone( data ) );
  6833. }
  6834. // morph attributes
  6835. const morphAttributes = source.morphAttributes;
  6836. for ( const name in morphAttributes ) {
  6837. const array = [];
  6838. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6839. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6840. array.push( morphAttribute[ i ].clone( data ) );
  6841. }
  6842. this.morphAttributes[ name ] = array;
  6843. }
  6844. this.morphTargetsRelative = source.morphTargetsRelative;
  6845. // groups
  6846. const groups = source.groups;
  6847. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6848. const group = groups[ i ];
  6849. this.addGroup( group.start, group.count, group.materialIndex );
  6850. }
  6851. // bounding box
  6852. const boundingBox = source.boundingBox;
  6853. if ( boundingBox !== null ) {
  6854. this.boundingBox = boundingBox.clone();
  6855. }
  6856. // bounding sphere
  6857. const boundingSphere = source.boundingSphere;
  6858. if ( boundingSphere !== null ) {
  6859. this.boundingSphere = boundingSphere.clone();
  6860. }
  6861. // draw range
  6862. this.drawRange.start = source.drawRange.start;
  6863. this.drawRange.count = source.drawRange.count;
  6864. // user data
  6865. this.userData = source.userData;
  6866. return this;
  6867. }
  6868. dispose() {
  6869. this.dispatchEvent( { type: 'dispose' } );
  6870. }
  6871. }
  6872. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6873. const _ray$3 = /*@__PURE__*/ new Ray();
  6874. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6875. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6876. const _vA$1 = /*@__PURE__*/ new Vector3();
  6877. const _vB$1 = /*@__PURE__*/ new Vector3();
  6878. const _vC$1 = /*@__PURE__*/ new Vector3();
  6879. const _tempA = /*@__PURE__*/ new Vector3();
  6880. const _morphA = /*@__PURE__*/ new Vector3();
  6881. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6882. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6883. class Mesh extends Object3D {
  6884. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6885. super();
  6886. this.isMesh = true;
  6887. this.type = 'Mesh';
  6888. this.geometry = geometry;
  6889. this.material = material;
  6890. this.updateMorphTargets();
  6891. }
  6892. copy( source, recursive ) {
  6893. super.copy( source, recursive );
  6894. if ( source.morphTargetInfluences !== undefined ) {
  6895. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6896. }
  6897. if ( source.morphTargetDictionary !== undefined ) {
  6898. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6899. }
  6900. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6901. this.geometry = source.geometry;
  6902. return this;
  6903. }
  6904. updateMorphTargets() {
  6905. const geometry = this.geometry;
  6906. const morphAttributes = geometry.morphAttributes;
  6907. const keys = Object.keys( morphAttributes );
  6908. if ( keys.length > 0 ) {
  6909. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6910. if ( morphAttribute !== undefined ) {
  6911. this.morphTargetInfluences = [];
  6912. this.morphTargetDictionary = {};
  6913. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6914. const name = morphAttribute[ m ].name || String( m );
  6915. this.morphTargetInfluences.push( 0 );
  6916. this.morphTargetDictionary[ name ] = m;
  6917. }
  6918. }
  6919. }
  6920. }
  6921. getVertexPosition( index, target ) {
  6922. const geometry = this.geometry;
  6923. const position = geometry.attributes.position;
  6924. const morphPosition = geometry.morphAttributes.position;
  6925. const morphTargetsRelative = geometry.morphTargetsRelative;
  6926. target.fromBufferAttribute( position, index );
  6927. const morphInfluences = this.morphTargetInfluences;
  6928. if ( morphPosition && morphInfluences ) {
  6929. _morphA.set( 0, 0, 0 );
  6930. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6931. const influence = morphInfluences[ i ];
  6932. const morphAttribute = morphPosition[ i ];
  6933. if ( influence === 0 ) continue;
  6934. _tempA.fromBufferAttribute( morphAttribute, index );
  6935. if ( morphTargetsRelative ) {
  6936. _morphA.addScaledVector( _tempA, influence );
  6937. } else {
  6938. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6939. }
  6940. }
  6941. target.add( _morphA );
  6942. }
  6943. return target;
  6944. }
  6945. raycast( raycaster, intersects ) {
  6946. const geometry = this.geometry;
  6947. const material = this.material;
  6948. const matrixWorld = this.matrixWorld;
  6949. if ( material === undefined ) return;
  6950. // test with bounding sphere in world space
  6951. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6952. _sphere$6.copy( geometry.boundingSphere );
  6953. _sphere$6.applyMatrix4( matrixWorld );
  6954. // check distance from ray origin to bounding sphere
  6955. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6956. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6957. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6958. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6959. }
  6960. // convert ray to local space of mesh
  6961. _inverseMatrix$3.copy( matrixWorld ).invert();
  6962. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6963. // test with bounding box in local space
  6964. if ( geometry.boundingBox !== null ) {
  6965. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6966. }
  6967. // test for intersections with geometry
  6968. this._computeIntersections( raycaster, intersects, _ray$3 );
  6969. }
  6970. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6971. let intersection;
  6972. const geometry = this.geometry;
  6973. const material = this.material;
  6974. const index = geometry.index;
  6975. const position = geometry.attributes.position;
  6976. const uv = geometry.attributes.uv;
  6977. const uv1 = geometry.attributes.uv1;
  6978. const normal = geometry.attributes.normal;
  6979. const groups = geometry.groups;
  6980. const drawRange = geometry.drawRange;
  6981. if ( index !== null ) {
  6982. // indexed buffer geometry
  6983. if ( Array.isArray( material ) ) {
  6984. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6985. const group = groups[ i ];
  6986. const groupMaterial = material[ group.materialIndex ];
  6987. const start = Math.max( group.start, drawRange.start );
  6988. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6989. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6990. const a = index.getX( j );
  6991. const b = index.getX( j + 1 );
  6992. const c = index.getX( j + 2 );
  6993. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6994. if ( intersection ) {
  6995. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6996. intersection.face.materialIndex = group.materialIndex;
  6997. intersects.push( intersection );
  6998. }
  6999. }
  7000. }
  7001. } else {
  7002. const start = Math.max( 0, drawRange.start );
  7003. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7004. for ( let i = start, il = end; i < il; i += 3 ) {
  7005. const a = index.getX( i );
  7006. const b = index.getX( i + 1 );
  7007. const c = index.getX( i + 2 );
  7008. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7009. if ( intersection ) {
  7010. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7011. intersects.push( intersection );
  7012. }
  7013. }
  7014. }
  7015. } else if ( position !== undefined ) {
  7016. // non-indexed buffer geometry
  7017. if ( Array.isArray( material ) ) {
  7018. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7019. const group = groups[ i ];
  7020. const groupMaterial = material[ group.materialIndex ];
  7021. const start = Math.max( group.start, drawRange.start );
  7022. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7023. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7024. const a = j;
  7025. const b = j + 1;
  7026. const c = j + 2;
  7027. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7028. if ( intersection ) {
  7029. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7030. intersection.face.materialIndex = group.materialIndex;
  7031. intersects.push( intersection );
  7032. }
  7033. }
  7034. }
  7035. } else {
  7036. const start = Math.max( 0, drawRange.start );
  7037. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7038. for ( let i = start, il = end; i < il; i += 3 ) {
  7039. const a = i;
  7040. const b = i + 1;
  7041. const c = i + 2;
  7042. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7043. if ( intersection ) {
  7044. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7045. intersects.push( intersection );
  7046. }
  7047. }
  7048. }
  7049. }
  7050. }
  7051. }
  7052. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7053. let intersect;
  7054. if ( material.side === BackSide ) {
  7055. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7056. } else {
  7057. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7058. }
  7059. if ( intersect === null ) return null;
  7060. _intersectionPointWorld.copy( point );
  7061. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7062. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7063. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7064. return {
  7065. distance: distance,
  7066. point: _intersectionPointWorld.clone(),
  7067. object: object
  7068. };
  7069. }
  7070. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7071. object.getVertexPosition( a, _vA$1 );
  7072. object.getVertexPosition( b, _vB$1 );
  7073. object.getVertexPosition( c, _vC$1 );
  7074. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7075. if ( intersection ) {
  7076. const barycoord = new Vector3();
  7077. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7078. if ( uv ) {
  7079. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7080. }
  7081. if ( uv1 ) {
  7082. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7083. }
  7084. if ( normal ) {
  7085. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7086. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7087. intersection.normal.multiplyScalar( - 1 );
  7088. }
  7089. }
  7090. const face = {
  7091. a: a,
  7092. b: b,
  7093. c: c,
  7094. normal: new Vector3(),
  7095. materialIndex: 0
  7096. };
  7097. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7098. intersection.face = face;
  7099. intersection.barycoord = barycoord;
  7100. }
  7101. return intersection;
  7102. }
  7103. class BoxGeometry extends BufferGeometry {
  7104. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7105. super();
  7106. this.type = 'BoxGeometry';
  7107. this.parameters = {
  7108. width: width,
  7109. height: height,
  7110. depth: depth,
  7111. widthSegments: widthSegments,
  7112. heightSegments: heightSegments,
  7113. depthSegments: depthSegments
  7114. };
  7115. const scope = this;
  7116. // segments
  7117. widthSegments = Math.floor( widthSegments );
  7118. heightSegments = Math.floor( heightSegments );
  7119. depthSegments = Math.floor( depthSegments );
  7120. // buffers
  7121. const indices = [];
  7122. const vertices = [];
  7123. const normals = [];
  7124. const uvs = [];
  7125. // helper variables
  7126. let numberOfVertices = 0;
  7127. let groupStart = 0;
  7128. // build each side of the box geometry
  7129. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7130. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7131. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7132. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7133. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7134. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7135. // build geometry
  7136. this.setIndex( indices );
  7137. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7138. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7139. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7140. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7141. const segmentWidth = width / gridX;
  7142. const segmentHeight = height / gridY;
  7143. const widthHalf = width / 2;
  7144. const heightHalf = height / 2;
  7145. const depthHalf = depth / 2;
  7146. const gridX1 = gridX + 1;
  7147. const gridY1 = gridY + 1;
  7148. let vertexCounter = 0;
  7149. let groupCount = 0;
  7150. const vector = new Vector3();
  7151. // generate vertices, normals and uvs
  7152. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7153. const y = iy * segmentHeight - heightHalf;
  7154. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7155. const x = ix * segmentWidth - widthHalf;
  7156. // set values to correct vector component
  7157. vector[ u ] = x * udir;
  7158. vector[ v ] = y * vdir;
  7159. vector[ w ] = depthHalf;
  7160. // now apply vector to vertex buffer
  7161. vertices.push( vector.x, vector.y, vector.z );
  7162. // set values to correct vector component
  7163. vector[ u ] = 0;
  7164. vector[ v ] = 0;
  7165. vector[ w ] = depth > 0 ? 1 : - 1;
  7166. // now apply vector to normal buffer
  7167. normals.push( vector.x, vector.y, vector.z );
  7168. // uvs
  7169. uvs.push( ix / gridX );
  7170. uvs.push( 1 - ( iy / gridY ) );
  7171. // counters
  7172. vertexCounter += 1;
  7173. }
  7174. }
  7175. // indices
  7176. // 1. you need three indices to draw a single face
  7177. // 2. a single segment consists of two faces
  7178. // 3. so we need to generate six (2*3) indices per segment
  7179. for ( let iy = 0; iy < gridY; iy ++ ) {
  7180. for ( let ix = 0; ix < gridX; ix ++ ) {
  7181. const a = numberOfVertices + ix + gridX1 * iy;
  7182. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7183. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7184. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7185. // faces
  7186. indices.push( a, b, d );
  7187. indices.push( b, c, d );
  7188. // increase counter
  7189. groupCount += 6;
  7190. }
  7191. }
  7192. // add a group to the geometry. this will ensure multi material support
  7193. scope.addGroup( groupStart, groupCount, materialIndex );
  7194. // calculate new start value for groups
  7195. groupStart += groupCount;
  7196. // update total number of vertices
  7197. numberOfVertices += vertexCounter;
  7198. }
  7199. }
  7200. copy( source ) {
  7201. super.copy( source );
  7202. this.parameters = Object.assign( {}, source.parameters );
  7203. return this;
  7204. }
  7205. static fromJSON( data ) {
  7206. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7207. }
  7208. }
  7209. /**
  7210. * Uniform Utilities
  7211. */
  7212. function cloneUniforms( src ) {
  7213. const dst = {};
  7214. for ( const u in src ) {
  7215. dst[ u ] = {};
  7216. for ( const p in src[ u ] ) {
  7217. const property = src[ u ][ p ];
  7218. if ( property && ( property.isColor ||
  7219. property.isMatrix3 || property.isMatrix4 ||
  7220. property.isVector2 || property.isVector3 || property.isVector4 ||
  7221. property.isTexture || property.isQuaternion ) ) {
  7222. if ( property.isRenderTargetTexture ) {
  7223. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7224. dst[ u ][ p ] = null;
  7225. } else {
  7226. dst[ u ][ p ] = property.clone();
  7227. }
  7228. } else if ( Array.isArray( property ) ) {
  7229. dst[ u ][ p ] = property.slice();
  7230. } else {
  7231. dst[ u ][ p ] = property;
  7232. }
  7233. }
  7234. }
  7235. return dst;
  7236. }
  7237. function cloneUniformsGroups( src ) {
  7238. const dst = [];
  7239. for ( let u = 0; u < src.length; u ++ ) {
  7240. dst.push( src[ u ].clone() );
  7241. }
  7242. return dst;
  7243. }
  7244. var default_vertex = /* glsl */`
  7245. void main() {
  7246. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7247. }
  7248. `;
  7249. var default_fragment = /* glsl */`
  7250. void main() {
  7251. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7252. }
  7253. `;
  7254. class ShaderMaterial extends Material {
  7255. constructor( parameters ) {
  7256. super();
  7257. this.isShaderMaterial = true;
  7258. this.type = 'ShaderMaterial';
  7259. this.defines = {};
  7260. this.uniforms = {};
  7261. this.uniformsGroups = [];
  7262. this.vertexShader = default_vertex;
  7263. this.fragmentShader = default_fragment;
  7264. this.linewidth = 1;
  7265. this.wireframe = false;
  7266. this.wireframeLinewidth = 1;
  7267. this.fog = false; // set to use scene fog
  7268. this.lights = false; // set to use scene lights
  7269. this.clipping = false; // set to use user-defined clipping planes
  7270. this.forceSinglePass = true;
  7271. this.extensions = {
  7272. clipCullDistance: false, // set to use vertex shader clipping
  7273. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7274. };
  7275. // When rendered geometry doesn't include these attributes but the material does,
  7276. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7277. this.defaultAttributeValues = {
  7278. 'color': [ 1, 1, 1 ],
  7279. 'uv': [ 0, 0 ],
  7280. 'uv1': [ 0, 0 ]
  7281. };
  7282. this.index0AttributeName = undefined;
  7283. this.uniformsNeedUpdate = false;
  7284. this.glslVersion = null;
  7285. if ( parameters !== undefined ) {
  7286. this.setValues( parameters );
  7287. }
  7288. }
  7289. copy( source ) {
  7290. super.copy( source );
  7291. this.fragmentShader = source.fragmentShader;
  7292. this.vertexShader = source.vertexShader;
  7293. this.uniforms = cloneUniforms( source.uniforms );
  7294. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7295. this.defines = Object.assign( {}, source.defines );
  7296. this.wireframe = source.wireframe;
  7297. this.wireframeLinewidth = source.wireframeLinewidth;
  7298. this.fog = source.fog;
  7299. this.lights = source.lights;
  7300. this.clipping = source.clipping;
  7301. this.extensions = Object.assign( {}, source.extensions );
  7302. this.glslVersion = source.glslVersion;
  7303. return this;
  7304. }
  7305. toJSON( meta ) {
  7306. const data = super.toJSON( meta );
  7307. data.glslVersion = this.glslVersion;
  7308. data.uniforms = {};
  7309. for ( const name in this.uniforms ) {
  7310. const uniform = this.uniforms[ name ];
  7311. const value = uniform.value;
  7312. if ( value && value.isTexture ) {
  7313. data.uniforms[ name ] = {
  7314. type: 't',
  7315. value: value.toJSON( meta ).uuid
  7316. };
  7317. } else if ( value && value.isColor ) {
  7318. data.uniforms[ name ] = {
  7319. type: 'c',
  7320. value: value.getHex()
  7321. };
  7322. } else if ( value && value.isVector2 ) {
  7323. data.uniforms[ name ] = {
  7324. type: 'v2',
  7325. value: value.toArray()
  7326. };
  7327. } else if ( value && value.isVector3 ) {
  7328. data.uniforms[ name ] = {
  7329. type: 'v3',
  7330. value: value.toArray()
  7331. };
  7332. } else if ( value && value.isVector4 ) {
  7333. data.uniforms[ name ] = {
  7334. type: 'v4',
  7335. value: value.toArray()
  7336. };
  7337. } else if ( value && value.isMatrix3 ) {
  7338. data.uniforms[ name ] = {
  7339. type: 'm3',
  7340. value: value.toArray()
  7341. };
  7342. } else if ( value && value.isMatrix4 ) {
  7343. data.uniforms[ name ] = {
  7344. type: 'm4',
  7345. value: value.toArray()
  7346. };
  7347. } else {
  7348. data.uniforms[ name ] = {
  7349. value: value
  7350. };
  7351. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7352. }
  7353. }
  7354. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7355. data.vertexShader = this.vertexShader;
  7356. data.fragmentShader = this.fragmentShader;
  7357. data.lights = this.lights;
  7358. data.clipping = this.clipping;
  7359. const extensions = {};
  7360. for ( const key in this.extensions ) {
  7361. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7362. }
  7363. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7364. return data;
  7365. }
  7366. }
  7367. class Camera extends Object3D {
  7368. constructor() {
  7369. super();
  7370. this.isCamera = true;
  7371. this.type = 'Camera';
  7372. this.matrixWorldInverse = new Matrix4();
  7373. this.projectionMatrix = new Matrix4();
  7374. this.projectionMatrixInverse = new Matrix4();
  7375. this.coordinateSystem = WebGLCoordinateSystem;
  7376. }
  7377. copy( source, recursive ) {
  7378. super.copy( source, recursive );
  7379. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7380. this.projectionMatrix.copy( source.projectionMatrix );
  7381. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7382. this.coordinateSystem = source.coordinateSystem;
  7383. return this;
  7384. }
  7385. getWorldDirection( target ) {
  7386. return super.getWorldDirection( target ).negate();
  7387. }
  7388. updateMatrixWorld( force ) {
  7389. super.updateMatrixWorld( force );
  7390. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7391. }
  7392. updateWorldMatrix( updateParents, updateChildren ) {
  7393. super.updateWorldMatrix( updateParents, updateChildren );
  7394. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7395. }
  7396. clone() {
  7397. return new this.constructor().copy( this );
  7398. }
  7399. }
  7400. const _v3$1 = /*@__PURE__*/ new Vector3();
  7401. const _minTarget = /*@__PURE__*/ new Vector2();
  7402. const _maxTarget = /*@__PURE__*/ new Vector2();
  7403. class PerspectiveCamera extends Camera {
  7404. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7405. super();
  7406. this.isPerspectiveCamera = true;
  7407. this.type = 'PerspectiveCamera';
  7408. this.fov = fov;
  7409. this.zoom = 1;
  7410. this.near = near;
  7411. this.far = far;
  7412. this.focus = 10;
  7413. this.aspect = aspect;
  7414. this.view = null;
  7415. this.filmGauge = 35; // width of the film (default in millimeters)
  7416. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7417. this.updateProjectionMatrix();
  7418. }
  7419. copy( source, recursive ) {
  7420. super.copy( source, recursive );
  7421. this.fov = source.fov;
  7422. this.zoom = source.zoom;
  7423. this.near = source.near;
  7424. this.far = source.far;
  7425. this.focus = source.focus;
  7426. this.aspect = source.aspect;
  7427. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7428. this.filmGauge = source.filmGauge;
  7429. this.filmOffset = source.filmOffset;
  7430. return this;
  7431. }
  7432. /**
  7433. * Sets the FOV by focal length in respect to the current .filmGauge.
  7434. *
  7435. * The default film gauge is 35, so that the focal length can be specified for
  7436. * a 35mm (full frame) camera.
  7437. *
  7438. * Values for focal length and film gauge must have the same unit.
  7439. */
  7440. setFocalLength( focalLength ) {
  7441. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7442. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7443. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7444. this.updateProjectionMatrix();
  7445. }
  7446. /**
  7447. * Calculates the focal length from the current .fov and .filmGauge.
  7448. */
  7449. getFocalLength() {
  7450. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7451. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7452. }
  7453. getEffectiveFOV() {
  7454. return RAD2DEG * 2 * Math.atan(
  7455. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7456. }
  7457. getFilmWidth() {
  7458. // film not completely covered in portrait format (aspect < 1)
  7459. return this.filmGauge * Math.min( this.aspect, 1 );
  7460. }
  7461. getFilmHeight() {
  7462. // film not completely covered in landscape format (aspect > 1)
  7463. return this.filmGauge / Math.max( this.aspect, 1 );
  7464. }
  7465. /**
  7466. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7467. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7468. */
  7469. getViewBounds( distance, minTarget, maxTarget ) {
  7470. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7471. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7472. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7473. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7474. }
  7475. /**
  7476. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7477. * Copies the result into the target Vector2, where x is width and y is height.
  7478. */
  7479. getViewSize( distance, target ) {
  7480. this.getViewBounds( distance, _minTarget, _maxTarget );
  7481. return target.subVectors( _maxTarget, _minTarget );
  7482. }
  7483. /**
  7484. * Sets an offset in a larger frustum. This is useful for multi-window or
  7485. * multi-monitor/multi-machine setups.
  7486. *
  7487. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7488. * the monitors are in grid like this
  7489. *
  7490. * +---+---+---+
  7491. * | A | B | C |
  7492. * +---+---+---+
  7493. * | D | E | F |
  7494. * +---+---+---+
  7495. *
  7496. * then for each monitor you would call it like this
  7497. *
  7498. * const w = 1920;
  7499. * const h = 1080;
  7500. * const fullWidth = w * 3;
  7501. * const fullHeight = h * 2;
  7502. *
  7503. * --A--
  7504. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7505. * --B--
  7506. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7507. * --C--
  7508. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7509. * --D--
  7510. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7511. * --E--
  7512. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7513. * --F--
  7514. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7515. *
  7516. * Note there is no reason monitors have to be the same size or in a grid.
  7517. */
  7518. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7519. this.aspect = fullWidth / fullHeight;
  7520. if ( this.view === null ) {
  7521. this.view = {
  7522. enabled: true,
  7523. fullWidth: 1,
  7524. fullHeight: 1,
  7525. offsetX: 0,
  7526. offsetY: 0,
  7527. width: 1,
  7528. height: 1
  7529. };
  7530. }
  7531. this.view.enabled = true;
  7532. this.view.fullWidth = fullWidth;
  7533. this.view.fullHeight = fullHeight;
  7534. this.view.offsetX = x;
  7535. this.view.offsetY = y;
  7536. this.view.width = width;
  7537. this.view.height = height;
  7538. this.updateProjectionMatrix();
  7539. }
  7540. clearViewOffset() {
  7541. if ( this.view !== null ) {
  7542. this.view.enabled = false;
  7543. }
  7544. this.updateProjectionMatrix();
  7545. }
  7546. updateProjectionMatrix() {
  7547. const near = this.near;
  7548. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7549. let height = 2 * top;
  7550. let width = this.aspect * height;
  7551. let left = - 0.5 * width;
  7552. const view = this.view;
  7553. if ( this.view !== null && this.view.enabled ) {
  7554. const fullWidth = view.fullWidth,
  7555. fullHeight = view.fullHeight;
  7556. left += view.offsetX * width / fullWidth;
  7557. top -= view.offsetY * height / fullHeight;
  7558. width *= view.width / fullWidth;
  7559. height *= view.height / fullHeight;
  7560. }
  7561. const skew = this.filmOffset;
  7562. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7563. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7564. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7565. }
  7566. toJSON( meta ) {
  7567. const data = super.toJSON( meta );
  7568. data.object.fov = this.fov;
  7569. data.object.zoom = this.zoom;
  7570. data.object.near = this.near;
  7571. data.object.far = this.far;
  7572. data.object.focus = this.focus;
  7573. data.object.aspect = this.aspect;
  7574. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7575. data.object.filmGauge = this.filmGauge;
  7576. data.object.filmOffset = this.filmOffset;
  7577. return data;
  7578. }
  7579. }
  7580. const fov = - 90; // negative fov is not an error
  7581. const aspect = 1;
  7582. class CubeCamera extends Object3D {
  7583. constructor( near, far, renderTarget ) {
  7584. super();
  7585. this.type = 'CubeCamera';
  7586. this.renderTarget = renderTarget;
  7587. this.coordinateSystem = null;
  7588. this.activeMipmapLevel = 0;
  7589. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7590. cameraPX.layers = this.layers;
  7591. this.add( cameraPX );
  7592. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7593. cameraNX.layers = this.layers;
  7594. this.add( cameraNX );
  7595. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7596. cameraPY.layers = this.layers;
  7597. this.add( cameraPY );
  7598. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7599. cameraNY.layers = this.layers;
  7600. this.add( cameraNY );
  7601. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7602. cameraPZ.layers = this.layers;
  7603. this.add( cameraPZ );
  7604. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7605. cameraNZ.layers = this.layers;
  7606. this.add( cameraNZ );
  7607. }
  7608. updateCoordinateSystem() {
  7609. const coordinateSystem = this.coordinateSystem;
  7610. const cameras = this.children.concat();
  7611. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7612. for ( const camera of cameras ) this.remove( camera );
  7613. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7614. cameraPX.up.set( 0, 1, 0 );
  7615. cameraPX.lookAt( 1, 0, 0 );
  7616. cameraNX.up.set( 0, 1, 0 );
  7617. cameraNX.lookAt( - 1, 0, 0 );
  7618. cameraPY.up.set( 0, 0, - 1 );
  7619. cameraPY.lookAt( 0, 1, 0 );
  7620. cameraNY.up.set( 0, 0, 1 );
  7621. cameraNY.lookAt( 0, - 1, 0 );
  7622. cameraPZ.up.set( 0, 1, 0 );
  7623. cameraPZ.lookAt( 0, 0, 1 );
  7624. cameraNZ.up.set( 0, 1, 0 );
  7625. cameraNZ.lookAt( 0, 0, - 1 );
  7626. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7627. cameraPX.up.set( 0, - 1, 0 );
  7628. cameraPX.lookAt( - 1, 0, 0 );
  7629. cameraNX.up.set( 0, - 1, 0 );
  7630. cameraNX.lookAt( 1, 0, 0 );
  7631. cameraPY.up.set( 0, 0, 1 );
  7632. cameraPY.lookAt( 0, 1, 0 );
  7633. cameraNY.up.set( 0, 0, - 1 );
  7634. cameraNY.lookAt( 0, - 1, 0 );
  7635. cameraPZ.up.set( 0, - 1, 0 );
  7636. cameraPZ.lookAt( 0, 0, 1 );
  7637. cameraNZ.up.set( 0, - 1, 0 );
  7638. cameraNZ.lookAt( 0, 0, - 1 );
  7639. } else {
  7640. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7641. }
  7642. for ( const camera of cameras ) {
  7643. this.add( camera );
  7644. camera.updateMatrixWorld();
  7645. }
  7646. }
  7647. update( renderer, scene ) {
  7648. if ( this.parent === null ) this.updateMatrixWorld();
  7649. const { renderTarget, activeMipmapLevel } = this;
  7650. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7651. this.coordinateSystem = renderer.coordinateSystem;
  7652. this.updateCoordinateSystem();
  7653. }
  7654. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7655. const currentRenderTarget = renderer.getRenderTarget();
  7656. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7657. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7658. const currentXrEnabled = renderer.xr.enabled;
  7659. renderer.xr.enabled = false;
  7660. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7661. renderTarget.texture.generateMipmaps = false;
  7662. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7663. renderer.render( scene, cameraPX );
  7664. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7665. renderer.render( scene, cameraNX );
  7666. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7667. renderer.render( scene, cameraPY );
  7668. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7669. renderer.render( scene, cameraNY );
  7670. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7671. renderer.render( scene, cameraPZ );
  7672. // mipmaps are generated during the last call of render()
  7673. // at this point, all sides of the cube render target are defined
  7674. renderTarget.texture.generateMipmaps = generateMipmaps;
  7675. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7676. renderer.render( scene, cameraNZ );
  7677. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7678. renderer.xr.enabled = currentXrEnabled;
  7679. renderTarget.texture.needsPMREMUpdate = true;
  7680. }
  7681. }
  7682. class CubeTexture extends Texture {
  7683. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7684. images = images !== undefined ? images : [];
  7685. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7686. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7687. this.isCubeTexture = true;
  7688. this.flipY = false;
  7689. }
  7690. get images() {
  7691. return this.image;
  7692. }
  7693. set images( value ) {
  7694. this.image = value;
  7695. }
  7696. }
  7697. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7698. constructor( size = 1, options = {} ) {
  7699. super( size, size, options );
  7700. this.isWebGLCubeRenderTarget = true;
  7701. const image = { width: size, height: size, depth: 1 };
  7702. const images = [ image, image, image, image, image, image ];
  7703. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7704. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7705. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7706. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7707. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7708. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7709. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7710. this.texture.isRenderTargetTexture = true;
  7711. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7712. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7713. }
  7714. fromEquirectangularTexture( renderer, texture ) {
  7715. this.texture.type = texture.type;
  7716. this.texture.colorSpace = texture.colorSpace;
  7717. this.texture.generateMipmaps = texture.generateMipmaps;
  7718. this.texture.minFilter = texture.minFilter;
  7719. this.texture.magFilter = texture.magFilter;
  7720. const shader = {
  7721. uniforms: {
  7722. tEquirect: { value: null },
  7723. },
  7724. vertexShader: /* glsl */`
  7725. varying vec3 vWorldDirection;
  7726. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7727. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7728. }
  7729. void main() {
  7730. vWorldDirection = transformDirection( position, modelMatrix );
  7731. #include <begin_vertex>
  7732. #include <project_vertex>
  7733. }
  7734. `,
  7735. fragmentShader: /* glsl */`
  7736. uniform sampler2D tEquirect;
  7737. varying vec3 vWorldDirection;
  7738. #include <common>
  7739. void main() {
  7740. vec3 direction = normalize( vWorldDirection );
  7741. vec2 sampleUV = equirectUv( direction );
  7742. gl_FragColor = texture2D( tEquirect, sampleUV );
  7743. }
  7744. `
  7745. };
  7746. const geometry = new BoxGeometry( 5, 5, 5 );
  7747. const material = new ShaderMaterial( {
  7748. name: 'CubemapFromEquirect',
  7749. uniforms: cloneUniforms( shader.uniforms ),
  7750. vertexShader: shader.vertexShader,
  7751. fragmentShader: shader.fragmentShader,
  7752. side: BackSide,
  7753. blending: NoBlending
  7754. } );
  7755. material.uniforms.tEquirect.value = texture;
  7756. const mesh = new Mesh( geometry, material );
  7757. const currentMinFilter = texture.minFilter;
  7758. // Avoid blurred poles
  7759. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7760. const camera = new CubeCamera( 1, 10, this );
  7761. camera.update( renderer, mesh );
  7762. texture.minFilter = currentMinFilter;
  7763. mesh.geometry.dispose();
  7764. mesh.material.dispose();
  7765. return this;
  7766. }
  7767. clear( renderer, color, depth, stencil ) {
  7768. const currentRenderTarget = renderer.getRenderTarget();
  7769. for ( let i = 0; i < 6; i ++ ) {
  7770. renderer.setRenderTarget( this, i );
  7771. renderer.clear( color, depth, stencil );
  7772. }
  7773. renderer.setRenderTarget( currentRenderTarget );
  7774. }
  7775. }
  7776. class FogExp2 {
  7777. constructor( color, density = 0.00025 ) {
  7778. this.isFogExp2 = true;
  7779. this.name = '';
  7780. this.color = new Color( color );
  7781. this.density = density;
  7782. }
  7783. clone() {
  7784. return new FogExp2( this.color, this.density );
  7785. }
  7786. toJSON( /* meta */ ) {
  7787. return {
  7788. type: 'FogExp2',
  7789. name: this.name,
  7790. color: this.color.getHex(),
  7791. density: this.density
  7792. };
  7793. }
  7794. }
  7795. class Fog {
  7796. constructor( color, near = 1, far = 1000 ) {
  7797. this.isFog = true;
  7798. this.name = '';
  7799. this.color = new Color( color );
  7800. this.near = near;
  7801. this.far = far;
  7802. }
  7803. clone() {
  7804. return new Fog( this.color, this.near, this.far );
  7805. }
  7806. toJSON( /* meta */ ) {
  7807. return {
  7808. type: 'Fog',
  7809. name: this.name,
  7810. color: this.color.getHex(),
  7811. near: this.near,
  7812. far: this.far
  7813. };
  7814. }
  7815. }
  7816. class Scene extends Object3D {
  7817. constructor() {
  7818. super();
  7819. this.isScene = true;
  7820. this.type = 'Scene';
  7821. this.background = null;
  7822. this.environment = null;
  7823. this.fog = null;
  7824. this.backgroundBlurriness = 0;
  7825. this.backgroundIntensity = 1;
  7826. this.backgroundRotation = new Euler();
  7827. this.environmentIntensity = 1;
  7828. this.environmentRotation = new Euler();
  7829. this.overrideMaterial = null;
  7830. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7831. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7832. }
  7833. }
  7834. copy( source, recursive ) {
  7835. super.copy( source, recursive );
  7836. if ( source.background !== null ) this.background = source.background.clone();
  7837. if ( source.environment !== null ) this.environment = source.environment.clone();
  7838. if ( source.fog !== null ) this.fog = source.fog.clone();
  7839. this.backgroundBlurriness = source.backgroundBlurriness;
  7840. this.backgroundIntensity = source.backgroundIntensity;
  7841. this.backgroundRotation.copy( source.backgroundRotation );
  7842. this.environmentIntensity = source.environmentIntensity;
  7843. this.environmentRotation.copy( source.environmentRotation );
  7844. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7845. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7846. return this;
  7847. }
  7848. toJSON( meta ) {
  7849. const data = super.toJSON( meta );
  7850. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7851. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7852. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7853. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7854. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7855. data.object.environmentRotation = this.environmentRotation.toArray();
  7856. return data;
  7857. }
  7858. }
  7859. class InterleavedBuffer {
  7860. constructor( array, stride ) {
  7861. this.isInterleavedBuffer = true;
  7862. this.array = array;
  7863. this.stride = stride;
  7864. this.count = array !== undefined ? array.length / stride : 0;
  7865. this.usage = StaticDrawUsage;
  7866. this.updateRanges = [];
  7867. this.version = 0;
  7868. this.uuid = generateUUID();
  7869. }
  7870. onUploadCallback() {}
  7871. set needsUpdate( value ) {
  7872. if ( value === true ) this.version ++;
  7873. }
  7874. setUsage( value ) {
  7875. this.usage = value;
  7876. return this;
  7877. }
  7878. addUpdateRange( start, count ) {
  7879. this.updateRanges.push( { start, count } );
  7880. }
  7881. clearUpdateRanges() {
  7882. this.updateRanges.length = 0;
  7883. }
  7884. copy( source ) {
  7885. this.array = new source.array.constructor( source.array );
  7886. this.count = source.count;
  7887. this.stride = source.stride;
  7888. this.usage = source.usage;
  7889. return this;
  7890. }
  7891. copyAt( index1, attribute, index2 ) {
  7892. index1 *= this.stride;
  7893. index2 *= attribute.stride;
  7894. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7895. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7896. }
  7897. return this;
  7898. }
  7899. set( value, offset = 0 ) {
  7900. this.array.set( value, offset );
  7901. return this;
  7902. }
  7903. clone( data ) {
  7904. if ( data.arrayBuffers === undefined ) {
  7905. data.arrayBuffers = {};
  7906. }
  7907. if ( this.array.buffer._uuid === undefined ) {
  7908. this.array.buffer._uuid = generateUUID();
  7909. }
  7910. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7911. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7912. }
  7913. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7914. const ib = new this.constructor( array, this.stride );
  7915. ib.setUsage( this.usage );
  7916. return ib;
  7917. }
  7918. onUpload( callback ) {
  7919. this.onUploadCallback = callback;
  7920. return this;
  7921. }
  7922. toJSON( data ) {
  7923. if ( data.arrayBuffers === undefined ) {
  7924. data.arrayBuffers = {};
  7925. }
  7926. // generate UUID for array buffer if necessary
  7927. if ( this.array.buffer._uuid === undefined ) {
  7928. this.array.buffer._uuid = generateUUID();
  7929. }
  7930. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7931. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7932. }
  7933. //
  7934. return {
  7935. uuid: this.uuid,
  7936. buffer: this.array.buffer._uuid,
  7937. type: this.array.constructor.name,
  7938. stride: this.stride
  7939. };
  7940. }
  7941. }
  7942. const _vector$7 = /*@__PURE__*/ new Vector3();
  7943. class InterleavedBufferAttribute {
  7944. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7945. this.isInterleavedBufferAttribute = true;
  7946. this.name = '';
  7947. this.data = interleavedBuffer;
  7948. this.itemSize = itemSize;
  7949. this.offset = offset;
  7950. this.normalized = normalized;
  7951. }
  7952. get count() {
  7953. return this.data.count;
  7954. }
  7955. get array() {
  7956. return this.data.array;
  7957. }
  7958. set needsUpdate( value ) {
  7959. this.data.needsUpdate = value;
  7960. }
  7961. applyMatrix4( m ) {
  7962. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7963. _vector$7.fromBufferAttribute( this, i );
  7964. _vector$7.applyMatrix4( m );
  7965. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7966. }
  7967. return this;
  7968. }
  7969. applyNormalMatrix( m ) {
  7970. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7971. _vector$7.fromBufferAttribute( this, i );
  7972. _vector$7.applyNormalMatrix( m );
  7973. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7974. }
  7975. return this;
  7976. }
  7977. transformDirection( m ) {
  7978. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7979. _vector$7.fromBufferAttribute( this, i );
  7980. _vector$7.transformDirection( m );
  7981. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7982. }
  7983. return this;
  7984. }
  7985. getComponent( index, component ) {
  7986. let value = this.array[ index * this.data.stride + this.offset + component ];
  7987. if ( this.normalized ) value = denormalize( value, this.array );
  7988. return value;
  7989. }
  7990. setComponent( index, component, value ) {
  7991. if ( this.normalized ) value = normalize$1( value, this.array );
  7992. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  7993. return this;
  7994. }
  7995. setX( index, x ) {
  7996. if ( this.normalized ) x = normalize$1( x, this.array );
  7997. this.data.array[ index * this.data.stride + this.offset ] = x;
  7998. return this;
  7999. }
  8000. setY( index, y ) {
  8001. if ( this.normalized ) y = normalize$1( y, this.array );
  8002. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8003. return this;
  8004. }
  8005. setZ( index, z ) {
  8006. if ( this.normalized ) z = normalize$1( z, this.array );
  8007. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8008. return this;
  8009. }
  8010. setW( index, w ) {
  8011. if ( this.normalized ) w = normalize$1( w, this.array );
  8012. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8013. return this;
  8014. }
  8015. getX( index ) {
  8016. let x = this.data.array[ index * this.data.stride + this.offset ];
  8017. if ( this.normalized ) x = denormalize( x, this.array );
  8018. return x;
  8019. }
  8020. getY( index ) {
  8021. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8022. if ( this.normalized ) y = denormalize( y, this.array );
  8023. return y;
  8024. }
  8025. getZ( index ) {
  8026. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8027. if ( this.normalized ) z = denormalize( z, this.array );
  8028. return z;
  8029. }
  8030. getW( index ) {
  8031. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8032. if ( this.normalized ) w = denormalize( w, this.array );
  8033. return w;
  8034. }
  8035. setXY( index, x, y ) {
  8036. index = index * this.data.stride + this.offset;
  8037. if ( this.normalized ) {
  8038. x = normalize$1( x, this.array );
  8039. y = normalize$1( y, this.array );
  8040. }
  8041. this.data.array[ index + 0 ] = x;
  8042. this.data.array[ index + 1 ] = y;
  8043. return this;
  8044. }
  8045. setXYZ( index, x, y, z ) {
  8046. index = index * this.data.stride + this.offset;
  8047. if ( this.normalized ) {
  8048. x = normalize$1( x, this.array );
  8049. y = normalize$1( y, this.array );
  8050. z = normalize$1( z, this.array );
  8051. }
  8052. this.data.array[ index + 0 ] = x;
  8053. this.data.array[ index + 1 ] = y;
  8054. this.data.array[ index + 2 ] = z;
  8055. return this;
  8056. }
  8057. setXYZW( index, x, y, z, w ) {
  8058. index = index * this.data.stride + this.offset;
  8059. if ( this.normalized ) {
  8060. x = normalize$1( x, this.array );
  8061. y = normalize$1( y, this.array );
  8062. z = normalize$1( z, this.array );
  8063. w = normalize$1( w, this.array );
  8064. }
  8065. this.data.array[ index + 0 ] = x;
  8066. this.data.array[ index + 1 ] = y;
  8067. this.data.array[ index + 2 ] = z;
  8068. this.data.array[ index + 3 ] = w;
  8069. return this;
  8070. }
  8071. clone( data ) {
  8072. if ( data === undefined ) {
  8073. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8074. const array = [];
  8075. for ( let i = 0; i < this.count; i ++ ) {
  8076. const index = i * this.data.stride + this.offset;
  8077. for ( let j = 0; j < this.itemSize; j ++ ) {
  8078. array.push( this.data.array[ index + j ] );
  8079. }
  8080. }
  8081. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8082. } else {
  8083. if ( data.interleavedBuffers === undefined ) {
  8084. data.interleavedBuffers = {};
  8085. }
  8086. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8087. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8088. }
  8089. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8090. }
  8091. }
  8092. toJSON( data ) {
  8093. if ( data === undefined ) {
  8094. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8095. const array = [];
  8096. for ( let i = 0; i < this.count; i ++ ) {
  8097. const index = i * this.data.stride + this.offset;
  8098. for ( let j = 0; j < this.itemSize; j ++ ) {
  8099. array.push( this.data.array[ index + j ] );
  8100. }
  8101. }
  8102. // de-interleave data and save it as an ordinary buffer attribute for now
  8103. return {
  8104. itemSize: this.itemSize,
  8105. type: this.array.constructor.name,
  8106. array: array,
  8107. normalized: this.normalized
  8108. };
  8109. } else {
  8110. // save as true interleaved attribute
  8111. if ( data.interleavedBuffers === undefined ) {
  8112. data.interleavedBuffers = {};
  8113. }
  8114. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8115. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8116. }
  8117. return {
  8118. isInterleavedBufferAttribute: true,
  8119. itemSize: this.itemSize,
  8120. data: this.data.uuid,
  8121. offset: this.offset,
  8122. normalized: this.normalized
  8123. };
  8124. }
  8125. }
  8126. }
  8127. class SpriteMaterial extends Material {
  8128. constructor( parameters ) {
  8129. super();
  8130. this.isSpriteMaterial = true;
  8131. this.type = 'SpriteMaterial';
  8132. this.color = new Color( 0xffffff );
  8133. this.map = null;
  8134. this.alphaMap = null;
  8135. this.rotation = 0;
  8136. this.sizeAttenuation = true;
  8137. this.transparent = true;
  8138. this.fog = true;
  8139. this.setValues( parameters );
  8140. }
  8141. copy( source ) {
  8142. super.copy( source );
  8143. this.color.copy( source.color );
  8144. this.map = source.map;
  8145. this.alphaMap = source.alphaMap;
  8146. this.rotation = source.rotation;
  8147. this.sizeAttenuation = source.sizeAttenuation;
  8148. this.fog = source.fog;
  8149. return this;
  8150. }
  8151. }
  8152. let _geometry$1;
  8153. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8154. const _worldScale = /*@__PURE__*/ new Vector3();
  8155. const _mvPosition = /*@__PURE__*/ new Vector3();
  8156. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8157. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8158. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8159. const _vA = /*@__PURE__*/ new Vector3();
  8160. const _vB = /*@__PURE__*/ new Vector3();
  8161. const _vC = /*@__PURE__*/ new Vector3();
  8162. const _uvA = /*@__PURE__*/ new Vector2();
  8163. const _uvB = /*@__PURE__*/ new Vector2();
  8164. const _uvC = /*@__PURE__*/ new Vector2();
  8165. class Sprite extends Object3D {
  8166. constructor( material = new SpriteMaterial() ) {
  8167. super();
  8168. this.isSprite = true;
  8169. this.type = 'Sprite';
  8170. if ( _geometry$1 === undefined ) {
  8171. _geometry$1 = new BufferGeometry();
  8172. const float32Array = new Float32Array( [
  8173. - 0.5, - 0.5, 0, 0, 0,
  8174. 0.5, - 0.5, 0, 1, 0,
  8175. 0.5, 0.5, 0, 1, 1,
  8176. - 0.5, 0.5, 0, 0, 1
  8177. ] );
  8178. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8179. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8180. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8181. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8182. }
  8183. this.geometry = _geometry$1;
  8184. this.material = material;
  8185. this.center = new Vector2( 0.5, 0.5 );
  8186. }
  8187. raycast( raycaster, intersects ) {
  8188. if ( raycaster.camera === null ) {
  8189. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8190. }
  8191. _worldScale.setFromMatrixScale( this.matrixWorld );
  8192. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8193. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8194. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8195. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8196. _worldScale.multiplyScalar( - _mvPosition.z );
  8197. }
  8198. const rotation = this.material.rotation;
  8199. let sin, cos;
  8200. if ( rotation !== 0 ) {
  8201. cos = Math.cos( rotation );
  8202. sin = Math.sin( rotation );
  8203. }
  8204. const center = this.center;
  8205. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8206. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8207. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8208. _uvA.set( 0, 0 );
  8209. _uvB.set( 1, 0 );
  8210. _uvC.set( 1, 1 );
  8211. // check first triangle
  8212. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8213. if ( intersect === null ) {
  8214. // check second triangle
  8215. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8216. _uvB.set( 0, 1 );
  8217. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8218. if ( intersect === null ) {
  8219. return;
  8220. }
  8221. }
  8222. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8223. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8224. intersects.push( {
  8225. distance: distance,
  8226. point: _intersectPoint.clone(),
  8227. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8228. face: null,
  8229. object: this
  8230. } );
  8231. }
  8232. copy( source, recursive ) {
  8233. super.copy( source, recursive );
  8234. if ( source.center !== undefined ) this.center.copy( source.center );
  8235. this.material = source.material;
  8236. return this;
  8237. }
  8238. }
  8239. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8240. // compute position in camera space
  8241. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8242. // to check if rotation is not zero
  8243. if ( sin !== undefined ) {
  8244. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8245. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8246. } else {
  8247. _rotatedPosition.copy( _alignedPosition );
  8248. }
  8249. vertexPosition.copy( mvPosition );
  8250. vertexPosition.x += _rotatedPosition.x;
  8251. vertexPosition.y += _rotatedPosition.y;
  8252. // transform to world space
  8253. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8254. }
  8255. const _v1$2 = /*@__PURE__*/ new Vector3();
  8256. const _v2$1 = /*@__PURE__*/ new Vector3();
  8257. class LOD extends Object3D {
  8258. constructor() {
  8259. super();
  8260. this._currentLevel = 0;
  8261. this.type = 'LOD';
  8262. Object.defineProperties( this, {
  8263. levels: {
  8264. enumerable: true,
  8265. value: []
  8266. },
  8267. isLOD: {
  8268. value: true,
  8269. }
  8270. } );
  8271. this.autoUpdate = true;
  8272. }
  8273. copy( source ) {
  8274. super.copy( source, false );
  8275. const levels = source.levels;
  8276. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8277. const level = levels[ i ];
  8278. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8279. }
  8280. this.autoUpdate = source.autoUpdate;
  8281. return this;
  8282. }
  8283. addLevel( object, distance = 0, hysteresis = 0 ) {
  8284. distance = Math.abs( distance );
  8285. const levels = this.levels;
  8286. let l;
  8287. for ( l = 0; l < levels.length; l ++ ) {
  8288. if ( distance < levels[ l ].distance ) {
  8289. break;
  8290. }
  8291. }
  8292. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8293. this.add( object );
  8294. return this;
  8295. }
  8296. removeLevel( distance ) {
  8297. const levels = this.levels;
  8298. for ( let i = 0; i < levels.length; i ++ ) {
  8299. if ( levels[ i ].distance === distance ) {
  8300. const removedElements = levels.splice( i, 1 );
  8301. this.remove( removedElements[ 0 ].object );
  8302. return true;
  8303. }
  8304. }
  8305. return false;
  8306. }
  8307. getCurrentLevel() {
  8308. return this._currentLevel;
  8309. }
  8310. getObjectForDistance( distance ) {
  8311. const levels = this.levels;
  8312. if ( levels.length > 0 ) {
  8313. let i, l;
  8314. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8315. let levelDistance = levels[ i ].distance;
  8316. if ( levels[ i ].object.visible ) {
  8317. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8318. }
  8319. if ( distance < levelDistance ) {
  8320. break;
  8321. }
  8322. }
  8323. return levels[ i - 1 ].object;
  8324. }
  8325. return null;
  8326. }
  8327. raycast( raycaster, intersects ) {
  8328. const levels = this.levels;
  8329. if ( levels.length > 0 ) {
  8330. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8331. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8332. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8333. }
  8334. }
  8335. update( camera ) {
  8336. const levels = this.levels;
  8337. if ( levels.length > 1 ) {
  8338. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8339. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8340. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8341. levels[ 0 ].object.visible = true;
  8342. let i, l;
  8343. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8344. let levelDistance = levels[ i ].distance;
  8345. if ( levels[ i ].object.visible ) {
  8346. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8347. }
  8348. if ( distance >= levelDistance ) {
  8349. levels[ i - 1 ].object.visible = false;
  8350. levels[ i ].object.visible = true;
  8351. } else {
  8352. break;
  8353. }
  8354. }
  8355. this._currentLevel = i - 1;
  8356. for ( ; i < l; i ++ ) {
  8357. levels[ i ].object.visible = false;
  8358. }
  8359. }
  8360. }
  8361. toJSON( meta ) {
  8362. const data = super.toJSON( meta );
  8363. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8364. data.object.levels = [];
  8365. const levels = this.levels;
  8366. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8367. const level = levels[ i ];
  8368. data.object.levels.push( {
  8369. object: level.object.uuid,
  8370. distance: level.distance,
  8371. hysteresis: level.hysteresis
  8372. } );
  8373. }
  8374. return data;
  8375. }
  8376. }
  8377. const _basePosition = /*@__PURE__*/ new Vector3();
  8378. const _skinIndex = /*@__PURE__*/ new Vector4();
  8379. const _skinWeight = /*@__PURE__*/ new Vector4();
  8380. const _vector3 = /*@__PURE__*/ new Vector3();
  8381. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8382. const _vertex = /*@__PURE__*/ new Vector3();
  8383. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8384. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8385. const _ray$2 = /*@__PURE__*/ new Ray();
  8386. class SkinnedMesh extends Mesh {
  8387. constructor( geometry, material ) {
  8388. super( geometry, material );
  8389. this.isSkinnedMesh = true;
  8390. this.type = 'SkinnedMesh';
  8391. this.bindMode = AttachedBindMode;
  8392. this.bindMatrix = new Matrix4();
  8393. this.bindMatrixInverse = new Matrix4();
  8394. this.boundingBox = null;
  8395. this.boundingSphere = null;
  8396. }
  8397. computeBoundingBox() {
  8398. const geometry = this.geometry;
  8399. if ( this.boundingBox === null ) {
  8400. this.boundingBox = new Box3();
  8401. }
  8402. this.boundingBox.makeEmpty();
  8403. const positionAttribute = geometry.getAttribute( 'position' );
  8404. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8405. this.getVertexPosition( i, _vertex );
  8406. this.boundingBox.expandByPoint( _vertex );
  8407. }
  8408. }
  8409. computeBoundingSphere() {
  8410. const geometry = this.geometry;
  8411. if ( this.boundingSphere === null ) {
  8412. this.boundingSphere = new Sphere();
  8413. }
  8414. this.boundingSphere.makeEmpty();
  8415. const positionAttribute = geometry.getAttribute( 'position' );
  8416. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8417. this.getVertexPosition( i, _vertex );
  8418. this.boundingSphere.expandByPoint( _vertex );
  8419. }
  8420. }
  8421. copy( source, recursive ) {
  8422. super.copy( source, recursive );
  8423. this.bindMode = source.bindMode;
  8424. this.bindMatrix.copy( source.bindMatrix );
  8425. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8426. this.skeleton = source.skeleton;
  8427. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8428. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8429. return this;
  8430. }
  8431. raycast( raycaster, intersects ) {
  8432. const material = this.material;
  8433. const matrixWorld = this.matrixWorld;
  8434. if ( material === undefined ) return;
  8435. // test with bounding sphere in world space
  8436. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8437. _sphere$5.copy( this.boundingSphere );
  8438. _sphere$5.applyMatrix4( matrixWorld );
  8439. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8440. // convert ray to local space of skinned mesh
  8441. _inverseMatrix$2.copy( matrixWorld ).invert();
  8442. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8443. // test with bounding box in local space
  8444. if ( this.boundingBox !== null ) {
  8445. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8446. }
  8447. // test for intersections with geometry
  8448. this._computeIntersections( raycaster, intersects, _ray$2 );
  8449. }
  8450. getVertexPosition( index, target ) {
  8451. super.getVertexPosition( index, target );
  8452. this.applyBoneTransform( index, target );
  8453. return target;
  8454. }
  8455. bind( skeleton, bindMatrix ) {
  8456. this.skeleton = skeleton;
  8457. if ( bindMatrix === undefined ) {
  8458. this.updateMatrixWorld( true );
  8459. this.skeleton.calculateInverses();
  8460. bindMatrix = this.matrixWorld;
  8461. }
  8462. this.bindMatrix.copy( bindMatrix );
  8463. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8464. }
  8465. pose() {
  8466. this.skeleton.pose();
  8467. }
  8468. normalizeSkinWeights() {
  8469. const vector = new Vector4();
  8470. const skinWeight = this.geometry.attributes.skinWeight;
  8471. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8472. vector.fromBufferAttribute( skinWeight, i );
  8473. const scale = 1.0 / vector.manhattanLength();
  8474. if ( scale !== Infinity ) {
  8475. vector.multiplyScalar( scale );
  8476. } else {
  8477. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8478. }
  8479. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8480. }
  8481. }
  8482. updateMatrixWorld( force ) {
  8483. super.updateMatrixWorld( force );
  8484. if ( this.bindMode === AttachedBindMode ) {
  8485. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8486. } else if ( this.bindMode === DetachedBindMode ) {
  8487. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8488. } else {
  8489. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8490. }
  8491. }
  8492. applyBoneTransform( index, vector ) {
  8493. const skeleton = this.skeleton;
  8494. const geometry = this.geometry;
  8495. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8496. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8497. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8498. vector.set( 0, 0, 0 );
  8499. for ( let i = 0; i < 4; i ++ ) {
  8500. const weight = _skinWeight.getComponent( i );
  8501. if ( weight !== 0 ) {
  8502. const boneIndex = _skinIndex.getComponent( i );
  8503. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8504. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8505. }
  8506. }
  8507. return vector.applyMatrix4( this.bindMatrixInverse );
  8508. }
  8509. }
  8510. class Bone extends Object3D {
  8511. constructor() {
  8512. super();
  8513. this.isBone = true;
  8514. this.type = 'Bone';
  8515. }
  8516. }
  8517. class DataTexture extends Texture {
  8518. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8519. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8520. this.isDataTexture = true;
  8521. this.image = { data: data, width: width, height: height };
  8522. this.generateMipmaps = false;
  8523. this.flipY = false;
  8524. this.unpackAlignment = 1;
  8525. }
  8526. }
  8527. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8528. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8529. class Skeleton {
  8530. constructor( bones = [], boneInverses = [] ) {
  8531. this.uuid = generateUUID();
  8532. this.bones = bones.slice( 0 );
  8533. this.boneInverses = boneInverses;
  8534. this.boneMatrices = null;
  8535. this.boneTexture = null;
  8536. this.init();
  8537. }
  8538. init() {
  8539. const bones = this.bones;
  8540. const boneInverses = this.boneInverses;
  8541. this.boneMatrices = new Float32Array( bones.length * 16 );
  8542. // calculate inverse bone matrices if necessary
  8543. if ( boneInverses.length === 0 ) {
  8544. this.calculateInverses();
  8545. } else {
  8546. // handle special case
  8547. if ( bones.length !== boneInverses.length ) {
  8548. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8549. this.boneInverses = [];
  8550. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8551. this.boneInverses.push( new Matrix4() );
  8552. }
  8553. }
  8554. }
  8555. }
  8556. calculateInverses() {
  8557. this.boneInverses.length = 0;
  8558. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8559. const inverse = new Matrix4();
  8560. if ( this.bones[ i ] ) {
  8561. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8562. }
  8563. this.boneInverses.push( inverse );
  8564. }
  8565. }
  8566. pose() {
  8567. // recover the bind-time world matrices
  8568. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8569. const bone = this.bones[ i ];
  8570. if ( bone ) {
  8571. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8572. }
  8573. }
  8574. // compute the local matrices, positions, rotations and scales
  8575. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8576. const bone = this.bones[ i ];
  8577. if ( bone ) {
  8578. if ( bone.parent && bone.parent.isBone ) {
  8579. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8580. bone.matrix.multiply( bone.matrixWorld );
  8581. } else {
  8582. bone.matrix.copy( bone.matrixWorld );
  8583. }
  8584. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8585. }
  8586. }
  8587. }
  8588. update() {
  8589. const bones = this.bones;
  8590. const boneInverses = this.boneInverses;
  8591. const boneMatrices = this.boneMatrices;
  8592. const boneTexture = this.boneTexture;
  8593. // flatten bone matrices to array
  8594. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8595. // compute the offset between the current and the original transform
  8596. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8597. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8598. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8599. }
  8600. if ( boneTexture !== null ) {
  8601. boneTexture.needsUpdate = true;
  8602. }
  8603. }
  8604. clone() {
  8605. return new Skeleton( this.bones, this.boneInverses );
  8606. }
  8607. computeBoneTexture() {
  8608. // layout (1 matrix = 4 pixels)
  8609. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8610. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8611. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8612. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8613. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8614. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8615. size = Math.ceil( size / 4 ) * 4;
  8616. size = Math.max( size, 4 );
  8617. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8618. boneMatrices.set( this.boneMatrices ); // copy current values
  8619. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8620. boneTexture.needsUpdate = true;
  8621. this.boneMatrices = boneMatrices;
  8622. this.boneTexture = boneTexture;
  8623. return this;
  8624. }
  8625. getBoneByName( name ) {
  8626. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8627. const bone = this.bones[ i ];
  8628. if ( bone.name === name ) {
  8629. return bone;
  8630. }
  8631. }
  8632. return undefined;
  8633. }
  8634. dispose( ) {
  8635. if ( this.boneTexture !== null ) {
  8636. this.boneTexture.dispose();
  8637. this.boneTexture = null;
  8638. }
  8639. }
  8640. fromJSON( json, bones ) {
  8641. this.uuid = json.uuid;
  8642. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8643. const uuid = json.bones[ i ];
  8644. let bone = bones[ uuid ];
  8645. if ( bone === undefined ) {
  8646. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8647. bone = new Bone();
  8648. }
  8649. this.bones.push( bone );
  8650. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8651. }
  8652. this.init();
  8653. return this;
  8654. }
  8655. toJSON() {
  8656. const data = {
  8657. metadata: {
  8658. version: 4.6,
  8659. type: 'Skeleton',
  8660. generator: 'Skeleton.toJSON'
  8661. },
  8662. bones: [],
  8663. boneInverses: []
  8664. };
  8665. data.uuid = this.uuid;
  8666. const bones = this.bones;
  8667. const boneInverses = this.boneInverses;
  8668. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8669. const bone = bones[ i ];
  8670. data.bones.push( bone.uuid );
  8671. const boneInverse = boneInverses[ i ];
  8672. data.boneInverses.push( boneInverse.toArray() );
  8673. }
  8674. return data;
  8675. }
  8676. }
  8677. class InstancedBufferAttribute extends BufferAttribute {
  8678. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8679. super( array, itemSize, normalized );
  8680. this.isInstancedBufferAttribute = true;
  8681. this.meshPerAttribute = meshPerAttribute;
  8682. }
  8683. copy( source ) {
  8684. super.copy( source );
  8685. this.meshPerAttribute = source.meshPerAttribute;
  8686. return this;
  8687. }
  8688. toJSON() {
  8689. const data = super.toJSON();
  8690. data.meshPerAttribute = this.meshPerAttribute;
  8691. data.isInstancedBufferAttribute = true;
  8692. return data;
  8693. }
  8694. }
  8695. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8696. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8697. const _instanceIntersects = [];
  8698. const _box3 = /*@__PURE__*/ new Box3();
  8699. const _identity = /*@__PURE__*/ new Matrix4();
  8700. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8701. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8702. class InstancedMesh extends Mesh {
  8703. constructor( geometry, material, count ) {
  8704. super( geometry, material );
  8705. this.isInstancedMesh = true;
  8706. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8707. this.instanceColor = null;
  8708. this.morphTexture = null;
  8709. this.count = count;
  8710. this.boundingBox = null;
  8711. this.boundingSphere = null;
  8712. for ( let i = 0; i < count; i ++ ) {
  8713. this.setMatrixAt( i, _identity );
  8714. }
  8715. }
  8716. computeBoundingBox() {
  8717. const geometry = this.geometry;
  8718. const count = this.count;
  8719. if ( this.boundingBox === null ) {
  8720. this.boundingBox = new Box3();
  8721. }
  8722. if ( geometry.boundingBox === null ) {
  8723. geometry.computeBoundingBox();
  8724. }
  8725. this.boundingBox.makeEmpty();
  8726. for ( let i = 0; i < count; i ++ ) {
  8727. this.getMatrixAt( i, _instanceLocalMatrix );
  8728. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8729. this.boundingBox.union( _box3 );
  8730. }
  8731. }
  8732. computeBoundingSphere() {
  8733. const geometry = this.geometry;
  8734. const count = this.count;
  8735. if ( this.boundingSphere === null ) {
  8736. this.boundingSphere = new Sphere();
  8737. }
  8738. if ( geometry.boundingSphere === null ) {
  8739. geometry.computeBoundingSphere();
  8740. }
  8741. this.boundingSphere.makeEmpty();
  8742. for ( let i = 0; i < count; i ++ ) {
  8743. this.getMatrixAt( i, _instanceLocalMatrix );
  8744. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8745. this.boundingSphere.union( _sphere$4 );
  8746. }
  8747. }
  8748. copy( source, recursive ) {
  8749. super.copy( source, recursive );
  8750. this.instanceMatrix.copy( source.instanceMatrix );
  8751. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8752. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8753. this.count = source.count;
  8754. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8755. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8756. return this;
  8757. }
  8758. getColorAt( index, color ) {
  8759. color.fromArray( this.instanceColor.array, index * 3 );
  8760. }
  8761. getMatrixAt( index, matrix ) {
  8762. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8763. }
  8764. getMorphAt( index, object ) {
  8765. const objectInfluences = object.morphTargetInfluences;
  8766. const array = this.morphTexture.source.data.data;
  8767. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8768. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8769. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8770. objectInfluences[ i ] = array[ dataIndex + i ];
  8771. }
  8772. }
  8773. raycast( raycaster, intersects ) {
  8774. const matrixWorld = this.matrixWorld;
  8775. const raycastTimes = this.count;
  8776. _mesh$1.geometry = this.geometry;
  8777. _mesh$1.material = this.material;
  8778. if ( _mesh$1.material === undefined ) return;
  8779. // test with bounding sphere first
  8780. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8781. _sphere$4.copy( this.boundingSphere );
  8782. _sphere$4.applyMatrix4( matrixWorld );
  8783. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8784. // now test each instance
  8785. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8786. // calculate the world matrix for each instance
  8787. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8788. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8789. // the mesh represents this single instance
  8790. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8791. _mesh$1.raycast( raycaster, _instanceIntersects );
  8792. // process the result of raycast
  8793. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8794. const intersect = _instanceIntersects[ i ];
  8795. intersect.instanceId = instanceId;
  8796. intersect.object = this;
  8797. intersects.push( intersect );
  8798. }
  8799. _instanceIntersects.length = 0;
  8800. }
  8801. }
  8802. setColorAt( index, color ) {
  8803. if ( this.instanceColor === null ) {
  8804. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8805. }
  8806. color.toArray( this.instanceColor.array, index * 3 );
  8807. }
  8808. setMatrixAt( index, matrix ) {
  8809. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8810. }
  8811. setMorphAt( index, object ) {
  8812. const objectInfluences = object.morphTargetInfluences;
  8813. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8814. if ( this.morphTexture === null ) {
  8815. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8816. }
  8817. const array = this.morphTexture.source.data.data;
  8818. let morphInfluencesSum = 0;
  8819. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8820. morphInfluencesSum += objectInfluences[ i ];
  8821. }
  8822. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8823. const dataIndex = len * index;
  8824. array[ dataIndex ] = morphBaseInfluence;
  8825. array.set( objectInfluences, dataIndex + 1 );
  8826. }
  8827. updateMorphTargets() {
  8828. }
  8829. dispose() {
  8830. this.dispatchEvent( { type: 'dispose' } );
  8831. if ( this.morphTexture !== null ) {
  8832. this.morphTexture.dispose();
  8833. this.morphTexture = null;
  8834. }
  8835. return this;
  8836. }
  8837. }
  8838. const _vector1 = /*@__PURE__*/ new Vector3();
  8839. const _vector2 = /*@__PURE__*/ new Vector3();
  8840. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8841. class Plane {
  8842. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8843. this.isPlane = true;
  8844. // normal is assumed to be normalized
  8845. this.normal = normal;
  8846. this.constant = constant;
  8847. }
  8848. set( normal, constant ) {
  8849. this.normal.copy( normal );
  8850. this.constant = constant;
  8851. return this;
  8852. }
  8853. setComponents( x, y, z, w ) {
  8854. this.normal.set( x, y, z );
  8855. this.constant = w;
  8856. return this;
  8857. }
  8858. setFromNormalAndCoplanarPoint( normal, point ) {
  8859. this.normal.copy( normal );
  8860. this.constant = - point.dot( this.normal );
  8861. return this;
  8862. }
  8863. setFromCoplanarPoints( a, b, c ) {
  8864. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8865. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8866. this.setFromNormalAndCoplanarPoint( normal, a );
  8867. return this;
  8868. }
  8869. copy( plane ) {
  8870. this.normal.copy( plane.normal );
  8871. this.constant = plane.constant;
  8872. return this;
  8873. }
  8874. normalize() {
  8875. // Note: will lead to a divide by zero if the plane is invalid.
  8876. const inverseNormalLength = 1.0 / this.normal.length();
  8877. this.normal.multiplyScalar( inverseNormalLength );
  8878. this.constant *= inverseNormalLength;
  8879. return this;
  8880. }
  8881. negate() {
  8882. this.constant *= - 1;
  8883. this.normal.negate();
  8884. return this;
  8885. }
  8886. distanceToPoint( point ) {
  8887. return this.normal.dot( point ) + this.constant;
  8888. }
  8889. distanceToSphere( sphere ) {
  8890. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8891. }
  8892. projectPoint( point, target ) {
  8893. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8894. }
  8895. intersectLine( line, target ) {
  8896. const direction = line.delta( _vector1 );
  8897. const denominator = this.normal.dot( direction );
  8898. if ( denominator === 0 ) {
  8899. // line is coplanar, return origin
  8900. if ( this.distanceToPoint( line.start ) === 0 ) {
  8901. return target.copy( line.start );
  8902. }
  8903. // Unsure if this is the correct method to handle this case.
  8904. return null;
  8905. }
  8906. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8907. if ( t < 0 || t > 1 ) {
  8908. return null;
  8909. }
  8910. return target.copy( line.start ).addScaledVector( direction, t );
  8911. }
  8912. intersectsLine( line ) {
  8913. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8914. const startSign = this.distanceToPoint( line.start );
  8915. const endSign = this.distanceToPoint( line.end );
  8916. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8917. }
  8918. intersectsBox( box ) {
  8919. return box.intersectsPlane( this );
  8920. }
  8921. intersectsSphere( sphere ) {
  8922. return sphere.intersectsPlane( this );
  8923. }
  8924. coplanarPoint( target ) {
  8925. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8926. }
  8927. applyMatrix4( matrix, optionalNormalMatrix ) {
  8928. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8929. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8930. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8931. this.constant = - referencePoint.dot( normal );
  8932. return this;
  8933. }
  8934. translate( offset ) {
  8935. this.constant -= offset.dot( this.normal );
  8936. return this;
  8937. }
  8938. equals( plane ) {
  8939. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8940. }
  8941. clone() {
  8942. return new this.constructor().copy( this );
  8943. }
  8944. }
  8945. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8946. const _vector$6 = /*@__PURE__*/ new Vector3();
  8947. class Frustum {
  8948. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8949. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8950. }
  8951. set( p0, p1, p2, p3, p4, p5 ) {
  8952. const planes = this.planes;
  8953. planes[ 0 ].copy( p0 );
  8954. planes[ 1 ].copy( p1 );
  8955. planes[ 2 ].copy( p2 );
  8956. planes[ 3 ].copy( p3 );
  8957. planes[ 4 ].copy( p4 );
  8958. planes[ 5 ].copy( p5 );
  8959. return this;
  8960. }
  8961. copy( frustum ) {
  8962. const planes = this.planes;
  8963. for ( let i = 0; i < 6; i ++ ) {
  8964. planes[ i ].copy( frustum.planes[ i ] );
  8965. }
  8966. return this;
  8967. }
  8968. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8969. const planes = this.planes;
  8970. const me = m.elements;
  8971. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8972. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8973. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8974. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8975. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8976. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8977. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8978. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8979. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8980. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8981. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8982. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8983. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8984. } else {
  8985. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8986. }
  8987. return this;
  8988. }
  8989. intersectsObject( object ) {
  8990. if ( object.boundingSphere !== undefined ) {
  8991. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8992. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8993. } else {
  8994. const geometry = object.geometry;
  8995. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8996. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8997. }
  8998. return this.intersectsSphere( _sphere$3 );
  8999. }
  9000. intersectsSprite( sprite ) {
  9001. _sphere$3.center.set( 0, 0, 0 );
  9002. _sphere$3.radius = 0.7071067811865476;
  9003. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9004. return this.intersectsSphere( _sphere$3 );
  9005. }
  9006. intersectsSphere( sphere ) {
  9007. const planes = this.planes;
  9008. const center = sphere.center;
  9009. const negRadius = - sphere.radius;
  9010. for ( let i = 0; i < 6; i ++ ) {
  9011. const distance = planes[ i ].distanceToPoint( center );
  9012. if ( distance < negRadius ) {
  9013. return false;
  9014. }
  9015. }
  9016. return true;
  9017. }
  9018. intersectsBox( box ) {
  9019. const planes = this.planes;
  9020. for ( let i = 0; i < 6; i ++ ) {
  9021. const plane = planes[ i ];
  9022. // corner at max distance
  9023. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9024. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9025. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9026. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9027. return false;
  9028. }
  9029. }
  9030. return true;
  9031. }
  9032. containsPoint( point ) {
  9033. const planes = this.planes;
  9034. for ( let i = 0; i < 6; i ++ ) {
  9035. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9036. return false;
  9037. }
  9038. }
  9039. return true;
  9040. }
  9041. clone() {
  9042. return new this.constructor().copy( this );
  9043. }
  9044. }
  9045. function sortOpaque( a, b ) {
  9046. return a.z - b.z;
  9047. }
  9048. function sortTransparent( a, b ) {
  9049. return b.z - a.z;
  9050. }
  9051. class MultiDrawRenderList {
  9052. constructor() {
  9053. this.index = 0;
  9054. this.pool = [];
  9055. this.list = [];
  9056. }
  9057. push( drawRange, z, index ) {
  9058. const pool = this.pool;
  9059. const list = this.list;
  9060. if ( this.index >= pool.length ) {
  9061. pool.push( {
  9062. start: - 1,
  9063. count: - 1,
  9064. z: - 1,
  9065. index: - 1,
  9066. } );
  9067. }
  9068. const item = pool[ this.index ];
  9069. list.push( item );
  9070. this.index ++;
  9071. item.start = drawRange.start;
  9072. item.count = drawRange.count;
  9073. item.z = z;
  9074. item.index = index;
  9075. }
  9076. reset() {
  9077. this.list.length = 0;
  9078. this.index = 0;
  9079. }
  9080. }
  9081. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9082. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9083. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9084. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9085. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9086. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9087. const _box$1 = /*@__PURE__*/ new Box3();
  9088. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9089. const _vector$5 = /*@__PURE__*/ new Vector3();
  9090. const _forward = /*@__PURE__*/ new Vector3();
  9091. const _temp = /*@__PURE__*/ new Vector3();
  9092. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9093. const _mesh = /*@__PURE__*/ new Mesh();
  9094. const _batchIntersects = [];
  9095. // @TODO: SkinnedMesh support?
  9096. // @TODO: geometry.groups support?
  9097. // @TODO: geometry.drawRange support?
  9098. // @TODO: geometry.morphAttributes support?
  9099. // @TODO: Support uniform parameter per geometry
  9100. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9101. // copies data from attribute "src" into "target" starting at "targetOffset"
  9102. function copyAttributeData( src, target, targetOffset = 0 ) {
  9103. const itemSize = target.itemSize;
  9104. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9105. // use the component getters and setters if the array data cannot
  9106. // be copied directly
  9107. const vertexCount = src.count;
  9108. for ( let i = 0; i < vertexCount; i ++ ) {
  9109. for ( let c = 0; c < itemSize; c ++ ) {
  9110. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9111. }
  9112. }
  9113. } else {
  9114. // faster copy approach using typed array set function
  9115. target.array.set( src.array, targetOffset * itemSize );
  9116. }
  9117. target.needsUpdate = true;
  9118. }
  9119. class BatchedMesh extends Mesh {
  9120. get maxInstanceCount() {
  9121. return this._maxInstanceCount;
  9122. }
  9123. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9124. super( new BufferGeometry(), material );
  9125. this.isBatchedMesh = true;
  9126. this.perObjectFrustumCulled = true;
  9127. this.sortObjects = true;
  9128. this.boundingBox = null;
  9129. this.boundingSphere = null;
  9130. this.customSort = null;
  9131. // stores visible, active, and geometry id per object
  9132. this._drawInfo = [];
  9133. // instance ids that have been set as inactive, and are available to be overwritten
  9134. this._availableInstanceIds = [];
  9135. // geometry information
  9136. this._drawRanges = [];
  9137. this._reservedRanges = [];
  9138. this._bounds = [];
  9139. this._maxInstanceCount = maxInstanceCount;
  9140. this._maxVertexCount = maxVertexCount;
  9141. this._maxIndexCount = maxIndexCount;
  9142. this._geometryInitialized = false;
  9143. this._geometryCount = 0;
  9144. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9145. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9146. this._multiDrawCount = 0;
  9147. this._multiDrawInstances = null;
  9148. this._visibilityChanged = true;
  9149. // Local matrix per geometry by using data texture
  9150. this._matricesTexture = null;
  9151. this._indirectTexture = null;
  9152. this._colorsTexture = null;
  9153. this._initMatricesTexture();
  9154. this._initIndirectTexture();
  9155. }
  9156. _initMatricesTexture() {
  9157. // layout (1 matrix = 4 pixels)
  9158. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9159. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9160. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9161. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9162. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9163. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9164. size = Math.ceil( size / 4 ) * 4;
  9165. size = Math.max( size, 4 );
  9166. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9167. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9168. this._matricesTexture = matricesTexture;
  9169. }
  9170. _initIndirectTexture() {
  9171. let size = Math.sqrt( this._maxInstanceCount );
  9172. size = Math.ceil( size );
  9173. const indirectArray = new Uint32Array( size * size );
  9174. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9175. this._indirectTexture = indirectTexture;
  9176. }
  9177. _initColorsTexture() {
  9178. let size = Math.sqrt( this._maxInstanceCount );
  9179. size = Math.ceil( size );
  9180. // 4 floats per RGBA pixel initialized to white
  9181. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9182. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9183. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9184. this._colorsTexture = colorsTexture;
  9185. }
  9186. _initializeGeometry( reference ) {
  9187. const geometry = this.geometry;
  9188. const maxVertexCount = this._maxVertexCount;
  9189. const maxIndexCount = this._maxIndexCount;
  9190. if ( this._geometryInitialized === false ) {
  9191. for ( const attributeName in reference.attributes ) {
  9192. const srcAttribute = reference.getAttribute( attributeName );
  9193. const { array, itemSize, normalized } = srcAttribute;
  9194. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9195. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9196. geometry.setAttribute( attributeName, dstAttribute );
  9197. }
  9198. if ( reference.getIndex() !== null ) {
  9199. // Reserve last u16 index for primitive restart.
  9200. const indexArray = maxVertexCount > 65535
  9201. ? new Uint32Array( maxIndexCount )
  9202. : new Uint16Array( maxIndexCount );
  9203. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9204. }
  9205. this._geometryInitialized = true;
  9206. }
  9207. }
  9208. // Make sure the geometry is compatible with the existing combined geometry attributes
  9209. _validateGeometry( geometry ) {
  9210. // check to ensure the geometries are using consistent attributes and indices
  9211. const batchGeometry = this.geometry;
  9212. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9213. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9214. }
  9215. for ( const attributeName in batchGeometry.attributes ) {
  9216. if ( ! geometry.hasAttribute( attributeName ) ) {
  9217. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9218. }
  9219. const srcAttribute = geometry.getAttribute( attributeName );
  9220. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9221. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9222. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9223. }
  9224. }
  9225. }
  9226. setCustomSort( func ) {
  9227. this.customSort = func;
  9228. return this;
  9229. }
  9230. computeBoundingBox() {
  9231. if ( this.boundingBox === null ) {
  9232. this.boundingBox = new Box3();
  9233. }
  9234. const boundingBox = this.boundingBox;
  9235. const drawInfo = this._drawInfo;
  9236. boundingBox.makeEmpty();
  9237. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9238. if ( drawInfo[ i ].active === false ) continue;
  9239. const geometryId = drawInfo[ i ].geometryIndex;
  9240. this.getMatrixAt( i, _matrix$1 );
  9241. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9242. boundingBox.union( _box$1 );
  9243. }
  9244. }
  9245. computeBoundingSphere() {
  9246. if ( this.boundingSphere === null ) {
  9247. this.boundingSphere = new Sphere();
  9248. }
  9249. const boundingSphere = this.boundingSphere;
  9250. const drawInfo = this._drawInfo;
  9251. boundingSphere.makeEmpty();
  9252. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9253. if ( drawInfo[ i ].active === false ) continue;
  9254. const geometryId = drawInfo[ i ].geometryIndex;
  9255. this.getMatrixAt( i, _matrix$1 );
  9256. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9257. boundingSphere.union( _sphere$2 );
  9258. }
  9259. }
  9260. addInstance( geometryId ) {
  9261. const atCapacity = this._drawInfo.length >= this.maxInstanceCount;
  9262. // ensure we're not over geometry
  9263. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  9264. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9265. }
  9266. const instanceDrawInfo = {
  9267. visible: true,
  9268. active: true,
  9269. geometryIndex: geometryId,
  9270. };
  9271. let drawId = null;
  9272. // Prioritize using previously freed instance ids
  9273. if ( this._availableInstanceIds.length > 0 ) {
  9274. drawId = this._availableInstanceIds.pop();
  9275. this._drawInfo[ drawId ] = instanceDrawInfo;
  9276. } else {
  9277. drawId = this._drawInfo.length;
  9278. this._drawInfo.push( instanceDrawInfo );
  9279. }
  9280. const matricesTexture = this._matricesTexture;
  9281. const matricesArray = matricesTexture.image.data;
  9282. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9283. matricesTexture.needsUpdate = true;
  9284. const colorsTexture = this._colorsTexture;
  9285. if ( colorsTexture ) {
  9286. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9287. colorsTexture.needsUpdate = true;
  9288. }
  9289. return drawId;
  9290. }
  9291. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9292. this._initializeGeometry( geometry );
  9293. this._validateGeometry( geometry );
  9294. // ensure we're not over geometry
  9295. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9296. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9297. }
  9298. // get the necessary range fo the geometry
  9299. const reservedRange = {
  9300. vertexStart: - 1,
  9301. vertexCount: - 1,
  9302. indexStart: - 1,
  9303. indexCount: - 1,
  9304. };
  9305. let lastRange = null;
  9306. const reservedRanges = this._reservedRanges;
  9307. const drawRanges = this._drawRanges;
  9308. const bounds = this._bounds;
  9309. if ( this._geometryCount !== 0 ) {
  9310. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9311. }
  9312. if ( vertexCount === - 1 ) {
  9313. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9314. } else {
  9315. reservedRange.vertexCount = vertexCount;
  9316. }
  9317. if ( lastRange === null ) {
  9318. reservedRange.vertexStart = 0;
  9319. } else {
  9320. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9321. }
  9322. const index = geometry.getIndex();
  9323. const hasIndex = index !== null;
  9324. if ( hasIndex ) {
  9325. if ( indexCount === - 1 ) {
  9326. reservedRange.indexCount = index.count;
  9327. } else {
  9328. reservedRange.indexCount = indexCount;
  9329. }
  9330. if ( lastRange === null ) {
  9331. reservedRange.indexStart = 0;
  9332. } else {
  9333. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9334. }
  9335. }
  9336. if (
  9337. reservedRange.indexStart !== - 1 &&
  9338. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9339. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9340. ) {
  9341. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9342. }
  9343. // update id
  9344. const geometryId = this._geometryCount;
  9345. this._geometryCount ++;
  9346. // add the reserved range and draw range objects
  9347. reservedRanges.push( reservedRange );
  9348. drawRanges.push( {
  9349. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9350. count: - 1
  9351. } );
  9352. bounds.push( {
  9353. boxInitialized: false,
  9354. box: new Box3(),
  9355. sphereInitialized: false,
  9356. sphere: new Sphere()
  9357. } );
  9358. // update the geometry
  9359. this.setGeometryAt( geometryId, geometry );
  9360. return geometryId;
  9361. }
  9362. setGeometryAt( geometryId, geometry ) {
  9363. if ( geometryId >= this._geometryCount ) {
  9364. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9365. }
  9366. this._validateGeometry( geometry );
  9367. const batchGeometry = this.geometry;
  9368. const hasIndex = batchGeometry.getIndex() !== null;
  9369. const dstIndex = batchGeometry.getIndex();
  9370. const srcIndex = geometry.getIndex();
  9371. const reservedRange = this._reservedRanges[ geometryId ];
  9372. if (
  9373. hasIndex &&
  9374. srcIndex.count > reservedRange.indexCount ||
  9375. geometry.attributes.position.count > reservedRange.vertexCount
  9376. ) {
  9377. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9378. }
  9379. // copy geometry over
  9380. const vertexStart = reservedRange.vertexStart;
  9381. const vertexCount = reservedRange.vertexCount;
  9382. for ( const attributeName in batchGeometry.attributes ) {
  9383. // copy attribute data
  9384. const srcAttribute = geometry.getAttribute( attributeName );
  9385. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9386. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9387. // fill the rest in with zeroes
  9388. const itemSize = srcAttribute.itemSize;
  9389. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9390. const index = vertexStart + i;
  9391. for ( let c = 0; c < itemSize; c ++ ) {
  9392. dstAttribute.setComponent( index, c, 0 );
  9393. }
  9394. }
  9395. dstAttribute.needsUpdate = true;
  9396. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9397. }
  9398. // copy index
  9399. if ( hasIndex ) {
  9400. const indexStart = reservedRange.indexStart;
  9401. // copy index data over
  9402. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9403. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9404. }
  9405. // fill the rest in with zeroes
  9406. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9407. dstIndex.setX( indexStart + i, vertexStart );
  9408. }
  9409. dstIndex.needsUpdate = true;
  9410. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9411. }
  9412. // store the bounding boxes
  9413. const bound = this._bounds[ geometryId ];
  9414. if ( geometry.boundingBox !== null ) {
  9415. bound.box.copy( geometry.boundingBox );
  9416. bound.boxInitialized = true;
  9417. } else {
  9418. bound.boxInitialized = false;
  9419. }
  9420. if ( geometry.boundingSphere !== null ) {
  9421. bound.sphere.copy( geometry.boundingSphere );
  9422. bound.sphereInitialized = true;
  9423. } else {
  9424. bound.sphereInitialized = false;
  9425. }
  9426. // set drawRange count
  9427. const drawRange = this._drawRanges[ geometryId ];
  9428. const posAttr = geometry.getAttribute( 'position' );
  9429. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9430. this._visibilityChanged = true;
  9431. return geometryId;
  9432. }
  9433. /*
  9434. deleteGeometry( geometryId ) {
  9435. // TODO: delete geometry and associated instances
  9436. }
  9437. */
  9438. deleteInstance( instanceId ) {
  9439. const drawInfo = this._drawInfo;
  9440. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9441. return this;
  9442. }
  9443. drawInfo[ instanceId ].active = false;
  9444. this._availableInstanceIds.push( instanceId );
  9445. this._visibilityChanged = true;
  9446. return this;
  9447. }
  9448. // get bounding box and compute it if it doesn't exist
  9449. getBoundingBoxAt( geometryId, target ) {
  9450. if ( geometryId >= this._geometryCount ) {
  9451. return null;
  9452. }
  9453. // compute bounding box
  9454. const bound = this._bounds[ geometryId ];
  9455. const box = bound.box;
  9456. const geometry = this.geometry;
  9457. if ( bound.boxInitialized === false ) {
  9458. box.makeEmpty();
  9459. const index = geometry.index;
  9460. const position = geometry.attributes.position;
  9461. const drawRange = this._drawRanges[ geometryId ];
  9462. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9463. let iv = i;
  9464. if ( index ) {
  9465. iv = index.getX( iv );
  9466. }
  9467. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9468. }
  9469. bound.boxInitialized = true;
  9470. }
  9471. target.copy( box );
  9472. return target;
  9473. }
  9474. // get bounding sphere and compute it if it doesn't exist
  9475. getBoundingSphereAt( geometryId, target ) {
  9476. if ( geometryId >= this._geometryCount ) {
  9477. return null;
  9478. }
  9479. // compute bounding sphere
  9480. const bound = this._bounds[ geometryId ];
  9481. const sphere = bound.sphere;
  9482. const geometry = this.geometry;
  9483. if ( bound.sphereInitialized === false ) {
  9484. sphere.makeEmpty();
  9485. this.getBoundingBoxAt( geometryId, _box$1 );
  9486. _box$1.getCenter( sphere.center );
  9487. const index = geometry.index;
  9488. const position = geometry.attributes.position;
  9489. const drawRange = this._drawRanges[ geometryId ];
  9490. let maxRadiusSq = 0;
  9491. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9492. let iv = i;
  9493. if ( index ) {
  9494. iv = index.getX( iv );
  9495. }
  9496. _vector$5.fromBufferAttribute( position, iv );
  9497. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9498. }
  9499. sphere.radius = Math.sqrt( maxRadiusSq );
  9500. bound.sphereInitialized = true;
  9501. }
  9502. target.copy( sphere );
  9503. return target;
  9504. }
  9505. setMatrixAt( instanceId, matrix ) {
  9506. // @TODO: Map geometryId to index of the arrays because
  9507. // optimize() can make geometryId mismatch the index
  9508. const drawInfo = this._drawInfo;
  9509. const matricesTexture = this._matricesTexture;
  9510. const matricesArray = this._matricesTexture.image.data;
  9511. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9512. return this;
  9513. }
  9514. matrix.toArray( matricesArray, instanceId * 16 );
  9515. matricesTexture.needsUpdate = true;
  9516. return this;
  9517. }
  9518. getMatrixAt( instanceId, matrix ) {
  9519. const drawInfo = this._drawInfo;
  9520. const matricesArray = this._matricesTexture.image.data;
  9521. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9522. return null;
  9523. }
  9524. return matrix.fromArray( matricesArray, instanceId * 16 );
  9525. }
  9526. setColorAt( instanceId, color ) {
  9527. if ( this._colorsTexture === null ) {
  9528. this._initColorsTexture();
  9529. }
  9530. // @TODO: Map id to index of the arrays because
  9531. // optimize() can make id mismatch the index
  9532. const colorsTexture = this._colorsTexture;
  9533. const colorsArray = this._colorsTexture.image.data;
  9534. const drawInfo = this._drawInfo;
  9535. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9536. return this;
  9537. }
  9538. color.toArray( colorsArray, instanceId * 4 );
  9539. colorsTexture.needsUpdate = true;
  9540. return this;
  9541. }
  9542. getColorAt( instanceId, color ) {
  9543. const colorsArray = this._colorsTexture.image.data;
  9544. const drawInfo = this._drawInfo;
  9545. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9546. return null;
  9547. }
  9548. return color.fromArray( colorsArray, instanceId * 4 );
  9549. }
  9550. setVisibleAt( instanceId, value ) {
  9551. // if the geometry is out of range, not active, or visibility state
  9552. // does not change then return early
  9553. const drawInfo = this._drawInfo;
  9554. if (
  9555. instanceId >= drawInfo.length ||
  9556. drawInfo[ instanceId ].active === false ||
  9557. drawInfo[ instanceId ].visible === value
  9558. ) {
  9559. return this;
  9560. }
  9561. drawInfo[ instanceId ].visible = value;
  9562. this._visibilityChanged = true;
  9563. return this;
  9564. }
  9565. getVisibleAt( instanceId ) {
  9566. // return early if the geometry is out of range or not active
  9567. const drawInfo = this._drawInfo;
  9568. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9569. return false;
  9570. }
  9571. return drawInfo[ instanceId ].visible;
  9572. }
  9573. setGeometryIdAt( instanceId, geometryId ) {
  9574. // return early if the geometry is out of range or not active
  9575. const drawInfo = this._drawInfo;
  9576. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9577. return null;
  9578. }
  9579. // check if the provided geometryId is within the valid range
  9580. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9581. return null;
  9582. }
  9583. drawInfo[ instanceId ].geometryIndex = geometryId;
  9584. return this;
  9585. }
  9586. getGeometryIdAt( instanceId ) {
  9587. const drawInfo = this._drawInfo;
  9588. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9589. return - 1;
  9590. }
  9591. return drawInfo[ instanceId ].geometryIndex;
  9592. }
  9593. getGeometryRangeAt( geometryId, target = {} ) {
  9594. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9595. return null;
  9596. }
  9597. const drawRange = this._drawRanges[ geometryId ];
  9598. target.start = drawRange.start;
  9599. target.count = drawRange.count;
  9600. return target;
  9601. }
  9602. raycast( raycaster, intersects ) {
  9603. const drawInfo = this._drawInfo;
  9604. const drawRanges = this._drawRanges;
  9605. const matrixWorld = this.matrixWorld;
  9606. const batchGeometry = this.geometry;
  9607. // iterate over each geometry
  9608. _mesh.material = this.material;
  9609. _mesh.geometry.index = batchGeometry.index;
  9610. _mesh.geometry.attributes = batchGeometry.attributes;
  9611. if ( _mesh.geometry.boundingBox === null ) {
  9612. _mesh.geometry.boundingBox = new Box3();
  9613. }
  9614. if ( _mesh.geometry.boundingSphere === null ) {
  9615. _mesh.geometry.boundingSphere = new Sphere();
  9616. }
  9617. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9618. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9619. continue;
  9620. }
  9621. const geometryId = drawInfo[ i ].geometryIndex;
  9622. const drawRange = drawRanges[ geometryId ];
  9623. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9624. // ge the intersects
  9625. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9626. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9627. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9628. _mesh.raycast( raycaster, _batchIntersects );
  9629. // add batch id to the intersects
  9630. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9631. const intersect = _batchIntersects[ j ];
  9632. intersect.object = this;
  9633. intersect.batchId = i;
  9634. intersects.push( intersect );
  9635. }
  9636. _batchIntersects.length = 0;
  9637. }
  9638. _mesh.material = null;
  9639. _mesh.geometry.index = null;
  9640. _mesh.geometry.attributes = {};
  9641. _mesh.geometry.setDrawRange( 0, Infinity );
  9642. }
  9643. copy( source ) {
  9644. super.copy( source );
  9645. this.geometry = source.geometry.clone();
  9646. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9647. this.sortObjects = source.sortObjects;
  9648. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9649. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9650. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9651. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9652. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9653. this._bounds = source._bounds.map( bound => ( {
  9654. boxInitialized: bound.boxInitialized,
  9655. box: bound.box.clone(),
  9656. sphereInitialized: bound.sphereInitialized,
  9657. sphere: bound.sphere.clone()
  9658. } ) );
  9659. this._maxInstanceCount = source._maxInstanceCount;
  9660. this._maxVertexCount = source._maxVertexCount;
  9661. this._maxIndexCount = source._maxIndexCount;
  9662. this._geometryInitialized = source._geometryInitialized;
  9663. this._geometryCount = source._geometryCount;
  9664. this._multiDrawCounts = source._multiDrawCounts.slice();
  9665. this._multiDrawStarts = source._multiDrawStarts.slice();
  9666. this._matricesTexture = source._matricesTexture.clone();
  9667. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9668. if ( this._colorsTexture !== null ) {
  9669. this._colorsTexture = source._colorsTexture.clone();
  9670. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9671. }
  9672. return this;
  9673. }
  9674. dispose() {
  9675. // Assuming the geometry is not shared with other meshes
  9676. this.geometry.dispose();
  9677. this._matricesTexture.dispose();
  9678. this._matricesTexture = null;
  9679. this._indirectTexture.dispose();
  9680. this._indirectTexture = null;
  9681. if ( this._colorsTexture !== null ) {
  9682. this._colorsTexture.dispose();
  9683. this._colorsTexture = null;
  9684. }
  9685. return this;
  9686. }
  9687. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9688. // if visibility has not changed and frustum culling and object sorting is not required
  9689. // then skip iterating over all items
  9690. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9691. return;
  9692. }
  9693. // the indexed version of the multi draw function requires specifying the start
  9694. // offset in bytes.
  9695. const index = geometry.getIndex();
  9696. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9697. const drawInfo = this._drawInfo;
  9698. const multiDrawStarts = this._multiDrawStarts;
  9699. const multiDrawCounts = this._multiDrawCounts;
  9700. const drawRanges = this._drawRanges;
  9701. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9702. const indirectTexture = this._indirectTexture;
  9703. const indirectArray = indirectTexture.image.data;
  9704. // prepare the frustum in the local frame
  9705. if ( perObjectFrustumCulled ) {
  9706. _projScreenMatrix$3
  9707. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9708. .multiply( this.matrixWorld );
  9709. _frustum$1.setFromProjectionMatrix(
  9710. _projScreenMatrix$3,
  9711. renderer.coordinateSystem
  9712. );
  9713. }
  9714. let count = 0;
  9715. if ( this.sortObjects ) {
  9716. // get the camera position in the local frame
  9717. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9718. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9719. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9720. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9721. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9722. const geometryId = drawInfo[ i ].geometryIndex;
  9723. // get the bounds in world space
  9724. this.getMatrixAt( i, _matrix$1 );
  9725. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9726. // determine whether the batched geometry is within the frustum
  9727. let culled = false;
  9728. if ( perObjectFrustumCulled ) {
  9729. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9730. }
  9731. if ( ! culled ) {
  9732. // get the distance from camera used for sorting
  9733. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9734. _renderList.push( drawRanges[ geometryId ], z, i );
  9735. }
  9736. }
  9737. }
  9738. // Sort the draw ranges and prep for rendering
  9739. const list = _renderList.list;
  9740. const customSort = this.customSort;
  9741. if ( customSort === null ) {
  9742. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9743. } else {
  9744. customSort.call( this, list, camera );
  9745. }
  9746. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9747. const item = list[ i ];
  9748. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9749. multiDrawCounts[ count ] = item.count;
  9750. indirectArray[ count ] = item.index;
  9751. count ++;
  9752. }
  9753. _renderList.reset();
  9754. } else {
  9755. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9756. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9757. const geometryId = drawInfo[ i ].geometryIndex;
  9758. // determine whether the batched geometry is within the frustum
  9759. let culled = false;
  9760. if ( perObjectFrustumCulled ) {
  9761. // get the bounds in world space
  9762. this.getMatrixAt( i, _matrix$1 );
  9763. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9764. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9765. }
  9766. if ( ! culled ) {
  9767. const range = drawRanges[ geometryId ];
  9768. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9769. multiDrawCounts[ count ] = range.count;
  9770. indirectArray[ count ] = i;
  9771. count ++;
  9772. }
  9773. }
  9774. }
  9775. }
  9776. indirectTexture.needsUpdate = true;
  9777. this._multiDrawCount = count;
  9778. this._visibilityChanged = false;
  9779. }
  9780. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9781. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9782. }
  9783. }
  9784. class LineBasicMaterial extends Material {
  9785. constructor( parameters ) {
  9786. super();
  9787. this.isLineBasicMaterial = true;
  9788. this.type = 'LineBasicMaterial';
  9789. this.color = new Color( 0xffffff );
  9790. this.map = null;
  9791. this.linewidth = 1;
  9792. this.linecap = 'round';
  9793. this.linejoin = 'round';
  9794. this.fog = true;
  9795. this.setValues( parameters );
  9796. }
  9797. copy( source ) {
  9798. super.copy( source );
  9799. this.color.copy( source.color );
  9800. this.map = source.map;
  9801. this.linewidth = source.linewidth;
  9802. this.linecap = source.linecap;
  9803. this.linejoin = source.linejoin;
  9804. this.fog = source.fog;
  9805. return this;
  9806. }
  9807. }
  9808. const _vStart = /*@__PURE__*/ new Vector3();
  9809. const _vEnd = /*@__PURE__*/ new Vector3();
  9810. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9811. const _ray$1 = /*@__PURE__*/ new Ray();
  9812. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9813. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9814. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9815. class Line extends Object3D {
  9816. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9817. super();
  9818. this.isLine = true;
  9819. this.type = 'Line';
  9820. this.geometry = geometry;
  9821. this.material = material;
  9822. this.updateMorphTargets();
  9823. }
  9824. copy( source, recursive ) {
  9825. super.copy( source, recursive );
  9826. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9827. this.geometry = source.geometry;
  9828. return this;
  9829. }
  9830. computeLineDistances() {
  9831. const geometry = this.geometry;
  9832. // we assume non-indexed geometry
  9833. if ( geometry.index === null ) {
  9834. const positionAttribute = geometry.attributes.position;
  9835. const lineDistances = [ 0 ];
  9836. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9837. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9838. _vEnd.fromBufferAttribute( positionAttribute, i );
  9839. lineDistances[ i ] = lineDistances[ i - 1 ];
  9840. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9841. }
  9842. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9843. } else {
  9844. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9845. }
  9846. return this;
  9847. }
  9848. raycast( raycaster, intersects ) {
  9849. const geometry = this.geometry;
  9850. const matrixWorld = this.matrixWorld;
  9851. const threshold = raycaster.params.Line.threshold;
  9852. const drawRange = geometry.drawRange;
  9853. // Checking boundingSphere distance to ray
  9854. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9855. _sphere$1.copy( geometry.boundingSphere );
  9856. _sphere$1.applyMatrix4( matrixWorld );
  9857. _sphere$1.radius += threshold;
  9858. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9859. //
  9860. _inverseMatrix$1.copy( matrixWorld ).invert();
  9861. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9862. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9863. const localThresholdSq = localThreshold * localThreshold;
  9864. const step = this.isLineSegments ? 2 : 1;
  9865. const index = geometry.index;
  9866. const attributes = geometry.attributes;
  9867. const positionAttribute = attributes.position;
  9868. if ( index !== null ) {
  9869. const start = Math.max( 0, drawRange.start );
  9870. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9871. for ( let i = start, l = end - 1; i < l; i += step ) {
  9872. const a = index.getX( i );
  9873. const b = index.getX( i + 1 );
  9874. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9875. if ( intersect ) {
  9876. intersects.push( intersect );
  9877. }
  9878. }
  9879. if ( this.isLineLoop ) {
  9880. const a = index.getX( end - 1 );
  9881. const b = index.getX( start );
  9882. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9883. if ( intersect ) {
  9884. intersects.push( intersect );
  9885. }
  9886. }
  9887. } else {
  9888. const start = Math.max( 0, drawRange.start );
  9889. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9890. for ( let i = start, l = end - 1; i < l; i += step ) {
  9891. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9892. if ( intersect ) {
  9893. intersects.push( intersect );
  9894. }
  9895. }
  9896. if ( this.isLineLoop ) {
  9897. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9898. if ( intersect ) {
  9899. intersects.push( intersect );
  9900. }
  9901. }
  9902. }
  9903. }
  9904. updateMorphTargets() {
  9905. const geometry = this.geometry;
  9906. const morphAttributes = geometry.morphAttributes;
  9907. const keys = Object.keys( morphAttributes );
  9908. if ( keys.length > 0 ) {
  9909. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9910. if ( morphAttribute !== undefined ) {
  9911. this.morphTargetInfluences = [];
  9912. this.morphTargetDictionary = {};
  9913. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9914. const name = morphAttribute[ m ].name || String( m );
  9915. this.morphTargetInfluences.push( 0 );
  9916. this.morphTargetDictionary[ name ] = m;
  9917. }
  9918. }
  9919. }
  9920. }
  9921. }
  9922. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9923. const positionAttribute = object.geometry.attributes.position;
  9924. _vStart.fromBufferAttribute( positionAttribute, a );
  9925. _vEnd.fromBufferAttribute( positionAttribute, b );
  9926. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9927. if ( distSq > thresholdSq ) return;
  9928. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9929. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9930. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9931. return {
  9932. distance: distance,
  9933. // What do we want? intersection point on the ray or on the segment??
  9934. // point: raycaster.ray.at( distance ),
  9935. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9936. index: a,
  9937. face: null,
  9938. faceIndex: null,
  9939. barycoord: null,
  9940. object: object
  9941. };
  9942. }
  9943. const _start = /*@__PURE__*/ new Vector3();
  9944. const _end = /*@__PURE__*/ new Vector3();
  9945. class LineSegments extends Line {
  9946. constructor( geometry, material ) {
  9947. super( geometry, material );
  9948. this.isLineSegments = true;
  9949. this.type = 'LineSegments';
  9950. }
  9951. computeLineDistances() {
  9952. const geometry = this.geometry;
  9953. // we assume non-indexed geometry
  9954. if ( geometry.index === null ) {
  9955. const positionAttribute = geometry.attributes.position;
  9956. const lineDistances = [];
  9957. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9958. _start.fromBufferAttribute( positionAttribute, i );
  9959. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9960. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9961. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9962. }
  9963. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9964. } else {
  9965. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9966. }
  9967. return this;
  9968. }
  9969. }
  9970. class LineLoop extends Line {
  9971. constructor( geometry, material ) {
  9972. super( geometry, material );
  9973. this.isLineLoop = true;
  9974. this.type = 'LineLoop';
  9975. }
  9976. }
  9977. class PointsMaterial extends Material {
  9978. constructor( parameters ) {
  9979. super();
  9980. this.isPointsMaterial = true;
  9981. this.type = 'PointsMaterial';
  9982. this.color = new Color( 0xffffff );
  9983. this.map = null;
  9984. this.alphaMap = null;
  9985. this.size = 1;
  9986. this.sizeAttenuation = true;
  9987. this.fog = true;
  9988. this.setValues( parameters );
  9989. }
  9990. copy( source ) {
  9991. super.copy( source );
  9992. this.color.copy( source.color );
  9993. this.map = source.map;
  9994. this.alphaMap = source.alphaMap;
  9995. this.size = source.size;
  9996. this.sizeAttenuation = source.sizeAttenuation;
  9997. this.fog = source.fog;
  9998. return this;
  9999. }
  10000. }
  10001. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  10002. const _ray = /*@__PURE__*/ new Ray();
  10003. const _sphere = /*@__PURE__*/ new Sphere();
  10004. const _position$2 = /*@__PURE__*/ new Vector3();
  10005. class Points extends Object3D {
  10006. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  10007. super();
  10008. this.isPoints = true;
  10009. this.type = 'Points';
  10010. this.geometry = geometry;
  10011. this.material = material;
  10012. this.updateMorphTargets();
  10013. }
  10014. copy( source, recursive ) {
  10015. super.copy( source, recursive );
  10016. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10017. this.geometry = source.geometry;
  10018. return this;
  10019. }
  10020. raycast( raycaster, intersects ) {
  10021. const geometry = this.geometry;
  10022. const matrixWorld = this.matrixWorld;
  10023. const threshold = raycaster.params.Points.threshold;
  10024. const drawRange = geometry.drawRange;
  10025. // Checking boundingSphere distance to ray
  10026. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10027. _sphere.copy( geometry.boundingSphere );
  10028. _sphere.applyMatrix4( matrixWorld );
  10029. _sphere.radius += threshold;
  10030. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10031. //
  10032. _inverseMatrix.copy( matrixWorld ).invert();
  10033. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10034. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10035. const localThresholdSq = localThreshold * localThreshold;
  10036. const index = geometry.index;
  10037. const attributes = geometry.attributes;
  10038. const positionAttribute = attributes.position;
  10039. if ( index !== null ) {
  10040. const start = Math.max( 0, drawRange.start );
  10041. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10042. for ( let i = start, il = end; i < il; i ++ ) {
  10043. const a = index.getX( i );
  10044. _position$2.fromBufferAttribute( positionAttribute, a );
  10045. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10046. }
  10047. } else {
  10048. const start = Math.max( 0, drawRange.start );
  10049. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10050. for ( let i = start, l = end; i < l; i ++ ) {
  10051. _position$2.fromBufferAttribute( positionAttribute, i );
  10052. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10053. }
  10054. }
  10055. }
  10056. updateMorphTargets() {
  10057. const geometry = this.geometry;
  10058. const morphAttributes = geometry.morphAttributes;
  10059. const keys = Object.keys( morphAttributes );
  10060. if ( keys.length > 0 ) {
  10061. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10062. if ( morphAttribute !== undefined ) {
  10063. this.morphTargetInfluences = [];
  10064. this.morphTargetDictionary = {};
  10065. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10066. const name = morphAttribute[ m ].name || String( m );
  10067. this.morphTargetInfluences.push( 0 );
  10068. this.morphTargetDictionary[ name ] = m;
  10069. }
  10070. }
  10071. }
  10072. }
  10073. }
  10074. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10075. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10076. if ( rayPointDistanceSq < localThresholdSq ) {
  10077. const intersectPoint = new Vector3();
  10078. _ray.closestPointToPoint( point, intersectPoint );
  10079. intersectPoint.applyMatrix4( matrixWorld );
  10080. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10081. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10082. intersects.push( {
  10083. distance: distance,
  10084. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10085. point: intersectPoint,
  10086. index: index,
  10087. face: null,
  10088. faceIndex: null,
  10089. barycoord: null,
  10090. object: object
  10091. } );
  10092. }
  10093. }
  10094. class Group extends Object3D {
  10095. constructor() {
  10096. super();
  10097. this.isGroup = true;
  10098. this.type = 'Group';
  10099. }
  10100. }
  10101. class VideoTexture extends Texture {
  10102. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10103. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10104. this.isVideoTexture = true;
  10105. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10106. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10107. this.generateMipmaps = false;
  10108. const scope = this;
  10109. function updateVideo() {
  10110. scope.needsUpdate = true;
  10111. video.requestVideoFrameCallback( updateVideo );
  10112. }
  10113. if ( 'requestVideoFrameCallback' in video ) {
  10114. video.requestVideoFrameCallback( updateVideo );
  10115. }
  10116. }
  10117. clone() {
  10118. return new this.constructor( this.image ).copy( this );
  10119. }
  10120. update() {
  10121. const video = this.image;
  10122. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10123. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10124. this.needsUpdate = true;
  10125. }
  10126. }
  10127. }
  10128. class FramebufferTexture extends Texture {
  10129. constructor( width, height ) {
  10130. super( { width, height } );
  10131. this.isFramebufferTexture = true;
  10132. this.magFilter = NearestFilter;
  10133. this.minFilter = NearestFilter;
  10134. this.generateMipmaps = false;
  10135. this.needsUpdate = true;
  10136. }
  10137. }
  10138. class CompressedTexture extends Texture {
  10139. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10140. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10141. this.isCompressedTexture = true;
  10142. this.image = { width: width, height: height };
  10143. this.mipmaps = mipmaps;
  10144. // no flipping for cube textures
  10145. // (also flipping doesn't work for compressed textures )
  10146. this.flipY = false;
  10147. // can't generate mipmaps for compressed textures
  10148. // mips must be embedded in DDS files
  10149. this.generateMipmaps = false;
  10150. }
  10151. }
  10152. class CompressedArrayTexture extends CompressedTexture {
  10153. constructor( mipmaps, width, height, depth, format, type ) {
  10154. super( mipmaps, width, height, format, type );
  10155. this.isCompressedArrayTexture = true;
  10156. this.image.depth = depth;
  10157. this.wrapR = ClampToEdgeWrapping;
  10158. this.layerUpdates = new Set();
  10159. }
  10160. addLayerUpdate( layerIndex ) {
  10161. this.layerUpdates.add( layerIndex );
  10162. }
  10163. clearLayerUpdates() {
  10164. this.layerUpdates.clear();
  10165. }
  10166. }
  10167. class CompressedCubeTexture extends CompressedTexture {
  10168. constructor( images, format, type ) {
  10169. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10170. this.isCompressedCubeTexture = true;
  10171. this.isCubeTexture = true;
  10172. this.image = images;
  10173. }
  10174. }
  10175. class CanvasTexture extends Texture {
  10176. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10177. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10178. this.isCanvasTexture = true;
  10179. this.needsUpdate = true;
  10180. }
  10181. }
  10182. class DepthTexture extends Texture {
  10183. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10184. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10185. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10186. }
  10187. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10188. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10189. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10190. this.isDepthTexture = true;
  10191. this.image = { width: width, height: height };
  10192. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10193. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10194. this.flipY = false;
  10195. this.generateMipmaps = false;
  10196. this.compareFunction = null;
  10197. }
  10198. copy( source ) {
  10199. super.copy( source );
  10200. this.compareFunction = source.compareFunction;
  10201. return this;
  10202. }
  10203. toJSON( meta ) {
  10204. const data = super.toJSON( meta );
  10205. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10206. return data;
  10207. }
  10208. }
  10209. /**
  10210. * Extensible curve object.
  10211. *
  10212. * Some common of curve methods:
  10213. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10214. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10215. * .getPoints(), .getSpacedPoints()
  10216. * .getLength()
  10217. * .updateArcLengths()
  10218. *
  10219. * This following curves inherit from THREE.Curve:
  10220. *
  10221. * -- 2D curves --
  10222. * THREE.ArcCurve
  10223. * THREE.CubicBezierCurve
  10224. * THREE.EllipseCurve
  10225. * THREE.LineCurve
  10226. * THREE.QuadraticBezierCurve
  10227. * THREE.SplineCurve
  10228. *
  10229. * -- 3D curves --
  10230. * THREE.CatmullRomCurve3
  10231. * THREE.CubicBezierCurve3
  10232. * THREE.LineCurve3
  10233. * THREE.QuadraticBezierCurve3
  10234. *
  10235. * A series of curves can be represented as a THREE.CurvePath.
  10236. *
  10237. **/
  10238. class Curve {
  10239. constructor() {
  10240. this.type = 'Curve';
  10241. this.arcLengthDivisions = 200;
  10242. }
  10243. // Virtual base class method to overwrite and implement in subclasses
  10244. // - t [0 .. 1]
  10245. getPoint( /* t, optionalTarget */ ) {
  10246. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10247. return null;
  10248. }
  10249. // Get point at relative position in curve according to arc length
  10250. // - u [0 .. 1]
  10251. getPointAt( u, optionalTarget ) {
  10252. const t = this.getUtoTmapping( u );
  10253. return this.getPoint( t, optionalTarget );
  10254. }
  10255. // Get sequence of points using getPoint( t )
  10256. getPoints( divisions = 5 ) {
  10257. const points = [];
  10258. for ( let d = 0; d <= divisions; d ++ ) {
  10259. points.push( this.getPoint( d / divisions ) );
  10260. }
  10261. return points;
  10262. }
  10263. // Get sequence of points using getPointAt( u )
  10264. getSpacedPoints( divisions = 5 ) {
  10265. const points = [];
  10266. for ( let d = 0; d <= divisions; d ++ ) {
  10267. points.push( this.getPointAt( d / divisions ) );
  10268. }
  10269. return points;
  10270. }
  10271. // Get total curve arc length
  10272. getLength() {
  10273. const lengths = this.getLengths();
  10274. return lengths[ lengths.length - 1 ];
  10275. }
  10276. // Get list of cumulative segment lengths
  10277. getLengths( divisions = this.arcLengthDivisions ) {
  10278. if ( this.cacheArcLengths &&
  10279. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10280. ! this.needsUpdate ) {
  10281. return this.cacheArcLengths;
  10282. }
  10283. this.needsUpdate = false;
  10284. const cache = [];
  10285. let current, last = this.getPoint( 0 );
  10286. let sum = 0;
  10287. cache.push( 0 );
  10288. for ( let p = 1; p <= divisions; p ++ ) {
  10289. current = this.getPoint( p / divisions );
  10290. sum += current.distanceTo( last );
  10291. cache.push( sum );
  10292. last = current;
  10293. }
  10294. this.cacheArcLengths = cache;
  10295. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10296. }
  10297. updateArcLengths() {
  10298. this.needsUpdate = true;
  10299. this.getLengths();
  10300. }
  10301. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10302. getUtoTmapping( u, distance ) {
  10303. const arcLengths = this.getLengths();
  10304. let i = 0;
  10305. const il = arcLengths.length;
  10306. let targetArcLength; // The targeted u distance value to get
  10307. if ( distance ) {
  10308. targetArcLength = distance;
  10309. } else {
  10310. targetArcLength = u * arcLengths[ il - 1 ];
  10311. }
  10312. // binary search for the index with largest value smaller than target u distance
  10313. let low = 0, high = il - 1, comparison;
  10314. while ( low <= high ) {
  10315. 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
  10316. comparison = arcLengths[ i ] - targetArcLength;
  10317. if ( comparison < 0 ) {
  10318. low = i + 1;
  10319. } else if ( comparison > 0 ) {
  10320. high = i - 1;
  10321. } else {
  10322. high = i;
  10323. break;
  10324. // DONE
  10325. }
  10326. }
  10327. i = high;
  10328. if ( arcLengths[ i ] === targetArcLength ) {
  10329. return i / ( il - 1 );
  10330. }
  10331. // we could get finer grain at lengths, or use simple interpolation between two points
  10332. const lengthBefore = arcLengths[ i ];
  10333. const lengthAfter = arcLengths[ i + 1 ];
  10334. const segmentLength = lengthAfter - lengthBefore;
  10335. // determine where we are between the 'before' and 'after' points
  10336. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10337. // add that fractional amount to t
  10338. const t = ( i + segmentFraction ) / ( il - 1 );
  10339. return t;
  10340. }
  10341. // Returns a unit vector tangent at t
  10342. // In case any sub curve does not implement its tangent derivation,
  10343. // 2 points a small delta apart will be used to find its gradient
  10344. // which seems to give a reasonable approximation
  10345. getTangent( t, optionalTarget ) {
  10346. const delta = 0.0001;
  10347. let t1 = t - delta;
  10348. let t2 = t + delta;
  10349. // Capping in case of danger
  10350. if ( t1 < 0 ) t1 = 0;
  10351. if ( t2 > 1 ) t2 = 1;
  10352. const pt1 = this.getPoint( t1 );
  10353. const pt2 = this.getPoint( t2 );
  10354. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10355. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10356. return tangent;
  10357. }
  10358. getTangentAt( u, optionalTarget ) {
  10359. const t = this.getUtoTmapping( u );
  10360. return this.getTangent( t, optionalTarget );
  10361. }
  10362. computeFrenetFrames( segments, closed ) {
  10363. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10364. const normal = new Vector3();
  10365. const tangents = [];
  10366. const normals = [];
  10367. const binormals = [];
  10368. const vec = new Vector3();
  10369. const mat = new Matrix4();
  10370. // compute the tangent vectors for each segment on the curve
  10371. for ( let i = 0; i <= segments; i ++ ) {
  10372. const u = i / segments;
  10373. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10374. }
  10375. // select an initial normal vector perpendicular to the first tangent vector,
  10376. // and in the direction of the minimum tangent xyz component
  10377. normals[ 0 ] = new Vector3();
  10378. binormals[ 0 ] = new Vector3();
  10379. let min = Number.MAX_VALUE;
  10380. const tx = Math.abs( tangents[ 0 ].x );
  10381. const ty = Math.abs( tangents[ 0 ].y );
  10382. const tz = Math.abs( tangents[ 0 ].z );
  10383. if ( tx <= min ) {
  10384. min = tx;
  10385. normal.set( 1, 0, 0 );
  10386. }
  10387. if ( ty <= min ) {
  10388. min = ty;
  10389. normal.set( 0, 1, 0 );
  10390. }
  10391. if ( tz <= min ) {
  10392. normal.set( 0, 0, 1 );
  10393. }
  10394. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10395. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10396. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10397. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10398. for ( let i = 1; i <= segments; i ++ ) {
  10399. normals[ i ] = normals[ i - 1 ].clone();
  10400. binormals[ i ] = binormals[ i - 1 ].clone();
  10401. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10402. if ( vec.length() > Number.EPSILON ) {
  10403. vec.normalize();
  10404. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10405. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10406. }
  10407. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10408. }
  10409. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10410. if ( closed === true ) {
  10411. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10412. theta /= segments;
  10413. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10414. theta = - theta;
  10415. }
  10416. for ( let i = 1; i <= segments; i ++ ) {
  10417. // twist a little...
  10418. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10419. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10420. }
  10421. }
  10422. return {
  10423. tangents: tangents,
  10424. normals: normals,
  10425. binormals: binormals
  10426. };
  10427. }
  10428. clone() {
  10429. return new this.constructor().copy( this );
  10430. }
  10431. copy( source ) {
  10432. this.arcLengthDivisions = source.arcLengthDivisions;
  10433. return this;
  10434. }
  10435. toJSON() {
  10436. const data = {
  10437. metadata: {
  10438. version: 4.6,
  10439. type: 'Curve',
  10440. generator: 'Curve.toJSON'
  10441. }
  10442. };
  10443. data.arcLengthDivisions = this.arcLengthDivisions;
  10444. data.type = this.type;
  10445. return data;
  10446. }
  10447. fromJSON( json ) {
  10448. this.arcLengthDivisions = json.arcLengthDivisions;
  10449. return this;
  10450. }
  10451. }
  10452. class EllipseCurve extends Curve {
  10453. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10454. super();
  10455. this.isEllipseCurve = true;
  10456. this.type = 'EllipseCurve';
  10457. this.aX = aX;
  10458. this.aY = aY;
  10459. this.xRadius = xRadius;
  10460. this.yRadius = yRadius;
  10461. this.aStartAngle = aStartAngle;
  10462. this.aEndAngle = aEndAngle;
  10463. this.aClockwise = aClockwise;
  10464. this.aRotation = aRotation;
  10465. }
  10466. getPoint( t, optionalTarget = new Vector2() ) {
  10467. const point = optionalTarget;
  10468. const twoPi = Math.PI * 2;
  10469. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10470. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10471. // ensures that deltaAngle is 0 .. 2 PI
  10472. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10473. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10474. if ( deltaAngle < Number.EPSILON ) {
  10475. if ( samePoints ) {
  10476. deltaAngle = 0;
  10477. } else {
  10478. deltaAngle = twoPi;
  10479. }
  10480. }
  10481. if ( this.aClockwise === true && ! samePoints ) {
  10482. if ( deltaAngle === twoPi ) {
  10483. deltaAngle = - twoPi;
  10484. } else {
  10485. deltaAngle = deltaAngle - twoPi;
  10486. }
  10487. }
  10488. const angle = this.aStartAngle + t * deltaAngle;
  10489. let x = this.aX + this.xRadius * Math.cos( angle );
  10490. let y = this.aY + this.yRadius * Math.sin( angle );
  10491. if ( this.aRotation !== 0 ) {
  10492. const cos = Math.cos( this.aRotation );
  10493. const sin = Math.sin( this.aRotation );
  10494. const tx = x - this.aX;
  10495. const ty = y - this.aY;
  10496. // Rotate the point about the center of the ellipse.
  10497. x = tx * cos - ty * sin + this.aX;
  10498. y = tx * sin + ty * cos + this.aY;
  10499. }
  10500. return point.set( x, y );
  10501. }
  10502. copy( source ) {
  10503. super.copy( source );
  10504. this.aX = source.aX;
  10505. this.aY = source.aY;
  10506. this.xRadius = source.xRadius;
  10507. this.yRadius = source.yRadius;
  10508. this.aStartAngle = source.aStartAngle;
  10509. this.aEndAngle = source.aEndAngle;
  10510. this.aClockwise = source.aClockwise;
  10511. this.aRotation = source.aRotation;
  10512. return this;
  10513. }
  10514. toJSON() {
  10515. const data = super.toJSON();
  10516. data.aX = this.aX;
  10517. data.aY = this.aY;
  10518. data.xRadius = this.xRadius;
  10519. data.yRadius = this.yRadius;
  10520. data.aStartAngle = this.aStartAngle;
  10521. data.aEndAngle = this.aEndAngle;
  10522. data.aClockwise = this.aClockwise;
  10523. data.aRotation = this.aRotation;
  10524. return data;
  10525. }
  10526. fromJSON( json ) {
  10527. super.fromJSON( json );
  10528. this.aX = json.aX;
  10529. this.aY = json.aY;
  10530. this.xRadius = json.xRadius;
  10531. this.yRadius = json.yRadius;
  10532. this.aStartAngle = json.aStartAngle;
  10533. this.aEndAngle = json.aEndAngle;
  10534. this.aClockwise = json.aClockwise;
  10535. this.aRotation = json.aRotation;
  10536. return this;
  10537. }
  10538. }
  10539. class ArcCurve extends EllipseCurve {
  10540. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10541. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10542. this.isArcCurve = true;
  10543. this.type = 'ArcCurve';
  10544. }
  10545. }
  10546. /**
  10547. * Centripetal CatmullRom Curve - which is useful for avoiding
  10548. * cusps and self-intersections in non-uniform catmull rom curves.
  10549. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10550. *
  10551. * curve.type accepts centripetal(default), chordal and catmullrom
  10552. * curve.tension is used for catmullrom which defaults to 0.5
  10553. */
  10554. /*
  10555. Based on an optimized c++ solution in
  10556. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10557. - http://ideone.com/NoEbVM
  10558. This CubicPoly class could be used for reusing some variables and calculations,
  10559. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10560. which can be placed in CurveUtils.
  10561. */
  10562. function CubicPoly() {
  10563. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10564. /*
  10565. * Compute coefficients for a cubic polynomial
  10566. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10567. * such that
  10568. * p(0) = x0, p(1) = x1
  10569. * and
  10570. * p'(0) = t0, p'(1) = t1.
  10571. */
  10572. function init( x0, x1, t0, t1 ) {
  10573. c0 = x0;
  10574. c1 = t0;
  10575. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10576. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10577. }
  10578. return {
  10579. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10580. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10581. },
  10582. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10583. // compute tangents when parameterized in [t1,t2]
  10584. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10585. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10586. // rescale tangents for parametrization in [0,1]
  10587. t1 *= dt1;
  10588. t2 *= dt1;
  10589. init( x1, x2, t1, t2 );
  10590. },
  10591. calc: function ( t ) {
  10592. const t2 = t * t;
  10593. const t3 = t2 * t;
  10594. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10595. }
  10596. };
  10597. }
  10598. //
  10599. const tmp = /*@__PURE__*/ new Vector3();
  10600. const px = /*@__PURE__*/ new CubicPoly();
  10601. const py = /*@__PURE__*/ new CubicPoly();
  10602. const pz = /*@__PURE__*/ new CubicPoly();
  10603. class CatmullRomCurve3 extends Curve {
  10604. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10605. super();
  10606. this.isCatmullRomCurve3 = true;
  10607. this.type = 'CatmullRomCurve3';
  10608. this.points = points;
  10609. this.closed = closed;
  10610. this.curveType = curveType;
  10611. this.tension = tension;
  10612. }
  10613. getPoint( t, optionalTarget = new Vector3() ) {
  10614. const point = optionalTarget;
  10615. const points = this.points;
  10616. const l = points.length;
  10617. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10618. let intPoint = Math.floor( p );
  10619. let weight = p - intPoint;
  10620. if ( this.closed ) {
  10621. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10622. } else if ( weight === 0 && intPoint === l - 1 ) {
  10623. intPoint = l - 2;
  10624. weight = 1;
  10625. }
  10626. let p0, p3; // 4 points (p1 & p2 defined below)
  10627. if ( this.closed || intPoint > 0 ) {
  10628. p0 = points[ ( intPoint - 1 ) % l ];
  10629. } else {
  10630. // extrapolate first point
  10631. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10632. p0 = tmp;
  10633. }
  10634. const p1 = points[ intPoint % l ];
  10635. const p2 = points[ ( intPoint + 1 ) % l ];
  10636. if ( this.closed || intPoint + 2 < l ) {
  10637. p3 = points[ ( intPoint + 2 ) % l ];
  10638. } else {
  10639. // extrapolate last point
  10640. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10641. p3 = tmp;
  10642. }
  10643. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10644. // init Centripetal / Chordal Catmull-Rom
  10645. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10646. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10647. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10648. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10649. // safety check for repeated points
  10650. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10651. if ( dt0 < 1e-4 ) dt0 = dt1;
  10652. if ( dt2 < 1e-4 ) dt2 = dt1;
  10653. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10654. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10655. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10656. } else if ( this.curveType === 'catmullrom' ) {
  10657. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10658. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10659. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10660. }
  10661. point.set(
  10662. px.calc( weight ),
  10663. py.calc( weight ),
  10664. pz.calc( weight )
  10665. );
  10666. return point;
  10667. }
  10668. copy( source ) {
  10669. super.copy( source );
  10670. this.points = [];
  10671. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10672. const point = source.points[ i ];
  10673. this.points.push( point.clone() );
  10674. }
  10675. this.closed = source.closed;
  10676. this.curveType = source.curveType;
  10677. this.tension = source.tension;
  10678. return this;
  10679. }
  10680. toJSON() {
  10681. const data = super.toJSON();
  10682. data.points = [];
  10683. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10684. const point = this.points[ i ];
  10685. data.points.push( point.toArray() );
  10686. }
  10687. data.closed = this.closed;
  10688. data.curveType = this.curveType;
  10689. data.tension = this.tension;
  10690. return data;
  10691. }
  10692. fromJSON( json ) {
  10693. super.fromJSON( json );
  10694. this.points = [];
  10695. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10696. const point = json.points[ i ];
  10697. this.points.push( new Vector3().fromArray( point ) );
  10698. }
  10699. this.closed = json.closed;
  10700. this.curveType = json.curveType;
  10701. this.tension = json.tension;
  10702. return this;
  10703. }
  10704. }
  10705. /**
  10706. * Bezier Curves formulas obtained from
  10707. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10708. */
  10709. function CatmullRom( t, p0, p1, p2, p3 ) {
  10710. const v0 = ( p2 - p0 ) * 0.5;
  10711. const v1 = ( p3 - p1 ) * 0.5;
  10712. const t2 = t * t;
  10713. const t3 = t * t2;
  10714. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10715. }
  10716. //
  10717. function QuadraticBezierP0( t, p ) {
  10718. const k = 1 - t;
  10719. return k * k * p;
  10720. }
  10721. function QuadraticBezierP1( t, p ) {
  10722. return 2 * ( 1 - t ) * t * p;
  10723. }
  10724. function QuadraticBezierP2( t, p ) {
  10725. return t * t * p;
  10726. }
  10727. function QuadraticBezier( t, p0, p1, p2 ) {
  10728. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10729. QuadraticBezierP2( t, p2 );
  10730. }
  10731. //
  10732. function CubicBezierP0( t, p ) {
  10733. const k = 1 - t;
  10734. return k * k * k * p;
  10735. }
  10736. function CubicBezierP1( t, p ) {
  10737. const k = 1 - t;
  10738. return 3 * k * k * t * p;
  10739. }
  10740. function CubicBezierP2( t, p ) {
  10741. return 3 * ( 1 - t ) * t * t * p;
  10742. }
  10743. function CubicBezierP3( t, p ) {
  10744. return t * t * t * p;
  10745. }
  10746. function CubicBezier( t, p0, p1, p2, p3 ) {
  10747. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10748. CubicBezierP3( t, p3 );
  10749. }
  10750. class CubicBezierCurve extends Curve {
  10751. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10752. super();
  10753. this.isCubicBezierCurve = true;
  10754. this.type = 'CubicBezierCurve';
  10755. this.v0 = v0;
  10756. this.v1 = v1;
  10757. this.v2 = v2;
  10758. this.v3 = v3;
  10759. }
  10760. getPoint( t, optionalTarget = new Vector2() ) {
  10761. const point = optionalTarget;
  10762. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10763. point.set(
  10764. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10765. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10766. );
  10767. return point;
  10768. }
  10769. copy( source ) {
  10770. super.copy( source );
  10771. this.v0.copy( source.v0 );
  10772. this.v1.copy( source.v1 );
  10773. this.v2.copy( source.v2 );
  10774. this.v3.copy( source.v3 );
  10775. return this;
  10776. }
  10777. toJSON() {
  10778. const data = super.toJSON();
  10779. data.v0 = this.v0.toArray();
  10780. data.v1 = this.v1.toArray();
  10781. data.v2 = this.v2.toArray();
  10782. data.v3 = this.v3.toArray();
  10783. return data;
  10784. }
  10785. fromJSON( json ) {
  10786. super.fromJSON( json );
  10787. this.v0.fromArray( json.v0 );
  10788. this.v1.fromArray( json.v1 );
  10789. this.v2.fromArray( json.v2 );
  10790. this.v3.fromArray( json.v3 );
  10791. return this;
  10792. }
  10793. }
  10794. class CubicBezierCurve3 extends Curve {
  10795. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10796. super();
  10797. this.isCubicBezierCurve3 = true;
  10798. this.type = 'CubicBezierCurve3';
  10799. this.v0 = v0;
  10800. this.v1 = v1;
  10801. this.v2 = v2;
  10802. this.v3 = v3;
  10803. }
  10804. getPoint( t, optionalTarget = new Vector3() ) {
  10805. const point = optionalTarget;
  10806. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10807. point.set(
  10808. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10809. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10810. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10811. );
  10812. return point;
  10813. }
  10814. copy( source ) {
  10815. super.copy( source );
  10816. this.v0.copy( source.v0 );
  10817. this.v1.copy( source.v1 );
  10818. this.v2.copy( source.v2 );
  10819. this.v3.copy( source.v3 );
  10820. return this;
  10821. }
  10822. toJSON() {
  10823. const data = super.toJSON();
  10824. data.v0 = this.v0.toArray();
  10825. data.v1 = this.v1.toArray();
  10826. data.v2 = this.v2.toArray();
  10827. data.v3 = this.v3.toArray();
  10828. return data;
  10829. }
  10830. fromJSON( json ) {
  10831. super.fromJSON( json );
  10832. this.v0.fromArray( json.v0 );
  10833. this.v1.fromArray( json.v1 );
  10834. this.v2.fromArray( json.v2 );
  10835. this.v3.fromArray( json.v3 );
  10836. return this;
  10837. }
  10838. }
  10839. class LineCurve extends Curve {
  10840. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10841. super();
  10842. this.isLineCurve = true;
  10843. this.type = 'LineCurve';
  10844. this.v1 = v1;
  10845. this.v2 = v2;
  10846. }
  10847. getPoint( t, optionalTarget = new Vector2() ) {
  10848. const point = optionalTarget;
  10849. if ( t === 1 ) {
  10850. point.copy( this.v2 );
  10851. } else {
  10852. point.copy( this.v2 ).sub( this.v1 );
  10853. point.multiplyScalar( t ).add( this.v1 );
  10854. }
  10855. return point;
  10856. }
  10857. // Line curve is linear, so we can overwrite default getPointAt
  10858. getPointAt( u, optionalTarget ) {
  10859. return this.getPoint( u, optionalTarget );
  10860. }
  10861. getTangent( t, optionalTarget = new Vector2() ) {
  10862. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10863. }
  10864. getTangentAt( u, optionalTarget ) {
  10865. return this.getTangent( u, optionalTarget );
  10866. }
  10867. copy( source ) {
  10868. super.copy( source );
  10869. this.v1.copy( source.v1 );
  10870. this.v2.copy( source.v2 );
  10871. return this;
  10872. }
  10873. toJSON() {
  10874. const data = super.toJSON();
  10875. data.v1 = this.v1.toArray();
  10876. data.v2 = this.v2.toArray();
  10877. return data;
  10878. }
  10879. fromJSON( json ) {
  10880. super.fromJSON( json );
  10881. this.v1.fromArray( json.v1 );
  10882. this.v2.fromArray( json.v2 );
  10883. return this;
  10884. }
  10885. }
  10886. class LineCurve3 extends Curve {
  10887. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10888. super();
  10889. this.isLineCurve3 = true;
  10890. this.type = 'LineCurve3';
  10891. this.v1 = v1;
  10892. this.v2 = v2;
  10893. }
  10894. getPoint( t, optionalTarget = new Vector3() ) {
  10895. const point = optionalTarget;
  10896. if ( t === 1 ) {
  10897. point.copy( this.v2 );
  10898. } else {
  10899. point.copy( this.v2 ).sub( this.v1 );
  10900. point.multiplyScalar( t ).add( this.v1 );
  10901. }
  10902. return point;
  10903. }
  10904. // Line curve is linear, so we can overwrite default getPointAt
  10905. getPointAt( u, optionalTarget ) {
  10906. return this.getPoint( u, optionalTarget );
  10907. }
  10908. getTangent( t, optionalTarget = new Vector3() ) {
  10909. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10910. }
  10911. getTangentAt( u, optionalTarget ) {
  10912. return this.getTangent( u, optionalTarget );
  10913. }
  10914. copy( source ) {
  10915. super.copy( source );
  10916. this.v1.copy( source.v1 );
  10917. this.v2.copy( source.v2 );
  10918. return this;
  10919. }
  10920. toJSON() {
  10921. const data = super.toJSON();
  10922. data.v1 = this.v1.toArray();
  10923. data.v2 = this.v2.toArray();
  10924. return data;
  10925. }
  10926. fromJSON( json ) {
  10927. super.fromJSON( json );
  10928. this.v1.fromArray( json.v1 );
  10929. this.v2.fromArray( json.v2 );
  10930. return this;
  10931. }
  10932. }
  10933. class QuadraticBezierCurve extends Curve {
  10934. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10935. super();
  10936. this.isQuadraticBezierCurve = true;
  10937. this.type = 'QuadraticBezierCurve';
  10938. this.v0 = v0;
  10939. this.v1 = v1;
  10940. this.v2 = v2;
  10941. }
  10942. getPoint( t, optionalTarget = new Vector2() ) {
  10943. const point = optionalTarget;
  10944. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10945. point.set(
  10946. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10947. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10948. );
  10949. return point;
  10950. }
  10951. copy( source ) {
  10952. super.copy( source );
  10953. this.v0.copy( source.v0 );
  10954. this.v1.copy( source.v1 );
  10955. this.v2.copy( source.v2 );
  10956. return this;
  10957. }
  10958. toJSON() {
  10959. const data = super.toJSON();
  10960. data.v0 = this.v0.toArray();
  10961. data.v1 = this.v1.toArray();
  10962. data.v2 = this.v2.toArray();
  10963. return data;
  10964. }
  10965. fromJSON( json ) {
  10966. super.fromJSON( json );
  10967. this.v0.fromArray( json.v0 );
  10968. this.v1.fromArray( json.v1 );
  10969. this.v2.fromArray( json.v2 );
  10970. return this;
  10971. }
  10972. }
  10973. class QuadraticBezierCurve3 extends Curve {
  10974. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10975. super();
  10976. this.isQuadraticBezierCurve3 = true;
  10977. this.type = 'QuadraticBezierCurve3';
  10978. this.v0 = v0;
  10979. this.v1 = v1;
  10980. this.v2 = v2;
  10981. }
  10982. getPoint( t, optionalTarget = new Vector3() ) {
  10983. const point = optionalTarget;
  10984. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10985. point.set(
  10986. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10987. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10988. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10989. );
  10990. return point;
  10991. }
  10992. copy( source ) {
  10993. super.copy( source );
  10994. this.v0.copy( source.v0 );
  10995. this.v1.copy( source.v1 );
  10996. this.v2.copy( source.v2 );
  10997. return this;
  10998. }
  10999. toJSON() {
  11000. const data = super.toJSON();
  11001. data.v0 = this.v0.toArray();
  11002. data.v1 = this.v1.toArray();
  11003. data.v2 = this.v2.toArray();
  11004. return data;
  11005. }
  11006. fromJSON( json ) {
  11007. super.fromJSON( json );
  11008. this.v0.fromArray( json.v0 );
  11009. this.v1.fromArray( json.v1 );
  11010. this.v2.fromArray( json.v2 );
  11011. return this;
  11012. }
  11013. }
  11014. class SplineCurve extends Curve {
  11015. constructor( points = [] ) {
  11016. super();
  11017. this.isSplineCurve = true;
  11018. this.type = 'SplineCurve';
  11019. this.points = points;
  11020. }
  11021. getPoint( t, optionalTarget = new Vector2() ) {
  11022. const point = optionalTarget;
  11023. const points = this.points;
  11024. const p = ( points.length - 1 ) * t;
  11025. const intPoint = Math.floor( p );
  11026. const weight = p - intPoint;
  11027. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11028. const p1 = points[ intPoint ];
  11029. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11030. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11031. point.set(
  11032. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11033. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11034. );
  11035. return point;
  11036. }
  11037. copy( source ) {
  11038. super.copy( source );
  11039. this.points = [];
  11040. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11041. const point = source.points[ i ];
  11042. this.points.push( point.clone() );
  11043. }
  11044. return this;
  11045. }
  11046. toJSON() {
  11047. const data = super.toJSON();
  11048. data.points = [];
  11049. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11050. const point = this.points[ i ];
  11051. data.points.push( point.toArray() );
  11052. }
  11053. return data;
  11054. }
  11055. fromJSON( json ) {
  11056. super.fromJSON( json );
  11057. this.points = [];
  11058. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11059. const point = json.points[ i ];
  11060. this.points.push( new Vector2().fromArray( point ) );
  11061. }
  11062. return this;
  11063. }
  11064. }
  11065. var Curves = /*#__PURE__*/Object.freeze({
  11066. __proto__: null,
  11067. ArcCurve: ArcCurve,
  11068. CatmullRomCurve3: CatmullRomCurve3,
  11069. CubicBezierCurve: CubicBezierCurve,
  11070. CubicBezierCurve3: CubicBezierCurve3,
  11071. EllipseCurve: EllipseCurve,
  11072. LineCurve: LineCurve,
  11073. LineCurve3: LineCurve3,
  11074. QuadraticBezierCurve: QuadraticBezierCurve,
  11075. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11076. SplineCurve: SplineCurve
  11077. });
  11078. /**************************************************************
  11079. * Curved Path - a curve path is simply a array of connected
  11080. * curves, but retains the api of a curve
  11081. **************************************************************/
  11082. class CurvePath extends Curve {
  11083. constructor() {
  11084. super();
  11085. this.type = 'CurvePath';
  11086. this.curves = [];
  11087. this.autoClose = false; // Automatically closes the path
  11088. }
  11089. add( curve ) {
  11090. this.curves.push( curve );
  11091. }
  11092. closePath() {
  11093. // Add a line curve if start and end of lines are not connected
  11094. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11095. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11096. if ( ! startPoint.equals( endPoint ) ) {
  11097. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11098. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11099. }
  11100. return this;
  11101. }
  11102. // To get accurate point with reference to
  11103. // entire path distance at time t,
  11104. // following has to be done:
  11105. // 1. Length of each sub path have to be known
  11106. // 2. Locate and identify type of curve
  11107. // 3. Get t for the curve
  11108. // 4. Return curve.getPointAt(t')
  11109. getPoint( t, optionalTarget ) {
  11110. const d = t * this.getLength();
  11111. const curveLengths = this.getCurveLengths();
  11112. let i = 0;
  11113. // To think about boundaries points.
  11114. while ( i < curveLengths.length ) {
  11115. if ( curveLengths[ i ] >= d ) {
  11116. const diff = curveLengths[ i ] - d;
  11117. const curve = this.curves[ i ];
  11118. const segmentLength = curve.getLength();
  11119. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11120. return curve.getPointAt( u, optionalTarget );
  11121. }
  11122. i ++;
  11123. }
  11124. return null;
  11125. // loop where sum != 0, sum > d , sum+1 <d
  11126. }
  11127. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11128. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11129. // getPoint() depends on getLength
  11130. getLength() {
  11131. const lens = this.getCurveLengths();
  11132. return lens[ lens.length - 1 ];
  11133. }
  11134. // cacheLengths must be recalculated.
  11135. updateArcLengths() {
  11136. this.needsUpdate = true;
  11137. this.cacheLengths = null;
  11138. this.getCurveLengths();
  11139. }
  11140. // Compute lengths and cache them
  11141. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11142. getCurveLengths() {
  11143. // We use cache values if curves and cache array are same length
  11144. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11145. return this.cacheLengths;
  11146. }
  11147. // Get length of sub-curve
  11148. // Push sums into cached array
  11149. const lengths = [];
  11150. let sums = 0;
  11151. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11152. sums += this.curves[ i ].getLength();
  11153. lengths.push( sums );
  11154. }
  11155. this.cacheLengths = lengths;
  11156. return lengths;
  11157. }
  11158. getSpacedPoints( divisions = 40 ) {
  11159. const points = [];
  11160. for ( let i = 0; i <= divisions; i ++ ) {
  11161. points.push( this.getPoint( i / divisions ) );
  11162. }
  11163. if ( this.autoClose ) {
  11164. points.push( points[ 0 ] );
  11165. }
  11166. return points;
  11167. }
  11168. getPoints( divisions = 12 ) {
  11169. const points = [];
  11170. let last;
  11171. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11172. const curve = curves[ i ];
  11173. const resolution = curve.isEllipseCurve ? divisions * 2
  11174. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11175. : curve.isSplineCurve ? divisions * curve.points.length
  11176. : divisions;
  11177. const pts = curve.getPoints( resolution );
  11178. for ( let j = 0; j < pts.length; j ++ ) {
  11179. const point = pts[ j ];
  11180. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11181. points.push( point );
  11182. last = point;
  11183. }
  11184. }
  11185. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11186. points.push( points[ 0 ] );
  11187. }
  11188. return points;
  11189. }
  11190. copy( source ) {
  11191. super.copy( source );
  11192. this.curves = [];
  11193. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11194. const curve = source.curves[ i ];
  11195. this.curves.push( curve.clone() );
  11196. }
  11197. this.autoClose = source.autoClose;
  11198. return this;
  11199. }
  11200. toJSON() {
  11201. const data = super.toJSON();
  11202. data.autoClose = this.autoClose;
  11203. data.curves = [];
  11204. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11205. const curve = this.curves[ i ];
  11206. data.curves.push( curve.toJSON() );
  11207. }
  11208. return data;
  11209. }
  11210. fromJSON( json ) {
  11211. super.fromJSON( json );
  11212. this.autoClose = json.autoClose;
  11213. this.curves = [];
  11214. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11215. const curve = json.curves[ i ];
  11216. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11217. }
  11218. return this;
  11219. }
  11220. }
  11221. class Path extends CurvePath {
  11222. constructor( points ) {
  11223. super();
  11224. this.type = 'Path';
  11225. this.currentPoint = new Vector2();
  11226. if ( points ) {
  11227. this.setFromPoints( points );
  11228. }
  11229. }
  11230. setFromPoints( points ) {
  11231. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11232. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11233. this.lineTo( points[ i ].x, points[ i ].y );
  11234. }
  11235. return this;
  11236. }
  11237. moveTo( x, y ) {
  11238. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11239. return this;
  11240. }
  11241. lineTo( x, y ) {
  11242. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11243. this.curves.push( curve );
  11244. this.currentPoint.set( x, y );
  11245. return this;
  11246. }
  11247. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11248. const curve = new QuadraticBezierCurve(
  11249. this.currentPoint.clone(),
  11250. new Vector2( aCPx, aCPy ),
  11251. new Vector2( aX, aY )
  11252. );
  11253. this.curves.push( curve );
  11254. this.currentPoint.set( aX, aY );
  11255. return this;
  11256. }
  11257. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11258. const curve = new CubicBezierCurve(
  11259. this.currentPoint.clone(),
  11260. new Vector2( aCP1x, aCP1y ),
  11261. new Vector2( aCP2x, aCP2y ),
  11262. new Vector2( aX, aY )
  11263. );
  11264. this.curves.push( curve );
  11265. this.currentPoint.set( aX, aY );
  11266. return this;
  11267. }
  11268. splineThru( pts /*Array of Vector*/ ) {
  11269. const npts = [ this.currentPoint.clone() ].concat( pts );
  11270. const curve = new SplineCurve( npts );
  11271. this.curves.push( curve );
  11272. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11273. return this;
  11274. }
  11275. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11276. const x0 = this.currentPoint.x;
  11277. const y0 = this.currentPoint.y;
  11278. this.absarc( aX + x0, aY + y0, aRadius,
  11279. aStartAngle, aEndAngle, aClockwise );
  11280. return this;
  11281. }
  11282. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11283. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11284. return this;
  11285. }
  11286. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11287. const x0 = this.currentPoint.x;
  11288. const y0 = this.currentPoint.y;
  11289. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11290. return this;
  11291. }
  11292. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11293. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11294. if ( this.curves.length > 0 ) {
  11295. // if a previous curve is present, attempt to join
  11296. const firstPoint = curve.getPoint( 0 );
  11297. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11298. this.lineTo( firstPoint.x, firstPoint.y );
  11299. }
  11300. }
  11301. this.curves.push( curve );
  11302. const lastPoint = curve.getPoint( 1 );
  11303. this.currentPoint.copy( lastPoint );
  11304. return this;
  11305. }
  11306. copy( source ) {
  11307. super.copy( source );
  11308. this.currentPoint.copy( source.currentPoint );
  11309. return this;
  11310. }
  11311. toJSON() {
  11312. const data = super.toJSON();
  11313. data.currentPoint = this.currentPoint.toArray();
  11314. return data;
  11315. }
  11316. fromJSON( json ) {
  11317. super.fromJSON( json );
  11318. this.currentPoint.fromArray( json.currentPoint );
  11319. return this;
  11320. }
  11321. }
  11322. class LatheGeometry extends BufferGeometry {
  11323. 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 ) {
  11324. super();
  11325. this.type = 'LatheGeometry';
  11326. this.parameters = {
  11327. points: points,
  11328. segments: segments,
  11329. phiStart: phiStart,
  11330. phiLength: phiLength
  11331. };
  11332. segments = Math.floor( segments );
  11333. // clamp phiLength so it's in range of [ 0, 2PI ]
  11334. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11335. // buffers
  11336. const indices = [];
  11337. const vertices = [];
  11338. const uvs = [];
  11339. const initNormals = [];
  11340. const normals = [];
  11341. // helper variables
  11342. const inverseSegments = 1.0 / segments;
  11343. const vertex = new Vector3();
  11344. const uv = new Vector2();
  11345. const normal = new Vector3();
  11346. const curNormal = new Vector3();
  11347. const prevNormal = new Vector3();
  11348. let dx = 0;
  11349. let dy = 0;
  11350. // pre-compute normals for initial "meridian"
  11351. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11352. switch ( j ) {
  11353. case 0: // special handling for 1st vertex on path
  11354. dx = points[ j + 1 ].x - points[ j ].x;
  11355. dy = points[ j + 1 ].y - points[ j ].y;
  11356. normal.x = dy * 1.0;
  11357. normal.y = - dx;
  11358. normal.z = dy * 0.0;
  11359. prevNormal.copy( normal );
  11360. normal.normalize();
  11361. initNormals.push( normal.x, normal.y, normal.z );
  11362. break;
  11363. case ( points.length - 1 ): // special handling for last Vertex on path
  11364. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11365. break;
  11366. default: // default handling for all vertices in between
  11367. dx = points[ j + 1 ].x - points[ j ].x;
  11368. dy = points[ j + 1 ].y - points[ j ].y;
  11369. normal.x = dy * 1.0;
  11370. normal.y = - dx;
  11371. normal.z = dy * 0.0;
  11372. curNormal.copy( normal );
  11373. normal.x += prevNormal.x;
  11374. normal.y += prevNormal.y;
  11375. normal.z += prevNormal.z;
  11376. normal.normalize();
  11377. initNormals.push( normal.x, normal.y, normal.z );
  11378. prevNormal.copy( curNormal );
  11379. }
  11380. }
  11381. // generate vertices, uvs and normals
  11382. for ( let i = 0; i <= segments; i ++ ) {
  11383. const phi = phiStart + i * inverseSegments * phiLength;
  11384. const sin = Math.sin( phi );
  11385. const cos = Math.cos( phi );
  11386. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11387. // vertex
  11388. vertex.x = points[ j ].x * sin;
  11389. vertex.y = points[ j ].y;
  11390. vertex.z = points[ j ].x * cos;
  11391. vertices.push( vertex.x, vertex.y, vertex.z );
  11392. // uv
  11393. uv.x = i / segments;
  11394. uv.y = j / ( points.length - 1 );
  11395. uvs.push( uv.x, uv.y );
  11396. // normal
  11397. const x = initNormals[ 3 * j + 0 ] * sin;
  11398. const y = initNormals[ 3 * j + 1 ];
  11399. const z = initNormals[ 3 * j + 0 ] * cos;
  11400. normals.push( x, y, z );
  11401. }
  11402. }
  11403. // indices
  11404. for ( let i = 0; i < segments; i ++ ) {
  11405. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11406. const base = j + i * points.length;
  11407. const a = base;
  11408. const b = base + points.length;
  11409. const c = base + points.length + 1;
  11410. const d = base + 1;
  11411. // faces
  11412. indices.push( a, b, d );
  11413. indices.push( c, d, b );
  11414. }
  11415. }
  11416. // build geometry
  11417. this.setIndex( indices );
  11418. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11419. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11420. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11421. }
  11422. copy( source ) {
  11423. super.copy( source );
  11424. this.parameters = Object.assign( {}, source.parameters );
  11425. return this;
  11426. }
  11427. static fromJSON( data ) {
  11428. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11429. }
  11430. }
  11431. class CapsuleGeometry extends LatheGeometry {
  11432. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11433. const path = new Path();
  11434. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11435. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11436. super( path.getPoints( capSegments ), radialSegments );
  11437. this.type = 'CapsuleGeometry';
  11438. this.parameters = {
  11439. radius: radius,
  11440. length: length,
  11441. capSegments: capSegments,
  11442. radialSegments: radialSegments,
  11443. };
  11444. }
  11445. static fromJSON( data ) {
  11446. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11447. }
  11448. }
  11449. class CircleGeometry extends BufferGeometry {
  11450. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11451. super();
  11452. this.type = 'CircleGeometry';
  11453. this.parameters = {
  11454. radius: radius,
  11455. segments: segments,
  11456. thetaStart: thetaStart,
  11457. thetaLength: thetaLength
  11458. };
  11459. segments = Math.max( 3, segments );
  11460. // buffers
  11461. const indices = [];
  11462. const vertices = [];
  11463. const normals = [];
  11464. const uvs = [];
  11465. // helper variables
  11466. const vertex = new Vector3();
  11467. const uv = new Vector2();
  11468. // center point
  11469. vertices.push( 0, 0, 0 );
  11470. normals.push( 0, 0, 1 );
  11471. uvs.push( 0.5, 0.5 );
  11472. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11473. const segment = thetaStart + s / segments * thetaLength;
  11474. // vertex
  11475. vertex.x = radius * Math.cos( segment );
  11476. vertex.y = radius * Math.sin( segment );
  11477. vertices.push( vertex.x, vertex.y, vertex.z );
  11478. // normal
  11479. normals.push( 0, 0, 1 );
  11480. // uvs
  11481. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11482. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11483. uvs.push( uv.x, uv.y );
  11484. }
  11485. // indices
  11486. for ( let i = 1; i <= segments; i ++ ) {
  11487. indices.push( i, i + 1, 0 );
  11488. }
  11489. // build geometry
  11490. this.setIndex( indices );
  11491. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11492. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11493. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11494. }
  11495. copy( source ) {
  11496. super.copy( source );
  11497. this.parameters = Object.assign( {}, source.parameters );
  11498. return this;
  11499. }
  11500. static fromJSON( data ) {
  11501. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11502. }
  11503. }
  11504. class CylinderGeometry extends BufferGeometry {
  11505. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11506. super();
  11507. this.type = 'CylinderGeometry';
  11508. this.parameters = {
  11509. radiusTop: radiusTop,
  11510. radiusBottom: radiusBottom,
  11511. height: height,
  11512. radialSegments: radialSegments,
  11513. heightSegments: heightSegments,
  11514. openEnded: openEnded,
  11515. thetaStart: thetaStart,
  11516. thetaLength: thetaLength
  11517. };
  11518. const scope = this;
  11519. radialSegments = Math.floor( radialSegments );
  11520. heightSegments = Math.floor( heightSegments );
  11521. // buffers
  11522. const indices = [];
  11523. const vertices = [];
  11524. const normals = [];
  11525. const uvs = [];
  11526. // helper variables
  11527. let index = 0;
  11528. const indexArray = [];
  11529. const halfHeight = height / 2;
  11530. let groupStart = 0;
  11531. // generate geometry
  11532. generateTorso();
  11533. if ( openEnded === false ) {
  11534. if ( radiusTop > 0 ) generateCap( true );
  11535. if ( radiusBottom > 0 ) generateCap( false );
  11536. }
  11537. // build geometry
  11538. this.setIndex( indices );
  11539. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11540. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11541. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11542. function generateTorso() {
  11543. const normal = new Vector3();
  11544. const vertex = new Vector3();
  11545. let groupCount = 0;
  11546. // this will be used to calculate the normal
  11547. const slope = ( radiusBottom - radiusTop ) / height;
  11548. // generate vertices, normals and uvs
  11549. for ( let y = 0; y <= heightSegments; y ++ ) {
  11550. const indexRow = [];
  11551. const v = y / heightSegments;
  11552. // calculate the radius of the current row
  11553. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11554. for ( let x = 0; x <= radialSegments; x ++ ) {
  11555. const u = x / radialSegments;
  11556. const theta = u * thetaLength + thetaStart;
  11557. const sinTheta = Math.sin( theta );
  11558. const cosTheta = Math.cos( theta );
  11559. // vertex
  11560. vertex.x = radius * sinTheta;
  11561. vertex.y = - v * height + halfHeight;
  11562. vertex.z = radius * cosTheta;
  11563. vertices.push( vertex.x, vertex.y, vertex.z );
  11564. // normal
  11565. normal.set( sinTheta, slope, cosTheta ).normalize();
  11566. normals.push( normal.x, normal.y, normal.z );
  11567. // uv
  11568. uvs.push( u, 1 - v );
  11569. // save index of vertex in respective row
  11570. indexRow.push( index ++ );
  11571. }
  11572. // now save vertices of the row in our index array
  11573. indexArray.push( indexRow );
  11574. }
  11575. // generate indices
  11576. for ( let x = 0; x < radialSegments; x ++ ) {
  11577. for ( let y = 0; y < heightSegments; y ++ ) {
  11578. // we use the index array to access the correct indices
  11579. const a = indexArray[ y ][ x ];
  11580. const b = indexArray[ y + 1 ][ x ];
  11581. const c = indexArray[ y + 1 ][ x + 1 ];
  11582. const d = indexArray[ y ][ x + 1 ];
  11583. // faces
  11584. if ( radiusTop > 0 ) {
  11585. indices.push( a, b, d );
  11586. groupCount += 3;
  11587. }
  11588. if ( radiusBottom > 0 ) {
  11589. indices.push( b, c, d );
  11590. groupCount += 3;
  11591. }
  11592. }
  11593. }
  11594. // add a group to the geometry. this will ensure multi material support
  11595. scope.addGroup( groupStart, groupCount, 0 );
  11596. // calculate new start value for groups
  11597. groupStart += groupCount;
  11598. }
  11599. function generateCap( top ) {
  11600. // save the index of the first center vertex
  11601. const centerIndexStart = index;
  11602. const uv = new Vector2();
  11603. const vertex = new Vector3();
  11604. let groupCount = 0;
  11605. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11606. const sign = ( top === true ) ? 1 : - 1;
  11607. // first we generate the center vertex data of the cap.
  11608. // because the geometry needs one set of uvs per face,
  11609. // we must generate a center vertex per face/segment
  11610. for ( let x = 1; x <= radialSegments; x ++ ) {
  11611. // vertex
  11612. vertices.push( 0, halfHeight * sign, 0 );
  11613. // normal
  11614. normals.push( 0, sign, 0 );
  11615. // uv
  11616. uvs.push( 0.5, 0.5 );
  11617. // increase index
  11618. index ++;
  11619. }
  11620. // save the index of the last center vertex
  11621. const centerIndexEnd = index;
  11622. // now we generate the surrounding vertices, normals and uvs
  11623. for ( let x = 0; x <= radialSegments; x ++ ) {
  11624. const u = x / radialSegments;
  11625. const theta = u * thetaLength + thetaStart;
  11626. const cosTheta = Math.cos( theta );
  11627. const sinTheta = Math.sin( theta );
  11628. // vertex
  11629. vertex.x = radius * sinTheta;
  11630. vertex.y = halfHeight * sign;
  11631. vertex.z = radius * cosTheta;
  11632. vertices.push( vertex.x, vertex.y, vertex.z );
  11633. // normal
  11634. normals.push( 0, sign, 0 );
  11635. // uv
  11636. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11637. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11638. uvs.push( uv.x, uv.y );
  11639. // increase index
  11640. index ++;
  11641. }
  11642. // generate indices
  11643. for ( let x = 0; x < radialSegments; x ++ ) {
  11644. const c = centerIndexStart + x;
  11645. const i = centerIndexEnd + x;
  11646. if ( top === true ) {
  11647. // face top
  11648. indices.push( i, i + 1, c );
  11649. } else {
  11650. // face bottom
  11651. indices.push( i + 1, i, c );
  11652. }
  11653. groupCount += 3;
  11654. }
  11655. // add a group to the geometry. this will ensure multi material support
  11656. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11657. // calculate new start value for groups
  11658. groupStart += groupCount;
  11659. }
  11660. }
  11661. copy( source ) {
  11662. super.copy( source );
  11663. this.parameters = Object.assign( {}, source.parameters );
  11664. return this;
  11665. }
  11666. static fromJSON( data ) {
  11667. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11668. }
  11669. }
  11670. class ConeGeometry extends CylinderGeometry {
  11671. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11672. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11673. this.type = 'ConeGeometry';
  11674. this.parameters = {
  11675. radius: radius,
  11676. height: height,
  11677. radialSegments: radialSegments,
  11678. heightSegments: heightSegments,
  11679. openEnded: openEnded,
  11680. thetaStart: thetaStart,
  11681. thetaLength: thetaLength
  11682. };
  11683. }
  11684. static fromJSON( data ) {
  11685. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11686. }
  11687. }
  11688. class PolyhedronGeometry extends BufferGeometry {
  11689. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11690. super();
  11691. this.type = 'PolyhedronGeometry';
  11692. this.parameters = {
  11693. vertices: vertices,
  11694. indices: indices,
  11695. radius: radius,
  11696. detail: detail
  11697. };
  11698. // default buffer data
  11699. const vertexBuffer = [];
  11700. const uvBuffer = [];
  11701. // the subdivision creates the vertex buffer data
  11702. subdivide( detail );
  11703. // all vertices should lie on a conceptual sphere with a given radius
  11704. applyRadius( radius );
  11705. // finally, create the uv data
  11706. generateUVs();
  11707. // build non-indexed geometry
  11708. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11709. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11710. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11711. if ( detail === 0 ) {
  11712. this.computeVertexNormals(); // flat normals
  11713. } else {
  11714. this.normalizeNormals(); // smooth normals
  11715. }
  11716. // helper functions
  11717. function subdivide( detail ) {
  11718. const a = new Vector3();
  11719. const b = new Vector3();
  11720. const c = new Vector3();
  11721. // iterate over all faces and apply a subdivision with the given detail value
  11722. for ( let i = 0; i < indices.length; i += 3 ) {
  11723. // get the vertices of the face
  11724. getVertexByIndex( indices[ i + 0 ], a );
  11725. getVertexByIndex( indices[ i + 1 ], b );
  11726. getVertexByIndex( indices[ i + 2 ], c );
  11727. // perform subdivision
  11728. subdivideFace( a, b, c, detail );
  11729. }
  11730. }
  11731. function subdivideFace( a, b, c, detail ) {
  11732. const cols = detail + 1;
  11733. // we use this multidimensional array as a data structure for creating the subdivision
  11734. const v = [];
  11735. // construct all of the vertices for this subdivision
  11736. for ( let i = 0; i <= cols; i ++ ) {
  11737. v[ i ] = [];
  11738. const aj = a.clone().lerp( c, i / cols );
  11739. const bj = b.clone().lerp( c, i / cols );
  11740. const rows = cols - i;
  11741. for ( let j = 0; j <= rows; j ++ ) {
  11742. if ( j === 0 && i === cols ) {
  11743. v[ i ][ j ] = aj;
  11744. } else {
  11745. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11746. }
  11747. }
  11748. }
  11749. // construct all of the faces
  11750. for ( let i = 0; i < cols; i ++ ) {
  11751. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11752. const k = Math.floor( j / 2 );
  11753. if ( j % 2 === 0 ) {
  11754. pushVertex( v[ i ][ k + 1 ] );
  11755. pushVertex( v[ i + 1 ][ k ] );
  11756. pushVertex( v[ i ][ k ] );
  11757. } else {
  11758. pushVertex( v[ i ][ k + 1 ] );
  11759. pushVertex( v[ i + 1 ][ k + 1 ] );
  11760. pushVertex( v[ i + 1 ][ k ] );
  11761. }
  11762. }
  11763. }
  11764. }
  11765. function applyRadius( radius ) {
  11766. const vertex = new Vector3();
  11767. // iterate over the entire buffer and apply the radius to each vertex
  11768. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11769. vertex.x = vertexBuffer[ i + 0 ];
  11770. vertex.y = vertexBuffer[ i + 1 ];
  11771. vertex.z = vertexBuffer[ i + 2 ];
  11772. vertex.normalize().multiplyScalar( radius );
  11773. vertexBuffer[ i + 0 ] = vertex.x;
  11774. vertexBuffer[ i + 1 ] = vertex.y;
  11775. vertexBuffer[ i + 2 ] = vertex.z;
  11776. }
  11777. }
  11778. function generateUVs() {
  11779. const vertex = new Vector3();
  11780. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11781. vertex.x = vertexBuffer[ i + 0 ];
  11782. vertex.y = vertexBuffer[ i + 1 ];
  11783. vertex.z = vertexBuffer[ i + 2 ];
  11784. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11785. const v = inclination( vertex ) / Math.PI + 0.5;
  11786. uvBuffer.push( u, 1 - v );
  11787. }
  11788. correctUVs();
  11789. correctSeam();
  11790. }
  11791. function correctSeam() {
  11792. // handle case when face straddles the seam, see #3269
  11793. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11794. // uv data of a single face
  11795. const x0 = uvBuffer[ i + 0 ];
  11796. const x1 = uvBuffer[ i + 2 ];
  11797. const x2 = uvBuffer[ i + 4 ];
  11798. const max = Math.max( x0, x1, x2 );
  11799. const min = Math.min( x0, x1, x2 );
  11800. // 0.9 is somewhat arbitrary
  11801. if ( max > 0.9 && min < 0.1 ) {
  11802. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11803. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11804. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11805. }
  11806. }
  11807. }
  11808. function pushVertex( vertex ) {
  11809. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11810. }
  11811. function getVertexByIndex( index, vertex ) {
  11812. const stride = index * 3;
  11813. vertex.x = vertices[ stride + 0 ];
  11814. vertex.y = vertices[ stride + 1 ];
  11815. vertex.z = vertices[ stride + 2 ];
  11816. }
  11817. function correctUVs() {
  11818. const a = new Vector3();
  11819. const b = new Vector3();
  11820. const c = new Vector3();
  11821. const centroid = new Vector3();
  11822. const uvA = new Vector2();
  11823. const uvB = new Vector2();
  11824. const uvC = new Vector2();
  11825. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11826. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11827. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11828. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11829. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11830. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11831. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11832. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11833. const azi = azimuth( centroid );
  11834. correctUV( uvA, j + 0, a, azi );
  11835. correctUV( uvB, j + 2, b, azi );
  11836. correctUV( uvC, j + 4, c, azi );
  11837. }
  11838. }
  11839. function correctUV( uv, stride, vector, azimuth ) {
  11840. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11841. uvBuffer[ stride ] = uv.x - 1;
  11842. }
  11843. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11844. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11845. }
  11846. }
  11847. // Angle around the Y axis, counter-clockwise when looking from above.
  11848. function azimuth( vector ) {
  11849. return Math.atan2( vector.z, - vector.x );
  11850. }
  11851. // Angle above the XZ plane.
  11852. function inclination( vector ) {
  11853. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11854. }
  11855. }
  11856. copy( source ) {
  11857. super.copy( source );
  11858. this.parameters = Object.assign( {}, source.parameters );
  11859. return this;
  11860. }
  11861. static fromJSON( data ) {
  11862. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11863. }
  11864. }
  11865. class DodecahedronGeometry extends PolyhedronGeometry {
  11866. constructor( radius = 1, detail = 0 ) {
  11867. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11868. const r = 1 / t;
  11869. const vertices = [
  11870. // (±1, ±1, ±1)
  11871. - 1, - 1, - 1, - 1, - 1, 1,
  11872. - 1, 1, - 1, - 1, 1, 1,
  11873. 1, - 1, - 1, 1, - 1, 1,
  11874. 1, 1, - 1, 1, 1, 1,
  11875. // (0, ±1/φ, ±φ)
  11876. 0, - r, - t, 0, - r, t,
  11877. 0, r, - t, 0, r, t,
  11878. // (±1/φ, ±φ, 0)
  11879. - r, - t, 0, - r, t, 0,
  11880. r, - t, 0, r, t, 0,
  11881. // (±φ, 0, ±1/φ)
  11882. - t, 0, - r, t, 0, - r,
  11883. - t, 0, r, t, 0, r
  11884. ];
  11885. const indices = [
  11886. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11887. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11888. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11889. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11890. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11891. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11892. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11893. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11894. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11895. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11896. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11897. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11898. ];
  11899. super( vertices, indices, radius, detail );
  11900. this.type = 'DodecahedronGeometry';
  11901. this.parameters = {
  11902. radius: radius,
  11903. detail: detail
  11904. };
  11905. }
  11906. static fromJSON( data ) {
  11907. return new DodecahedronGeometry( data.radius, data.detail );
  11908. }
  11909. }
  11910. const _v0 = /*@__PURE__*/ new Vector3();
  11911. const _v1$1 = /*@__PURE__*/ new Vector3();
  11912. const _normal$1 = /*@__PURE__*/ new Vector3();
  11913. const _triangle = /*@__PURE__*/ new Triangle();
  11914. class EdgesGeometry extends BufferGeometry {
  11915. constructor( geometry = null, thresholdAngle = 1 ) {
  11916. super();
  11917. this.type = 'EdgesGeometry';
  11918. this.parameters = {
  11919. geometry: geometry,
  11920. thresholdAngle: thresholdAngle
  11921. };
  11922. if ( geometry !== null ) {
  11923. const precisionPoints = 4;
  11924. const precision = Math.pow( 10, precisionPoints );
  11925. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11926. const indexAttr = geometry.getIndex();
  11927. const positionAttr = geometry.getAttribute( 'position' );
  11928. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11929. const indexArr = [ 0, 0, 0 ];
  11930. const vertKeys = [ 'a', 'b', 'c' ];
  11931. const hashes = new Array( 3 );
  11932. const edgeData = {};
  11933. const vertices = [];
  11934. for ( let i = 0; i < indexCount; i += 3 ) {
  11935. if ( indexAttr ) {
  11936. indexArr[ 0 ] = indexAttr.getX( i );
  11937. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11938. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11939. } else {
  11940. indexArr[ 0 ] = i;
  11941. indexArr[ 1 ] = i + 1;
  11942. indexArr[ 2 ] = i + 2;
  11943. }
  11944. const { a, b, c } = _triangle;
  11945. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11946. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11947. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11948. _triangle.getNormal( _normal$1 );
  11949. // create hashes for the edge from the vertices
  11950. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11951. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11952. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11953. // skip degenerate triangles
  11954. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11955. continue;
  11956. }
  11957. // iterate over every edge
  11958. for ( let j = 0; j < 3; j ++ ) {
  11959. // get the first and next vertex making up the edge
  11960. const jNext = ( j + 1 ) % 3;
  11961. const vecHash0 = hashes[ j ];
  11962. const vecHash1 = hashes[ jNext ];
  11963. const v0 = _triangle[ vertKeys[ j ] ];
  11964. const v1 = _triangle[ vertKeys[ jNext ] ];
  11965. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11966. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11967. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11968. // if we found a sibling edge add it into the vertex array if
  11969. // it meets the angle threshold and delete the edge from the map.
  11970. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11971. vertices.push( v0.x, v0.y, v0.z );
  11972. vertices.push( v1.x, v1.y, v1.z );
  11973. }
  11974. edgeData[ reverseHash ] = null;
  11975. } else if ( ! ( hash in edgeData ) ) {
  11976. // if we've already got an edge here then skip adding a new one
  11977. edgeData[ hash ] = {
  11978. index0: indexArr[ j ],
  11979. index1: indexArr[ jNext ],
  11980. normal: _normal$1.clone(),
  11981. };
  11982. }
  11983. }
  11984. }
  11985. // iterate over all remaining, unmatched edges and add them to the vertex array
  11986. for ( const key in edgeData ) {
  11987. if ( edgeData[ key ] ) {
  11988. const { index0, index1 } = edgeData[ key ];
  11989. _v0.fromBufferAttribute( positionAttr, index0 );
  11990. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11991. vertices.push( _v0.x, _v0.y, _v0.z );
  11992. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11993. }
  11994. }
  11995. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11996. }
  11997. }
  11998. copy( source ) {
  11999. super.copy( source );
  12000. this.parameters = Object.assign( {}, source.parameters );
  12001. return this;
  12002. }
  12003. }
  12004. class Shape extends Path {
  12005. constructor( points ) {
  12006. super( points );
  12007. this.uuid = generateUUID();
  12008. this.type = 'Shape';
  12009. this.holes = [];
  12010. }
  12011. getPointsHoles( divisions ) {
  12012. const holesPts = [];
  12013. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12014. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12015. }
  12016. return holesPts;
  12017. }
  12018. // get points of shape and holes (keypoints based on segments parameter)
  12019. extractPoints( divisions ) {
  12020. return {
  12021. shape: this.getPoints( divisions ),
  12022. holes: this.getPointsHoles( divisions )
  12023. };
  12024. }
  12025. copy( source ) {
  12026. super.copy( source );
  12027. this.holes = [];
  12028. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12029. const hole = source.holes[ i ];
  12030. this.holes.push( hole.clone() );
  12031. }
  12032. return this;
  12033. }
  12034. toJSON() {
  12035. const data = super.toJSON();
  12036. data.uuid = this.uuid;
  12037. data.holes = [];
  12038. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12039. const hole = this.holes[ i ];
  12040. data.holes.push( hole.toJSON() );
  12041. }
  12042. return data;
  12043. }
  12044. fromJSON( json ) {
  12045. super.fromJSON( json );
  12046. this.uuid = json.uuid;
  12047. this.holes = [];
  12048. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12049. const hole = json.holes[ i ];
  12050. this.holes.push( new Path().fromJSON( hole ) );
  12051. }
  12052. return this;
  12053. }
  12054. }
  12055. /**
  12056. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12057. */
  12058. const Earcut = {
  12059. triangulate: function ( data, holeIndices, dim = 2 ) {
  12060. const hasHoles = holeIndices && holeIndices.length;
  12061. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12062. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12063. const triangles = [];
  12064. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12065. let minX, minY, maxX, maxY, x, y, invSize;
  12066. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12067. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12068. if ( data.length > 80 * dim ) {
  12069. minX = maxX = data[ 0 ];
  12070. minY = maxY = data[ 1 ];
  12071. for ( let i = dim; i < outerLen; i += dim ) {
  12072. x = data[ i ];
  12073. y = data[ i + 1 ];
  12074. if ( x < minX ) minX = x;
  12075. if ( y < minY ) minY = y;
  12076. if ( x > maxX ) maxX = x;
  12077. if ( y > maxY ) maxY = y;
  12078. }
  12079. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12080. invSize = Math.max( maxX - minX, maxY - minY );
  12081. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12082. }
  12083. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12084. return triangles;
  12085. }
  12086. };
  12087. // create a circular doubly linked list from polygon points in the specified winding order
  12088. function linkedList( data, start, end, dim, clockwise ) {
  12089. let i, last;
  12090. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12091. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12092. } else {
  12093. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12094. }
  12095. if ( last && equals$1( last, last.next ) ) {
  12096. removeNode( last );
  12097. last = last.next;
  12098. }
  12099. return last;
  12100. }
  12101. // eliminate colinear or duplicate points
  12102. function filterPoints( start, end ) {
  12103. if ( ! start ) return start;
  12104. if ( ! end ) end = start;
  12105. let p = start,
  12106. again;
  12107. do {
  12108. again = false;
  12109. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12110. removeNode( p );
  12111. p = end = p.prev;
  12112. if ( p === p.next ) break;
  12113. again = true;
  12114. } else {
  12115. p = p.next;
  12116. }
  12117. } while ( again || p !== end );
  12118. return end;
  12119. }
  12120. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12121. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12122. if ( ! ear ) return;
  12123. // interlink polygon nodes in z-order
  12124. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12125. let stop = ear,
  12126. prev, next;
  12127. // iterate through ears, slicing them one by one
  12128. while ( ear.prev !== ear.next ) {
  12129. prev = ear.prev;
  12130. next = ear.next;
  12131. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12132. // cut off the triangle
  12133. triangles.push( prev.i / dim | 0 );
  12134. triangles.push( ear.i / dim | 0 );
  12135. triangles.push( next.i / dim | 0 );
  12136. removeNode( ear );
  12137. // skipping the next vertex leads to less sliver triangles
  12138. ear = next.next;
  12139. stop = next.next;
  12140. continue;
  12141. }
  12142. ear = next;
  12143. // if we looped through the whole remaining polygon and can't find any more ears
  12144. if ( ear === stop ) {
  12145. // try filtering points and slicing again
  12146. if ( ! pass ) {
  12147. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12148. // if this didn't work, try curing all small self-intersections locally
  12149. } else if ( pass === 1 ) {
  12150. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12151. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12152. // as a last resort, try splitting the remaining polygon into two
  12153. } else if ( pass === 2 ) {
  12154. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12155. }
  12156. break;
  12157. }
  12158. }
  12159. }
  12160. // check whether a polygon node forms a valid ear with adjacent nodes
  12161. function isEar( ear ) {
  12162. const a = ear.prev,
  12163. b = ear,
  12164. c = ear.next;
  12165. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12166. // now make sure we don't have other points inside the potential ear
  12167. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12168. // triangle bbox; min & max are calculated like this for speed
  12169. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12170. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12171. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12172. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12173. let p = c.next;
  12174. while ( p !== a ) {
  12175. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12176. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12177. area( p.prev, p, p.next ) >= 0 ) return false;
  12178. p = p.next;
  12179. }
  12180. return true;
  12181. }
  12182. function isEarHashed( ear, minX, minY, invSize ) {
  12183. const a = ear.prev,
  12184. b = ear,
  12185. c = ear.next;
  12186. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12187. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12188. // triangle bbox; min & max are calculated like this for speed
  12189. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12190. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12191. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12192. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12193. // z-order range for the current triangle bbox;
  12194. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12195. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12196. let p = ear.prevZ,
  12197. n = ear.nextZ;
  12198. // look for points inside the triangle in both directions
  12199. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12200. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12201. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12202. p = p.prevZ;
  12203. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12204. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12205. n = n.nextZ;
  12206. }
  12207. // look for remaining points in decreasing z-order
  12208. while ( p && p.z >= minZ ) {
  12209. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12210. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12211. p = p.prevZ;
  12212. }
  12213. // look for remaining points in increasing z-order
  12214. while ( n && n.z <= maxZ ) {
  12215. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12216. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12217. n = n.nextZ;
  12218. }
  12219. return true;
  12220. }
  12221. // go through all polygon nodes and cure small local self-intersections
  12222. function cureLocalIntersections( start, triangles, dim ) {
  12223. let p = start;
  12224. do {
  12225. const a = p.prev,
  12226. b = p.next.next;
  12227. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12228. triangles.push( a.i / dim | 0 );
  12229. triangles.push( p.i / dim | 0 );
  12230. triangles.push( b.i / dim | 0 );
  12231. // remove two nodes involved
  12232. removeNode( p );
  12233. removeNode( p.next );
  12234. p = start = b;
  12235. }
  12236. p = p.next;
  12237. } while ( p !== start );
  12238. return filterPoints( p );
  12239. }
  12240. // try splitting polygon into two and triangulate them independently
  12241. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12242. // look for a valid diagonal that divides the polygon into two
  12243. let a = start;
  12244. do {
  12245. let b = a.next.next;
  12246. while ( b !== a.prev ) {
  12247. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12248. // split the polygon in two by the diagonal
  12249. let c = splitPolygon( a, b );
  12250. // filter colinear points around the cuts
  12251. a = filterPoints( a, a.next );
  12252. c = filterPoints( c, c.next );
  12253. // run earcut on each half
  12254. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12255. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12256. return;
  12257. }
  12258. b = b.next;
  12259. }
  12260. a = a.next;
  12261. } while ( a !== start );
  12262. }
  12263. // link every hole into the outer loop, producing a single-ring polygon without holes
  12264. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12265. const queue = [];
  12266. let i, len, start, end, list;
  12267. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12268. start = holeIndices[ i ] * dim;
  12269. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12270. list = linkedList( data, start, end, dim, false );
  12271. if ( list === list.next ) list.steiner = true;
  12272. queue.push( getLeftmost( list ) );
  12273. }
  12274. queue.sort( compareX );
  12275. // process holes from left to right
  12276. for ( i = 0; i < queue.length; i ++ ) {
  12277. outerNode = eliminateHole( queue[ i ], outerNode );
  12278. }
  12279. return outerNode;
  12280. }
  12281. function compareX( a, b ) {
  12282. return a.x - b.x;
  12283. }
  12284. // find a bridge between vertices that connects hole with an outer ring and link it
  12285. function eliminateHole( hole, outerNode ) {
  12286. const bridge = findHoleBridge( hole, outerNode );
  12287. if ( ! bridge ) {
  12288. return outerNode;
  12289. }
  12290. const bridgeReverse = splitPolygon( bridge, hole );
  12291. // filter collinear points around the cuts
  12292. filterPoints( bridgeReverse, bridgeReverse.next );
  12293. return filterPoints( bridge, bridge.next );
  12294. }
  12295. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12296. function findHoleBridge( hole, outerNode ) {
  12297. let p = outerNode,
  12298. qx = - Infinity,
  12299. m;
  12300. const hx = hole.x, hy = hole.y;
  12301. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12302. // segment's endpoint with lesser x will be potential connection point
  12303. do {
  12304. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12305. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12306. if ( x <= hx && x > qx ) {
  12307. qx = x;
  12308. m = p.x < p.next.x ? p : p.next;
  12309. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12310. }
  12311. }
  12312. p = p.next;
  12313. } while ( p !== outerNode );
  12314. if ( ! m ) return null;
  12315. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12316. // if there are no points found, we have a valid connection;
  12317. // otherwise choose the point of the minimum angle with the ray as connection point
  12318. const stop = m,
  12319. mx = m.x,
  12320. my = m.y;
  12321. let tanMin = Infinity, tan;
  12322. p = m;
  12323. do {
  12324. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12325. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12326. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12327. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12328. m = p;
  12329. tanMin = tan;
  12330. }
  12331. }
  12332. p = p.next;
  12333. } while ( p !== stop );
  12334. return m;
  12335. }
  12336. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12337. function sectorContainsSector( m, p ) {
  12338. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12339. }
  12340. // interlink polygon nodes in z-order
  12341. function indexCurve( start, minX, minY, invSize ) {
  12342. let p = start;
  12343. do {
  12344. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12345. p.prevZ = p.prev;
  12346. p.nextZ = p.next;
  12347. p = p.next;
  12348. } while ( p !== start );
  12349. p.prevZ.nextZ = null;
  12350. p.prevZ = null;
  12351. sortLinked( p );
  12352. }
  12353. // Simon Tatham's linked list merge sort algorithm
  12354. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12355. function sortLinked( list ) {
  12356. let i, p, q, e, tail, numMerges, pSize, qSize,
  12357. inSize = 1;
  12358. do {
  12359. p = list;
  12360. list = null;
  12361. tail = null;
  12362. numMerges = 0;
  12363. while ( p ) {
  12364. numMerges ++;
  12365. q = p;
  12366. pSize = 0;
  12367. for ( i = 0; i < inSize; i ++ ) {
  12368. pSize ++;
  12369. q = q.nextZ;
  12370. if ( ! q ) break;
  12371. }
  12372. qSize = inSize;
  12373. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12374. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12375. e = p;
  12376. p = p.nextZ;
  12377. pSize --;
  12378. } else {
  12379. e = q;
  12380. q = q.nextZ;
  12381. qSize --;
  12382. }
  12383. if ( tail ) tail.nextZ = e;
  12384. else list = e;
  12385. e.prevZ = tail;
  12386. tail = e;
  12387. }
  12388. p = q;
  12389. }
  12390. tail.nextZ = null;
  12391. inSize *= 2;
  12392. } while ( numMerges > 1 );
  12393. return list;
  12394. }
  12395. // z-order of a point given coords and inverse of the longer side of data bbox
  12396. function zOrder( x, y, minX, minY, invSize ) {
  12397. // coords are transformed into non-negative 15-bit integer range
  12398. x = ( x - minX ) * invSize | 0;
  12399. y = ( y - minY ) * invSize | 0;
  12400. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12401. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12402. x = ( x | ( x << 2 ) ) & 0x33333333;
  12403. x = ( x | ( x << 1 ) ) & 0x55555555;
  12404. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12405. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12406. y = ( y | ( y << 2 ) ) & 0x33333333;
  12407. y = ( y | ( y << 1 ) ) & 0x55555555;
  12408. return x | ( y << 1 );
  12409. }
  12410. // find the leftmost node of a polygon ring
  12411. function getLeftmost( start ) {
  12412. let p = start,
  12413. leftmost = start;
  12414. do {
  12415. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12416. p = p.next;
  12417. } while ( p !== start );
  12418. return leftmost;
  12419. }
  12420. // check if a point lies within a convex triangle
  12421. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12422. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12423. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12424. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12425. }
  12426. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12427. function isValidDiagonal( a, b ) {
  12428. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12429. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12430. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12431. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12432. }
  12433. // signed area of a triangle
  12434. function area( p, q, r ) {
  12435. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12436. }
  12437. // check if two points are equal
  12438. function equals$1( p1, p2 ) {
  12439. return p1.x === p2.x && p1.y === p2.y;
  12440. }
  12441. // check if two segments intersect
  12442. function intersects( p1, q1, p2, q2 ) {
  12443. const o1 = sign$1( area( p1, q1, p2 ) );
  12444. const o2 = sign$1( area( p1, q1, q2 ) );
  12445. const o3 = sign$1( area( p2, q2, p1 ) );
  12446. const o4 = sign$1( area( p2, q2, q1 ) );
  12447. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12448. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12449. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12450. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12451. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12452. return false;
  12453. }
  12454. // for collinear points p, q, r, check if point q lies on segment pr
  12455. function onSegment( p, q, r ) {
  12456. 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 );
  12457. }
  12458. function sign$1( num ) {
  12459. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12460. }
  12461. // check if a polygon diagonal intersects any polygon segments
  12462. function intersectsPolygon( a, b ) {
  12463. let p = a;
  12464. do {
  12465. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12466. intersects( p, p.next, a, b ) ) return true;
  12467. p = p.next;
  12468. } while ( p !== a );
  12469. return false;
  12470. }
  12471. // check if a polygon diagonal is locally inside the polygon
  12472. function locallyInside( a, b ) {
  12473. return area( a.prev, a, a.next ) < 0 ?
  12474. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12475. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12476. }
  12477. // check if the middle point of a polygon diagonal is inside the polygon
  12478. function middleInside( a, b ) {
  12479. let p = a,
  12480. inside = false;
  12481. const px = ( a.x + b.x ) / 2,
  12482. py = ( a.y + b.y ) / 2;
  12483. do {
  12484. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12485. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12486. inside = ! inside;
  12487. p = p.next;
  12488. } while ( p !== a );
  12489. return inside;
  12490. }
  12491. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12492. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12493. function splitPolygon( a, b ) {
  12494. const a2 = new Node$1( a.i, a.x, a.y ),
  12495. b2 = new Node$1( b.i, b.x, b.y ),
  12496. an = a.next,
  12497. bp = b.prev;
  12498. a.next = b;
  12499. b.prev = a;
  12500. a2.next = an;
  12501. an.prev = a2;
  12502. b2.next = a2;
  12503. a2.prev = b2;
  12504. bp.next = b2;
  12505. b2.prev = bp;
  12506. return b2;
  12507. }
  12508. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12509. function insertNode( i, x, y, last ) {
  12510. const p = new Node$1( i, x, y );
  12511. if ( ! last ) {
  12512. p.prev = p;
  12513. p.next = p;
  12514. } else {
  12515. p.next = last.next;
  12516. p.prev = last;
  12517. last.next.prev = p;
  12518. last.next = p;
  12519. }
  12520. return p;
  12521. }
  12522. function removeNode( p ) {
  12523. p.next.prev = p.prev;
  12524. p.prev.next = p.next;
  12525. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12526. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12527. }
  12528. function Node$1( i, x, y ) {
  12529. // vertex index in coordinates array
  12530. this.i = i;
  12531. // vertex coordinates
  12532. this.x = x;
  12533. this.y = y;
  12534. // previous and next vertex nodes in a polygon ring
  12535. this.prev = null;
  12536. this.next = null;
  12537. // z-order curve value
  12538. this.z = 0;
  12539. // previous and next nodes in z-order
  12540. this.prevZ = null;
  12541. this.nextZ = null;
  12542. // indicates whether this is a steiner point
  12543. this.steiner = false;
  12544. }
  12545. function signedArea( data, start, end, dim ) {
  12546. let sum = 0;
  12547. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12548. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12549. j = i;
  12550. }
  12551. return sum;
  12552. }
  12553. class ShapeUtils {
  12554. // calculate area of the contour polygon
  12555. static area( contour ) {
  12556. const n = contour.length;
  12557. let a = 0.0;
  12558. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12559. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12560. }
  12561. return a * 0.5;
  12562. }
  12563. static isClockWise( pts ) {
  12564. return ShapeUtils.area( pts ) < 0;
  12565. }
  12566. static triangulateShape( contour, holes ) {
  12567. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12568. const holeIndices = []; // array of hole indices
  12569. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12570. removeDupEndPts( contour );
  12571. addContour( vertices, contour );
  12572. //
  12573. let holeIndex = contour.length;
  12574. holes.forEach( removeDupEndPts );
  12575. for ( let i = 0; i < holes.length; i ++ ) {
  12576. holeIndices.push( holeIndex );
  12577. holeIndex += holes[ i ].length;
  12578. addContour( vertices, holes[ i ] );
  12579. }
  12580. //
  12581. const triangles = Earcut.triangulate( vertices, holeIndices );
  12582. //
  12583. for ( let i = 0; i < triangles.length; i += 3 ) {
  12584. faces.push( triangles.slice( i, i + 3 ) );
  12585. }
  12586. return faces;
  12587. }
  12588. }
  12589. function removeDupEndPts( points ) {
  12590. const l = points.length;
  12591. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12592. points.pop();
  12593. }
  12594. }
  12595. function addContour( vertices, contour ) {
  12596. for ( let i = 0; i < contour.length; i ++ ) {
  12597. vertices.push( contour[ i ].x );
  12598. vertices.push( contour[ i ].y );
  12599. }
  12600. }
  12601. /**
  12602. * Creates extruded geometry from a path shape.
  12603. *
  12604. * parameters = {
  12605. *
  12606. * curveSegments: <int>, // number of points on the curves
  12607. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12608. * depth: <float>, // Depth to extrude the shape
  12609. *
  12610. * bevelEnabled: <bool>, // turn on bevel
  12611. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12612. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12613. * bevelOffset: <float>, // how far from shape outline does bevel start
  12614. * bevelSegments: <int>, // number of bevel layers
  12615. *
  12616. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12617. *
  12618. * UVGenerator: <Object> // object that provides UV generator functions
  12619. *
  12620. * }
  12621. */
  12622. class ExtrudeGeometry extends BufferGeometry {
  12623. 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 = {} ) {
  12624. super();
  12625. this.type = 'ExtrudeGeometry';
  12626. this.parameters = {
  12627. shapes: shapes,
  12628. options: options
  12629. };
  12630. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12631. const scope = this;
  12632. const verticesArray = [];
  12633. const uvArray = [];
  12634. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12635. const shape = shapes[ i ];
  12636. addShape( shape );
  12637. }
  12638. // build geometry
  12639. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12640. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12641. this.computeVertexNormals();
  12642. // functions
  12643. function addShape( shape ) {
  12644. const placeholder = [];
  12645. // options
  12646. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12647. const steps = options.steps !== undefined ? options.steps : 1;
  12648. const depth = options.depth !== undefined ? options.depth : 1;
  12649. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12650. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12651. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12652. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12653. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12654. const extrudePath = options.extrudePath;
  12655. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12656. //
  12657. let extrudePts, extrudeByPath = false;
  12658. let splineTube, binormal, normal, position2;
  12659. if ( extrudePath ) {
  12660. extrudePts = extrudePath.getSpacedPoints( steps );
  12661. extrudeByPath = true;
  12662. bevelEnabled = false; // bevels not supported for path extrusion
  12663. // SETUP TNB variables
  12664. // TODO1 - have a .isClosed in spline?
  12665. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12666. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12667. binormal = new Vector3();
  12668. normal = new Vector3();
  12669. position2 = new Vector3();
  12670. }
  12671. // Safeguards if bevels are not enabled
  12672. if ( ! bevelEnabled ) {
  12673. bevelSegments = 0;
  12674. bevelThickness = 0;
  12675. bevelSize = 0;
  12676. bevelOffset = 0;
  12677. }
  12678. // Variables initialization
  12679. const shapePoints = shape.extractPoints( curveSegments );
  12680. let vertices = shapePoints.shape;
  12681. const holes = shapePoints.holes;
  12682. const reverse = ! ShapeUtils.isClockWise( vertices );
  12683. if ( reverse ) {
  12684. vertices = vertices.reverse();
  12685. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12686. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12687. const ahole = holes[ h ];
  12688. if ( ShapeUtils.isClockWise( ahole ) ) {
  12689. holes[ h ] = ahole.reverse();
  12690. }
  12691. }
  12692. }
  12693. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12694. /* Vertices */
  12695. const contour = vertices; // vertices has all points but contour has only points of circumference
  12696. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12697. const ahole = holes[ h ];
  12698. vertices = vertices.concat( ahole );
  12699. }
  12700. function scalePt2( pt, vec, size ) {
  12701. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12702. return pt.clone().addScaledVector( vec, size );
  12703. }
  12704. const vlen = vertices.length, flen = faces.length;
  12705. // Find directions for point movement
  12706. function getBevelVec( inPt, inPrev, inNext ) {
  12707. // computes for inPt the corresponding point inPt' on a new contour
  12708. // shifted by 1 unit (length of normalized vector) to the left
  12709. // if we walk along contour clockwise, this new contour is outside the old one
  12710. //
  12711. // inPt' is the intersection of the two lines parallel to the two
  12712. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12713. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12714. // good reading for geometry algorithms (here: line-line intersection)
  12715. // http://geomalgorithms.com/a05-_intersect-1.html
  12716. const v_prev_x = inPt.x - inPrev.x,
  12717. v_prev_y = inPt.y - inPrev.y;
  12718. const v_next_x = inNext.x - inPt.x,
  12719. v_next_y = inNext.y - inPt.y;
  12720. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12721. // check for collinear edges
  12722. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12723. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12724. // not collinear
  12725. // length of vectors for normalizing
  12726. const v_prev_len = Math.sqrt( v_prev_lensq );
  12727. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12728. // shift adjacent points by unit vectors to the left
  12729. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12730. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12731. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12732. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12733. // scaling factor for v_prev to intersection point
  12734. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12735. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12736. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12737. // vector from inPt to intersection point
  12738. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12739. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12740. // Don't normalize!, otherwise sharp corners become ugly
  12741. // but prevent crazy spikes
  12742. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12743. if ( v_trans_lensq <= 2 ) {
  12744. return new Vector2( v_trans_x, v_trans_y );
  12745. } else {
  12746. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12747. }
  12748. } else {
  12749. // handle special case of collinear edges
  12750. let direction_eq = false; // assumes: opposite
  12751. if ( v_prev_x > Number.EPSILON ) {
  12752. if ( v_next_x > Number.EPSILON ) {
  12753. direction_eq = true;
  12754. }
  12755. } else {
  12756. if ( v_prev_x < - Number.EPSILON ) {
  12757. if ( v_next_x < - Number.EPSILON ) {
  12758. direction_eq = true;
  12759. }
  12760. } else {
  12761. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12762. direction_eq = true;
  12763. }
  12764. }
  12765. }
  12766. if ( direction_eq ) {
  12767. // console.log("Warning: lines are a straight sequence");
  12768. v_trans_x = - v_prev_y;
  12769. v_trans_y = v_prev_x;
  12770. shrink_by = Math.sqrt( v_prev_lensq );
  12771. } else {
  12772. // console.log("Warning: lines are a straight spike");
  12773. v_trans_x = v_prev_x;
  12774. v_trans_y = v_prev_y;
  12775. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12776. }
  12777. }
  12778. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12779. }
  12780. const contourMovements = [];
  12781. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12782. if ( j === il ) j = 0;
  12783. if ( k === il ) k = 0;
  12784. // (j)---(i)---(k)
  12785. // console.log('i,j,k', i, j , k)
  12786. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12787. }
  12788. const holesMovements = [];
  12789. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12790. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12791. const ahole = holes[ h ];
  12792. oneHoleMovements = [];
  12793. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12794. if ( j === il ) j = 0;
  12795. if ( k === il ) k = 0;
  12796. // (j)---(i)---(k)
  12797. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12798. }
  12799. holesMovements.push( oneHoleMovements );
  12800. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12801. }
  12802. // Loop bevelSegments, 1 for the front, 1 for the back
  12803. for ( let b = 0; b < bevelSegments; b ++ ) {
  12804. //for ( b = bevelSegments; b > 0; b -- ) {
  12805. const t = b / bevelSegments;
  12806. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12807. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12808. // contract shape
  12809. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12810. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12811. v( vert.x, vert.y, - z );
  12812. }
  12813. // expand holes
  12814. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12815. const ahole = holes[ h ];
  12816. oneHoleMovements = holesMovements[ h ];
  12817. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12818. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12819. v( vert.x, vert.y, - z );
  12820. }
  12821. }
  12822. }
  12823. const bs = bevelSize + bevelOffset;
  12824. // Back facing vertices
  12825. for ( let i = 0; i < vlen; i ++ ) {
  12826. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12827. if ( ! extrudeByPath ) {
  12828. v( vert.x, vert.y, 0 );
  12829. } else {
  12830. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12831. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12832. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12833. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12834. v( position2.x, position2.y, position2.z );
  12835. }
  12836. }
  12837. // Add stepped vertices...
  12838. // Including front facing vertices
  12839. for ( let s = 1; s <= steps; s ++ ) {
  12840. for ( let i = 0; i < vlen; i ++ ) {
  12841. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12842. if ( ! extrudeByPath ) {
  12843. v( vert.x, vert.y, depth / steps * s );
  12844. } else {
  12845. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12846. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12847. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12848. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12849. v( position2.x, position2.y, position2.z );
  12850. }
  12851. }
  12852. }
  12853. // Add bevel segments planes
  12854. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12855. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12856. const t = b / bevelSegments;
  12857. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12858. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12859. // contract shape
  12860. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12861. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12862. v( vert.x, vert.y, depth + z );
  12863. }
  12864. // expand holes
  12865. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12866. const ahole = holes[ h ];
  12867. oneHoleMovements = holesMovements[ h ];
  12868. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12869. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12870. if ( ! extrudeByPath ) {
  12871. v( vert.x, vert.y, depth + z );
  12872. } else {
  12873. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12874. }
  12875. }
  12876. }
  12877. }
  12878. /* Faces */
  12879. // Top and bottom faces
  12880. buildLidFaces();
  12881. // Sides faces
  12882. buildSideFaces();
  12883. ///// Internal functions
  12884. function buildLidFaces() {
  12885. const start = verticesArray.length / 3;
  12886. if ( bevelEnabled ) {
  12887. let layer = 0; // steps + 1
  12888. let offset = vlen * layer;
  12889. // Bottom faces
  12890. for ( let i = 0; i < flen; i ++ ) {
  12891. const face = faces[ i ];
  12892. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12893. }
  12894. layer = steps + bevelSegments * 2;
  12895. offset = vlen * layer;
  12896. // Top faces
  12897. for ( let i = 0; i < flen; i ++ ) {
  12898. const face = faces[ i ];
  12899. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12900. }
  12901. } else {
  12902. // Bottom faces
  12903. for ( let i = 0; i < flen; i ++ ) {
  12904. const face = faces[ i ];
  12905. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12906. }
  12907. // Top faces
  12908. for ( let i = 0; i < flen; i ++ ) {
  12909. const face = faces[ i ];
  12910. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12911. }
  12912. }
  12913. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12914. }
  12915. // Create faces for the z-sides of the shape
  12916. function buildSideFaces() {
  12917. const start = verticesArray.length / 3;
  12918. let layeroffset = 0;
  12919. sidewalls( contour, layeroffset );
  12920. layeroffset += contour.length;
  12921. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12922. const ahole = holes[ h ];
  12923. sidewalls( ahole, layeroffset );
  12924. //, true
  12925. layeroffset += ahole.length;
  12926. }
  12927. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12928. }
  12929. function sidewalls( contour, layeroffset ) {
  12930. let i = contour.length;
  12931. while ( -- i >= 0 ) {
  12932. const j = i;
  12933. let k = i - 1;
  12934. if ( k < 0 ) k = contour.length - 1;
  12935. //console.log('b', i,j, i-1, k,vertices.length);
  12936. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12937. const slen1 = vlen * s;
  12938. const slen2 = vlen * ( s + 1 );
  12939. const a = layeroffset + j + slen1,
  12940. b = layeroffset + k + slen1,
  12941. c = layeroffset + k + slen2,
  12942. d = layeroffset + j + slen2;
  12943. f4( a, b, c, d );
  12944. }
  12945. }
  12946. }
  12947. function v( x, y, z ) {
  12948. placeholder.push( x );
  12949. placeholder.push( y );
  12950. placeholder.push( z );
  12951. }
  12952. function f3( a, b, c ) {
  12953. addVertex( a );
  12954. addVertex( b );
  12955. addVertex( c );
  12956. const nextIndex = verticesArray.length / 3;
  12957. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12958. addUV( uvs[ 0 ] );
  12959. addUV( uvs[ 1 ] );
  12960. addUV( uvs[ 2 ] );
  12961. }
  12962. function f4( a, b, c, d ) {
  12963. addVertex( a );
  12964. addVertex( b );
  12965. addVertex( d );
  12966. addVertex( b );
  12967. addVertex( c );
  12968. addVertex( d );
  12969. const nextIndex = verticesArray.length / 3;
  12970. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12971. addUV( uvs[ 0 ] );
  12972. addUV( uvs[ 1 ] );
  12973. addUV( uvs[ 3 ] );
  12974. addUV( uvs[ 1 ] );
  12975. addUV( uvs[ 2 ] );
  12976. addUV( uvs[ 3 ] );
  12977. }
  12978. function addVertex( index ) {
  12979. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12980. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12981. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12982. }
  12983. function addUV( vector2 ) {
  12984. uvArray.push( vector2.x );
  12985. uvArray.push( vector2.y );
  12986. }
  12987. }
  12988. }
  12989. copy( source ) {
  12990. super.copy( source );
  12991. this.parameters = Object.assign( {}, source.parameters );
  12992. return this;
  12993. }
  12994. toJSON() {
  12995. const data = super.toJSON();
  12996. const shapes = this.parameters.shapes;
  12997. const options = this.parameters.options;
  12998. return toJSON$1( shapes, options, data );
  12999. }
  13000. static fromJSON( data, shapes ) {
  13001. const geometryShapes = [];
  13002. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13003. const shape = shapes[ data.shapes[ j ] ];
  13004. geometryShapes.push( shape );
  13005. }
  13006. const extrudePath = data.options.extrudePath;
  13007. if ( extrudePath !== undefined ) {
  13008. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13009. }
  13010. return new ExtrudeGeometry( geometryShapes, data.options );
  13011. }
  13012. }
  13013. const WorldUVGenerator = {
  13014. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13015. const a_x = vertices[ indexA * 3 ];
  13016. const a_y = vertices[ indexA * 3 + 1 ];
  13017. const b_x = vertices[ indexB * 3 ];
  13018. const b_y = vertices[ indexB * 3 + 1 ];
  13019. const c_x = vertices[ indexC * 3 ];
  13020. const c_y = vertices[ indexC * 3 + 1 ];
  13021. return [
  13022. new Vector2( a_x, a_y ),
  13023. new Vector2( b_x, b_y ),
  13024. new Vector2( c_x, c_y )
  13025. ];
  13026. },
  13027. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13028. const a_x = vertices[ indexA * 3 ];
  13029. const a_y = vertices[ indexA * 3 + 1 ];
  13030. const a_z = vertices[ indexA * 3 + 2 ];
  13031. const b_x = vertices[ indexB * 3 ];
  13032. const b_y = vertices[ indexB * 3 + 1 ];
  13033. const b_z = vertices[ indexB * 3 + 2 ];
  13034. const c_x = vertices[ indexC * 3 ];
  13035. const c_y = vertices[ indexC * 3 + 1 ];
  13036. const c_z = vertices[ indexC * 3 + 2 ];
  13037. const d_x = vertices[ indexD * 3 ];
  13038. const d_y = vertices[ indexD * 3 + 1 ];
  13039. const d_z = vertices[ indexD * 3 + 2 ];
  13040. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13041. return [
  13042. new Vector2( a_x, 1 - a_z ),
  13043. new Vector2( b_x, 1 - b_z ),
  13044. new Vector2( c_x, 1 - c_z ),
  13045. new Vector2( d_x, 1 - d_z )
  13046. ];
  13047. } else {
  13048. return [
  13049. new Vector2( a_y, 1 - a_z ),
  13050. new Vector2( b_y, 1 - b_z ),
  13051. new Vector2( c_y, 1 - c_z ),
  13052. new Vector2( d_y, 1 - d_z )
  13053. ];
  13054. }
  13055. }
  13056. };
  13057. function toJSON$1( shapes, options, data ) {
  13058. data.shapes = [];
  13059. if ( Array.isArray( shapes ) ) {
  13060. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13061. const shape = shapes[ i ];
  13062. data.shapes.push( shape.uuid );
  13063. }
  13064. } else {
  13065. data.shapes.push( shapes.uuid );
  13066. }
  13067. data.options = Object.assign( {}, options );
  13068. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13069. return data;
  13070. }
  13071. class IcosahedronGeometry extends PolyhedronGeometry {
  13072. constructor( radius = 1, detail = 0 ) {
  13073. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13074. const vertices = [
  13075. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13076. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13077. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13078. ];
  13079. const indices = [
  13080. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13081. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13082. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13083. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13084. ];
  13085. super( vertices, indices, radius, detail );
  13086. this.type = 'IcosahedronGeometry';
  13087. this.parameters = {
  13088. radius: radius,
  13089. detail: detail
  13090. };
  13091. }
  13092. static fromJSON( data ) {
  13093. return new IcosahedronGeometry( data.radius, data.detail );
  13094. }
  13095. }
  13096. class OctahedronGeometry extends PolyhedronGeometry {
  13097. constructor( radius = 1, detail = 0 ) {
  13098. const vertices = [
  13099. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13100. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13101. ];
  13102. const indices = [
  13103. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13104. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13105. 1, 3, 4, 1, 4, 2
  13106. ];
  13107. super( vertices, indices, radius, detail );
  13108. this.type = 'OctahedronGeometry';
  13109. this.parameters = {
  13110. radius: radius,
  13111. detail: detail
  13112. };
  13113. }
  13114. static fromJSON( data ) {
  13115. return new OctahedronGeometry( data.radius, data.detail );
  13116. }
  13117. }
  13118. class PlaneGeometry extends BufferGeometry {
  13119. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13120. super();
  13121. this.type = 'PlaneGeometry';
  13122. this.parameters = {
  13123. width: width,
  13124. height: height,
  13125. widthSegments: widthSegments,
  13126. heightSegments: heightSegments
  13127. };
  13128. const width_half = width / 2;
  13129. const height_half = height / 2;
  13130. const gridX = Math.floor( widthSegments );
  13131. const gridY = Math.floor( heightSegments );
  13132. const gridX1 = gridX + 1;
  13133. const gridY1 = gridY + 1;
  13134. const segment_width = width / gridX;
  13135. const segment_height = height / gridY;
  13136. //
  13137. const indices = [];
  13138. const vertices = [];
  13139. const normals = [];
  13140. const uvs = [];
  13141. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13142. const y = iy * segment_height - height_half;
  13143. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13144. const x = ix * segment_width - width_half;
  13145. vertices.push( x, - y, 0 );
  13146. normals.push( 0, 0, 1 );
  13147. uvs.push( ix / gridX );
  13148. uvs.push( 1 - ( iy / gridY ) );
  13149. }
  13150. }
  13151. for ( let iy = 0; iy < gridY; iy ++ ) {
  13152. for ( let ix = 0; ix < gridX; ix ++ ) {
  13153. const a = ix + gridX1 * iy;
  13154. const b = ix + gridX1 * ( iy + 1 );
  13155. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13156. const d = ( ix + 1 ) + gridX1 * iy;
  13157. indices.push( a, b, d );
  13158. indices.push( b, c, d );
  13159. }
  13160. }
  13161. this.setIndex( indices );
  13162. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13163. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13164. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13165. }
  13166. copy( source ) {
  13167. super.copy( source );
  13168. this.parameters = Object.assign( {}, source.parameters );
  13169. return this;
  13170. }
  13171. static fromJSON( data ) {
  13172. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13173. }
  13174. }
  13175. class RingGeometry extends BufferGeometry {
  13176. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13177. super();
  13178. this.type = 'RingGeometry';
  13179. this.parameters = {
  13180. innerRadius: innerRadius,
  13181. outerRadius: outerRadius,
  13182. thetaSegments: thetaSegments,
  13183. phiSegments: phiSegments,
  13184. thetaStart: thetaStart,
  13185. thetaLength: thetaLength
  13186. };
  13187. thetaSegments = Math.max( 3, thetaSegments );
  13188. phiSegments = Math.max( 1, phiSegments );
  13189. // buffers
  13190. const indices = [];
  13191. const vertices = [];
  13192. const normals = [];
  13193. const uvs = [];
  13194. // some helper variables
  13195. let radius = innerRadius;
  13196. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13197. const vertex = new Vector3();
  13198. const uv = new Vector2();
  13199. // generate vertices, normals and uvs
  13200. for ( let j = 0; j <= phiSegments; j ++ ) {
  13201. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13202. // values are generate from the inside of the ring to the outside
  13203. const segment = thetaStart + i / thetaSegments * thetaLength;
  13204. // vertex
  13205. vertex.x = radius * Math.cos( segment );
  13206. vertex.y = radius * Math.sin( segment );
  13207. vertices.push( vertex.x, vertex.y, vertex.z );
  13208. // normal
  13209. normals.push( 0, 0, 1 );
  13210. // uv
  13211. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13212. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13213. uvs.push( uv.x, uv.y );
  13214. }
  13215. // increase the radius for next row of vertices
  13216. radius += radiusStep;
  13217. }
  13218. // indices
  13219. for ( let j = 0; j < phiSegments; j ++ ) {
  13220. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13221. for ( let i = 0; i < thetaSegments; i ++ ) {
  13222. const segment = i + thetaSegmentLevel;
  13223. const a = segment;
  13224. const b = segment + thetaSegments + 1;
  13225. const c = segment + thetaSegments + 2;
  13226. const d = segment + 1;
  13227. // faces
  13228. indices.push( a, b, d );
  13229. indices.push( b, c, d );
  13230. }
  13231. }
  13232. // build geometry
  13233. this.setIndex( indices );
  13234. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13235. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13236. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13237. }
  13238. copy( source ) {
  13239. super.copy( source );
  13240. this.parameters = Object.assign( {}, source.parameters );
  13241. return this;
  13242. }
  13243. static fromJSON( data ) {
  13244. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13245. }
  13246. }
  13247. class ShapeGeometry extends BufferGeometry {
  13248. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13249. super();
  13250. this.type = 'ShapeGeometry';
  13251. this.parameters = {
  13252. shapes: shapes,
  13253. curveSegments: curveSegments
  13254. };
  13255. // buffers
  13256. const indices = [];
  13257. const vertices = [];
  13258. const normals = [];
  13259. const uvs = [];
  13260. // helper variables
  13261. let groupStart = 0;
  13262. let groupCount = 0;
  13263. // allow single and array values for "shapes" parameter
  13264. if ( Array.isArray( shapes ) === false ) {
  13265. addShape( shapes );
  13266. } else {
  13267. for ( let i = 0; i < shapes.length; i ++ ) {
  13268. addShape( shapes[ i ] );
  13269. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13270. groupStart += groupCount;
  13271. groupCount = 0;
  13272. }
  13273. }
  13274. // build geometry
  13275. this.setIndex( indices );
  13276. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13277. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13278. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13279. // helper functions
  13280. function addShape( shape ) {
  13281. const indexOffset = vertices.length / 3;
  13282. const points = shape.extractPoints( curveSegments );
  13283. let shapeVertices = points.shape;
  13284. const shapeHoles = points.holes;
  13285. // check direction of vertices
  13286. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13287. shapeVertices = shapeVertices.reverse();
  13288. }
  13289. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13290. const shapeHole = shapeHoles[ i ];
  13291. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13292. shapeHoles[ i ] = shapeHole.reverse();
  13293. }
  13294. }
  13295. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13296. // join vertices of inner and outer paths to a single array
  13297. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13298. const shapeHole = shapeHoles[ i ];
  13299. shapeVertices = shapeVertices.concat( shapeHole );
  13300. }
  13301. // vertices, normals, uvs
  13302. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13303. const vertex = shapeVertices[ i ];
  13304. vertices.push( vertex.x, vertex.y, 0 );
  13305. normals.push( 0, 0, 1 );
  13306. uvs.push( vertex.x, vertex.y ); // world uvs
  13307. }
  13308. // indices
  13309. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13310. const face = faces[ i ];
  13311. const a = face[ 0 ] + indexOffset;
  13312. const b = face[ 1 ] + indexOffset;
  13313. const c = face[ 2 ] + indexOffset;
  13314. indices.push( a, b, c );
  13315. groupCount += 3;
  13316. }
  13317. }
  13318. }
  13319. copy( source ) {
  13320. super.copy( source );
  13321. this.parameters = Object.assign( {}, source.parameters );
  13322. return this;
  13323. }
  13324. toJSON() {
  13325. const data = super.toJSON();
  13326. const shapes = this.parameters.shapes;
  13327. return toJSON( shapes, data );
  13328. }
  13329. static fromJSON( data, shapes ) {
  13330. const geometryShapes = [];
  13331. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13332. const shape = shapes[ data.shapes[ j ] ];
  13333. geometryShapes.push( shape );
  13334. }
  13335. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13336. }
  13337. }
  13338. function toJSON( shapes, data ) {
  13339. data.shapes = [];
  13340. if ( Array.isArray( shapes ) ) {
  13341. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13342. const shape = shapes[ i ];
  13343. data.shapes.push( shape.uuid );
  13344. }
  13345. } else {
  13346. data.shapes.push( shapes.uuid );
  13347. }
  13348. return data;
  13349. }
  13350. class SphereGeometry extends BufferGeometry {
  13351. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13352. super();
  13353. this.type = 'SphereGeometry';
  13354. this.parameters = {
  13355. radius: radius,
  13356. widthSegments: widthSegments,
  13357. heightSegments: heightSegments,
  13358. phiStart: phiStart,
  13359. phiLength: phiLength,
  13360. thetaStart: thetaStart,
  13361. thetaLength: thetaLength
  13362. };
  13363. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13364. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13365. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13366. let index = 0;
  13367. const grid = [];
  13368. const vertex = new Vector3();
  13369. const normal = new Vector3();
  13370. // buffers
  13371. const indices = [];
  13372. const vertices = [];
  13373. const normals = [];
  13374. const uvs = [];
  13375. // generate vertices, normals and uvs
  13376. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13377. const verticesRow = [];
  13378. const v = iy / heightSegments;
  13379. // special case for the poles
  13380. let uOffset = 0;
  13381. if ( iy === 0 && thetaStart === 0 ) {
  13382. uOffset = 0.5 / widthSegments;
  13383. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13384. uOffset = - 0.5 / widthSegments;
  13385. }
  13386. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13387. const u = ix / widthSegments;
  13388. // vertex
  13389. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13390. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13391. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13392. vertices.push( vertex.x, vertex.y, vertex.z );
  13393. // normal
  13394. normal.copy( vertex ).normalize();
  13395. normals.push( normal.x, normal.y, normal.z );
  13396. // uv
  13397. uvs.push( u + uOffset, 1 - v );
  13398. verticesRow.push( index ++ );
  13399. }
  13400. grid.push( verticesRow );
  13401. }
  13402. // indices
  13403. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13404. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13405. const a = grid[ iy ][ ix + 1 ];
  13406. const b = grid[ iy ][ ix ];
  13407. const c = grid[ iy + 1 ][ ix ];
  13408. const d = grid[ iy + 1 ][ ix + 1 ];
  13409. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13410. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13411. }
  13412. }
  13413. // build geometry
  13414. this.setIndex( indices );
  13415. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13416. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13417. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13418. }
  13419. copy( source ) {
  13420. super.copy( source );
  13421. this.parameters = Object.assign( {}, source.parameters );
  13422. return this;
  13423. }
  13424. static fromJSON( data ) {
  13425. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13426. }
  13427. }
  13428. class TetrahedronGeometry extends PolyhedronGeometry {
  13429. constructor( radius = 1, detail = 0 ) {
  13430. const vertices = [
  13431. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13432. ];
  13433. const indices = [
  13434. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13435. ];
  13436. super( vertices, indices, radius, detail );
  13437. this.type = 'TetrahedronGeometry';
  13438. this.parameters = {
  13439. radius: radius,
  13440. detail: detail
  13441. };
  13442. }
  13443. static fromJSON( data ) {
  13444. return new TetrahedronGeometry( data.radius, data.detail );
  13445. }
  13446. }
  13447. class TorusGeometry extends BufferGeometry {
  13448. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13449. super();
  13450. this.type = 'TorusGeometry';
  13451. this.parameters = {
  13452. radius: radius,
  13453. tube: tube,
  13454. radialSegments: radialSegments,
  13455. tubularSegments: tubularSegments,
  13456. arc: arc
  13457. };
  13458. radialSegments = Math.floor( radialSegments );
  13459. tubularSegments = Math.floor( tubularSegments );
  13460. // buffers
  13461. const indices = [];
  13462. const vertices = [];
  13463. const normals = [];
  13464. const uvs = [];
  13465. // helper variables
  13466. const center = new Vector3();
  13467. const vertex = new Vector3();
  13468. const normal = new Vector3();
  13469. // generate vertices, normals and uvs
  13470. for ( let j = 0; j <= radialSegments; j ++ ) {
  13471. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13472. const u = i / tubularSegments * arc;
  13473. const v = j / radialSegments * Math.PI * 2;
  13474. // vertex
  13475. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13476. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13477. vertex.z = tube * Math.sin( v );
  13478. vertices.push( vertex.x, vertex.y, vertex.z );
  13479. // normal
  13480. center.x = radius * Math.cos( u );
  13481. center.y = radius * Math.sin( u );
  13482. normal.subVectors( vertex, center ).normalize();
  13483. normals.push( normal.x, normal.y, normal.z );
  13484. // uv
  13485. uvs.push( i / tubularSegments );
  13486. uvs.push( j / radialSegments );
  13487. }
  13488. }
  13489. // generate indices
  13490. for ( let j = 1; j <= radialSegments; j ++ ) {
  13491. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13492. // indices
  13493. const a = ( tubularSegments + 1 ) * j + i - 1;
  13494. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13495. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13496. const d = ( tubularSegments + 1 ) * j + i;
  13497. // faces
  13498. indices.push( a, b, d );
  13499. indices.push( b, c, d );
  13500. }
  13501. }
  13502. // build geometry
  13503. this.setIndex( indices );
  13504. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13505. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13506. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13507. }
  13508. copy( source ) {
  13509. super.copy( source );
  13510. this.parameters = Object.assign( {}, source.parameters );
  13511. return this;
  13512. }
  13513. static fromJSON( data ) {
  13514. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13515. }
  13516. }
  13517. class TorusKnotGeometry extends BufferGeometry {
  13518. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13519. super();
  13520. this.type = 'TorusKnotGeometry';
  13521. this.parameters = {
  13522. radius: radius,
  13523. tube: tube,
  13524. tubularSegments: tubularSegments,
  13525. radialSegments: radialSegments,
  13526. p: p,
  13527. q: q
  13528. };
  13529. tubularSegments = Math.floor( tubularSegments );
  13530. radialSegments = Math.floor( radialSegments );
  13531. // buffers
  13532. const indices = [];
  13533. const vertices = [];
  13534. const normals = [];
  13535. const uvs = [];
  13536. // helper variables
  13537. const vertex = new Vector3();
  13538. const normal = new Vector3();
  13539. const P1 = new Vector3();
  13540. const P2 = new Vector3();
  13541. const B = new Vector3();
  13542. const T = new Vector3();
  13543. const N = new Vector3();
  13544. // generate vertices, normals and uvs
  13545. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13546. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13547. const u = i / tubularSegments * p * Math.PI * 2;
  13548. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13549. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13550. calculatePositionOnCurve( u, p, q, radius, P1 );
  13551. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13552. // calculate orthonormal basis
  13553. T.subVectors( P2, P1 );
  13554. N.addVectors( P2, P1 );
  13555. B.crossVectors( T, N );
  13556. N.crossVectors( B, T );
  13557. // normalize B, N. T can be ignored, we don't use it
  13558. B.normalize();
  13559. N.normalize();
  13560. for ( let j = 0; j <= radialSegments; ++ j ) {
  13561. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13562. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13563. const v = j / radialSegments * Math.PI * 2;
  13564. const cx = - tube * Math.cos( v );
  13565. const cy = tube * Math.sin( v );
  13566. // now calculate the final vertex position.
  13567. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13568. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13569. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13570. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13571. vertices.push( vertex.x, vertex.y, vertex.z );
  13572. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13573. normal.subVectors( vertex, P1 ).normalize();
  13574. normals.push( normal.x, normal.y, normal.z );
  13575. // uv
  13576. uvs.push( i / tubularSegments );
  13577. uvs.push( j / radialSegments );
  13578. }
  13579. }
  13580. // generate indices
  13581. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13582. for ( let i = 1; i <= radialSegments; i ++ ) {
  13583. // indices
  13584. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13585. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13586. const c = ( radialSegments + 1 ) * j + i;
  13587. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13588. // faces
  13589. indices.push( a, b, d );
  13590. indices.push( b, c, d );
  13591. }
  13592. }
  13593. // build geometry
  13594. this.setIndex( indices );
  13595. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13596. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13597. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13598. // this function calculates the current position on the torus curve
  13599. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13600. const cu = Math.cos( u );
  13601. const su = Math.sin( u );
  13602. const quOverP = q / p * u;
  13603. const cs = Math.cos( quOverP );
  13604. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13605. position.y = radius * ( 2 + cs ) * su * 0.5;
  13606. position.z = radius * Math.sin( quOverP ) * 0.5;
  13607. }
  13608. }
  13609. copy( source ) {
  13610. super.copy( source );
  13611. this.parameters = Object.assign( {}, source.parameters );
  13612. return this;
  13613. }
  13614. static fromJSON( data ) {
  13615. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13616. }
  13617. }
  13618. class TubeGeometry extends BufferGeometry {
  13619. 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 ) {
  13620. super();
  13621. this.type = 'TubeGeometry';
  13622. this.parameters = {
  13623. path: path,
  13624. tubularSegments: tubularSegments,
  13625. radius: radius,
  13626. radialSegments: radialSegments,
  13627. closed: closed
  13628. };
  13629. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13630. // expose internals
  13631. this.tangents = frames.tangents;
  13632. this.normals = frames.normals;
  13633. this.binormals = frames.binormals;
  13634. // helper variables
  13635. const vertex = new Vector3();
  13636. const normal = new Vector3();
  13637. const uv = new Vector2();
  13638. let P = new Vector3();
  13639. // buffer
  13640. const vertices = [];
  13641. const normals = [];
  13642. const uvs = [];
  13643. const indices = [];
  13644. // create buffer data
  13645. generateBufferData();
  13646. // build geometry
  13647. this.setIndex( indices );
  13648. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13649. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13650. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13651. // functions
  13652. function generateBufferData() {
  13653. for ( let i = 0; i < tubularSegments; i ++ ) {
  13654. generateSegment( i );
  13655. }
  13656. // if the geometry is not closed, generate the last row of vertices and normals
  13657. // at the regular position on the given path
  13658. //
  13659. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13660. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13661. // uvs are generated in a separate function.
  13662. // this makes it easy compute correct values for closed geometries
  13663. generateUVs();
  13664. // finally create faces
  13665. generateIndices();
  13666. }
  13667. function generateSegment( i ) {
  13668. // we use getPointAt to sample evenly distributed points from the given path
  13669. P = path.getPointAt( i / tubularSegments, P );
  13670. // retrieve corresponding normal and binormal
  13671. const N = frames.normals[ i ];
  13672. const B = frames.binormals[ i ];
  13673. // generate normals and vertices for the current segment
  13674. for ( let j = 0; j <= radialSegments; j ++ ) {
  13675. const v = j / radialSegments * Math.PI * 2;
  13676. const sin = Math.sin( v );
  13677. const cos = - Math.cos( v );
  13678. // normal
  13679. normal.x = ( cos * N.x + sin * B.x );
  13680. normal.y = ( cos * N.y + sin * B.y );
  13681. normal.z = ( cos * N.z + sin * B.z );
  13682. normal.normalize();
  13683. normals.push( normal.x, normal.y, normal.z );
  13684. // vertex
  13685. vertex.x = P.x + radius * normal.x;
  13686. vertex.y = P.y + radius * normal.y;
  13687. vertex.z = P.z + radius * normal.z;
  13688. vertices.push( vertex.x, vertex.y, vertex.z );
  13689. }
  13690. }
  13691. function generateIndices() {
  13692. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13693. for ( let i = 1; i <= radialSegments; i ++ ) {
  13694. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13695. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13696. const c = ( radialSegments + 1 ) * j + i;
  13697. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13698. // faces
  13699. indices.push( a, b, d );
  13700. indices.push( b, c, d );
  13701. }
  13702. }
  13703. }
  13704. function generateUVs() {
  13705. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13706. for ( let j = 0; j <= radialSegments; j ++ ) {
  13707. uv.x = i / tubularSegments;
  13708. uv.y = j / radialSegments;
  13709. uvs.push( uv.x, uv.y );
  13710. }
  13711. }
  13712. }
  13713. }
  13714. copy( source ) {
  13715. super.copy( source );
  13716. this.parameters = Object.assign( {}, source.parameters );
  13717. return this;
  13718. }
  13719. toJSON() {
  13720. const data = super.toJSON();
  13721. data.path = this.parameters.path.toJSON();
  13722. return data;
  13723. }
  13724. static fromJSON( data ) {
  13725. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13726. // User defined curves or instances of CurvePath will not be deserialized.
  13727. return new TubeGeometry(
  13728. new Curves[ data.path.type ]().fromJSON( data.path ),
  13729. data.tubularSegments,
  13730. data.radius,
  13731. data.radialSegments,
  13732. data.closed
  13733. );
  13734. }
  13735. }
  13736. class WireframeGeometry extends BufferGeometry {
  13737. constructor( geometry = null ) {
  13738. super();
  13739. this.type = 'WireframeGeometry';
  13740. this.parameters = {
  13741. geometry: geometry
  13742. };
  13743. if ( geometry !== null ) {
  13744. // buffer
  13745. const vertices = [];
  13746. const edges = new Set();
  13747. // helper variables
  13748. const start = new Vector3();
  13749. const end = new Vector3();
  13750. if ( geometry.index !== null ) {
  13751. // indexed BufferGeometry
  13752. const position = geometry.attributes.position;
  13753. const indices = geometry.index;
  13754. let groups = geometry.groups;
  13755. if ( groups.length === 0 ) {
  13756. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13757. }
  13758. // create a data structure that contains all edges without duplicates
  13759. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13760. const group = groups[ o ];
  13761. const groupStart = group.start;
  13762. const groupCount = group.count;
  13763. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13764. for ( let j = 0; j < 3; j ++ ) {
  13765. const index1 = indices.getX( i + j );
  13766. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13767. start.fromBufferAttribute( position, index1 );
  13768. end.fromBufferAttribute( position, index2 );
  13769. if ( isUniqueEdge( start, end, edges ) === true ) {
  13770. vertices.push( start.x, start.y, start.z );
  13771. vertices.push( end.x, end.y, end.z );
  13772. }
  13773. }
  13774. }
  13775. }
  13776. } else {
  13777. // non-indexed BufferGeometry
  13778. const position = geometry.attributes.position;
  13779. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13780. for ( let j = 0; j < 3; j ++ ) {
  13781. // three edges per triangle, an edge is represented as (index1, index2)
  13782. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13783. const index1 = 3 * i + j;
  13784. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13785. start.fromBufferAttribute( position, index1 );
  13786. end.fromBufferAttribute( position, index2 );
  13787. if ( isUniqueEdge( start, end, edges ) === true ) {
  13788. vertices.push( start.x, start.y, start.z );
  13789. vertices.push( end.x, end.y, end.z );
  13790. }
  13791. }
  13792. }
  13793. }
  13794. // build geometry
  13795. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13796. }
  13797. }
  13798. copy( source ) {
  13799. super.copy( source );
  13800. this.parameters = Object.assign( {}, source.parameters );
  13801. return this;
  13802. }
  13803. }
  13804. function isUniqueEdge( start, end, edges ) {
  13805. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13806. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13807. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13808. return false;
  13809. } else {
  13810. edges.add( hash1 );
  13811. edges.add( hash2 );
  13812. return true;
  13813. }
  13814. }
  13815. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13816. __proto__: null,
  13817. BoxGeometry: BoxGeometry,
  13818. CapsuleGeometry: CapsuleGeometry,
  13819. CircleGeometry: CircleGeometry,
  13820. ConeGeometry: ConeGeometry,
  13821. CylinderGeometry: CylinderGeometry,
  13822. DodecahedronGeometry: DodecahedronGeometry,
  13823. EdgesGeometry: EdgesGeometry,
  13824. ExtrudeGeometry: ExtrudeGeometry,
  13825. IcosahedronGeometry: IcosahedronGeometry,
  13826. LatheGeometry: LatheGeometry,
  13827. OctahedronGeometry: OctahedronGeometry,
  13828. PlaneGeometry: PlaneGeometry,
  13829. PolyhedronGeometry: PolyhedronGeometry,
  13830. RingGeometry: RingGeometry,
  13831. ShapeGeometry: ShapeGeometry,
  13832. SphereGeometry: SphereGeometry,
  13833. TetrahedronGeometry: TetrahedronGeometry,
  13834. TorusGeometry: TorusGeometry,
  13835. TorusKnotGeometry: TorusKnotGeometry,
  13836. TubeGeometry: TubeGeometry,
  13837. WireframeGeometry: WireframeGeometry
  13838. });
  13839. class ShadowMaterial extends Material {
  13840. constructor( parameters ) {
  13841. super();
  13842. this.isShadowMaterial = true;
  13843. this.type = 'ShadowMaterial';
  13844. this.color = new Color( 0x000000 );
  13845. this.transparent = true;
  13846. this.fog = true;
  13847. this.setValues( parameters );
  13848. }
  13849. copy( source ) {
  13850. super.copy( source );
  13851. this.color.copy( source.color );
  13852. this.fog = source.fog;
  13853. return this;
  13854. }
  13855. }
  13856. class RawShaderMaterial extends ShaderMaterial {
  13857. constructor( parameters ) {
  13858. super( parameters );
  13859. this.isRawShaderMaterial = true;
  13860. this.type = 'RawShaderMaterial';
  13861. }
  13862. }
  13863. class MeshStandardMaterial extends Material {
  13864. constructor( parameters ) {
  13865. super();
  13866. this.isMeshStandardMaterial = true;
  13867. this.defines = { 'STANDARD': '' };
  13868. this.type = 'MeshStandardMaterial';
  13869. this.color = new Color( 0xffffff ); // diffuse
  13870. this.roughness = 1.0;
  13871. this.metalness = 0.0;
  13872. this.map = null;
  13873. this.lightMap = null;
  13874. this.lightMapIntensity = 1.0;
  13875. this.aoMap = null;
  13876. this.aoMapIntensity = 1.0;
  13877. this.emissive = new Color( 0x000000 );
  13878. this.emissiveIntensity = 1.0;
  13879. this.emissiveMap = null;
  13880. this.bumpMap = null;
  13881. this.bumpScale = 1;
  13882. this.normalMap = null;
  13883. this.normalMapType = TangentSpaceNormalMap;
  13884. this.normalScale = new Vector2( 1, 1 );
  13885. this.displacementMap = null;
  13886. this.displacementScale = 1;
  13887. this.displacementBias = 0;
  13888. this.roughnessMap = null;
  13889. this.metalnessMap = null;
  13890. this.alphaMap = null;
  13891. this.envMap = null;
  13892. this.envMapRotation = new Euler();
  13893. this.envMapIntensity = 1.0;
  13894. this.wireframe = false;
  13895. this.wireframeLinewidth = 1;
  13896. this.wireframeLinecap = 'round';
  13897. this.wireframeLinejoin = 'round';
  13898. this.flatShading = false;
  13899. this.fog = true;
  13900. this.setValues( parameters );
  13901. }
  13902. copy( source ) {
  13903. super.copy( source );
  13904. this.defines = { 'STANDARD': '' };
  13905. this.color.copy( source.color );
  13906. this.roughness = source.roughness;
  13907. this.metalness = source.metalness;
  13908. this.map = source.map;
  13909. this.lightMap = source.lightMap;
  13910. this.lightMapIntensity = source.lightMapIntensity;
  13911. this.aoMap = source.aoMap;
  13912. this.aoMapIntensity = source.aoMapIntensity;
  13913. this.emissive.copy( source.emissive );
  13914. this.emissiveMap = source.emissiveMap;
  13915. this.emissiveIntensity = source.emissiveIntensity;
  13916. this.bumpMap = source.bumpMap;
  13917. this.bumpScale = source.bumpScale;
  13918. this.normalMap = source.normalMap;
  13919. this.normalMapType = source.normalMapType;
  13920. this.normalScale.copy( source.normalScale );
  13921. this.displacementMap = source.displacementMap;
  13922. this.displacementScale = source.displacementScale;
  13923. this.displacementBias = source.displacementBias;
  13924. this.roughnessMap = source.roughnessMap;
  13925. this.metalnessMap = source.metalnessMap;
  13926. this.alphaMap = source.alphaMap;
  13927. this.envMap = source.envMap;
  13928. this.envMapRotation.copy( source.envMapRotation );
  13929. this.envMapIntensity = source.envMapIntensity;
  13930. this.wireframe = source.wireframe;
  13931. this.wireframeLinewidth = source.wireframeLinewidth;
  13932. this.wireframeLinecap = source.wireframeLinecap;
  13933. this.wireframeLinejoin = source.wireframeLinejoin;
  13934. this.flatShading = source.flatShading;
  13935. this.fog = source.fog;
  13936. return this;
  13937. }
  13938. }
  13939. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13940. constructor( parameters ) {
  13941. super();
  13942. this.isMeshPhysicalMaterial = true;
  13943. this.defines = {
  13944. 'STANDARD': '',
  13945. 'PHYSICAL': ''
  13946. };
  13947. this.type = 'MeshPhysicalMaterial';
  13948. this.anisotropyRotation = 0;
  13949. this.anisotropyMap = null;
  13950. this.clearcoatMap = null;
  13951. this.clearcoatRoughness = 0.0;
  13952. this.clearcoatRoughnessMap = null;
  13953. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13954. this.clearcoatNormalMap = null;
  13955. this.ior = 1.5;
  13956. Object.defineProperty( this, 'reflectivity', {
  13957. get: function () {
  13958. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13959. },
  13960. set: function ( reflectivity ) {
  13961. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13962. }
  13963. } );
  13964. this.iridescenceMap = null;
  13965. this.iridescenceIOR = 1.3;
  13966. this.iridescenceThicknessRange = [ 100, 400 ];
  13967. this.iridescenceThicknessMap = null;
  13968. this.sheenColor = new Color( 0x000000 );
  13969. this.sheenColorMap = null;
  13970. this.sheenRoughness = 1.0;
  13971. this.sheenRoughnessMap = null;
  13972. this.transmissionMap = null;
  13973. this.thickness = 0;
  13974. this.thicknessMap = null;
  13975. this.attenuationDistance = Infinity;
  13976. this.attenuationColor = new Color( 1, 1, 1 );
  13977. this.specularIntensity = 1.0;
  13978. this.specularIntensityMap = null;
  13979. this.specularColor = new Color( 1, 1, 1 );
  13980. this.specularColorMap = null;
  13981. this._anisotropy = 0;
  13982. this._clearcoat = 0;
  13983. this._dispersion = 0;
  13984. this._iridescence = 0;
  13985. this._sheen = 0.0;
  13986. this._transmission = 0;
  13987. this.setValues( parameters );
  13988. }
  13989. get anisotropy() {
  13990. return this._anisotropy;
  13991. }
  13992. set anisotropy( value ) {
  13993. if ( this._anisotropy > 0 !== value > 0 ) {
  13994. this.version ++;
  13995. }
  13996. this._anisotropy = value;
  13997. }
  13998. get clearcoat() {
  13999. return this._clearcoat;
  14000. }
  14001. set clearcoat( value ) {
  14002. if ( this._clearcoat > 0 !== value > 0 ) {
  14003. this.version ++;
  14004. }
  14005. this._clearcoat = value;
  14006. }
  14007. get iridescence() {
  14008. return this._iridescence;
  14009. }
  14010. set iridescence( value ) {
  14011. if ( this._iridescence > 0 !== value > 0 ) {
  14012. this.version ++;
  14013. }
  14014. this._iridescence = value;
  14015. }
  14016. get dispersion() {
  14017. return this._dispersion;
  14018. }
  14019. set dispersion( value ) {
  14020. if ( this._dispersion > 0 !== value > 0 ) {
  14021. this.version ++;
  14022. }
  14023. this._dispersion = value;
  14024. }
  14025. get sheen() {
  14026. return this._sheen;
  14027. }
  14028. set sheen( value ) {
  14029. if ( this._sheen > 0 !== value > 0 ) {
  14030. this.version ++;
  14031. }
  14032. this._sheen = value;
  14033. }
  14034. get transmission() {
  14035. return this._transmission;
  14036. }
  14037. set transmission( value ) {
  14038. if ( this._transmission > 0 !== value > 0 ) {
  14039. this.version ++;
  14040. }
  14041. this._transmission = value;
  14042. }
  14043. copy( source ) {
  14044. super.copy( source );
  14045. this.defines = {
  14046. 'STANDARD': '',
  14047. 'PHYSICAL': ''
  14048. };
  14049. this.anisotropy = source.anisotropy;
  14050. this.anisotropyRotation = source.anisotropyRotation;
  14051. this.anisotropyMap = source.anisotropyMap;
  14052. this.clearcoat = source.clearcoat;
  14053. this.clearcoatMap = source.clearcoatMap;
  14054. this.clearcoatRoughness = source.clearcoatRoughness;
  14055. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14056. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14057. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14058. this.dispersion = source.dispersion;
  14059. this.ior = source.ior;
  14060. this.iridescence = source.iridescence;
  14061. this.iridescenceMap = source.iridescenceMap;
  14062. this.iridescenceIOR = source.iridescenceIOR;
  14063. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14064. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14065. this.sheen = source.sheen;
  14066. this.sheenColor.copy( source.sheenColor );
  14067. this.sheenColorMap = source.sheenColorMap;
  14068. this.sheenRoughness = source.sheenRoughness;
  14069. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14070. this.transmission = source.transmission;
  14071. this.transmissionMap = source.transmissionMap;
  14072. this.thickness = source.thickness;
  14073. this.thicknessMap = source.thicknessMap;
  14074. this.attenuationDistance = source.attenuationDistance;
  14075. this.attenuationColor.copy( source.attenuationColor );
  14076. this.specularIntensity = source.specularIntensity;
  14077. this.specularIntensityMap = source.specularIntensityMap;
  14078. this.specularColor.copy( source.specularColor );
  14079. this.specularColorMap = source.specularColorMap;
  14080. return this;
  14081. }
  14082. }
  14083. class MeshPhongMaterial extends Material {
  14084. constructor( parameters ) {
  14085. super();
  14086. this.isMeshPhongMaterial = true;
  14087. this.type = 'MeshPhongMaterial';
  14088. this.color = new Color( 0xffffff ); // diffuse
  14089. this.specular = new Color( 0x111111 );
  14090. this.shininess = 30;
  14091. this.map = null;
  14092. this.lightMap = null;
  14093. this.lightMapIntensity = 1.0;
  14094. this.aoMap = null;
  14095. this.aoMapIntensity = 1.0;
  14096. this.emissive = new Color( 0x000000 );
  14097. this.emissiveIntensity = 1.0;
  14098. this.emissiveMap = null;
  14099. this.bumpMap = null;
  14100. this.bumpScale = 1;
  14101. this.normalMap = null;
  14102. this.normalMapType = TangentSpaceNormalMap;
  14103. this.normalScale = new Vector2( 1, 1 );
  14104. this.displacementMap = null;
  14105. this.displacementScale = 1;
  14106. this.displacementBias = 0;
  14107. this.specularMap = null;
  14108. this.alphaMap = null;
  14109. this.envMap = null;
  14110. this.envMapRotation = new Euler();
  14111. this.combine = MultiplyOperation;
  14112. this.reflectivity = 1;
  14113. this.refractionRatio = 0.98;
  14114. this.wireframe = false;
  14115. this.wireframeLinewidth = 1;
  14116. this.wireframeLinecap = 'round';
  14117. this.wireframeLinejoin = 'round';
  14118. this.flatShading = false;
  14119. this.fog = true;
  14120. this.setValues( parameters );
  14121. }
  14122. copy( source ) {
  14123. super.copy( source );
  14124. this.color.copy( source.color );
  14125. this.specular.copy( source.specular );
  14126. this.shininess = source.shininess;
  14127. this.map = source.map;
  14128. this.lightMap = source.lightMap;
  14129. this.lightMapIntensity = source.lightMapIntensity;
  14130. this.aoMap = source.aoMap;
  14131. this.aoMapIntensity = source.aoMapIntensity;
  14132. this.emissive.copy( source.emissive );
  14133. this.emissiveMap = source.emissiveMap;
  14134. this.emissiveIntensity = source.emissiveIntensity;
  14135. this.bumpMap = source.bumpMap;
  14136. this.bumpScale = source.bumpScale;
  14137. this.normalMap = source.normalMap;
  14138. this.normalMapType = source.normalMapType;
  14139. this.normalScale.copy( source.normalScale );
  14140. this.displacementMap = source.displacementMap;
  14141. this.displacementScale = source.displacementScale;
  14142. this.displacementBias = source.displacementBias;
  14143. this.specularMap = source.specularMap;
  14144. this.alphaMap = source.alphaMap;
  14145. this.envMap = source.envMap;
  14146. this.envMapRotation.copy( source.envMapRotation );
  14147. this.combine = source.combine;
  14148. this.reflectivity = source.reflectivity;
  14149. this.refractionRatio = source.refractionRatio;
  14150. this.wireframe = source.wireframe;
  14151. this.wireframeLinewidth = source.wireframeLinewidth;
  14152. this.wireframeLinecap = source.wireframeLinecap;
  14153. this.wireframeLinejoin = source.wireframeLinejoin;
  14154. this.flatShading = source.flatShading;
  14155. this.fog = source.fog;
  14156. return this;
  14157. }
  14158. }
  14159. class MeshToonMaterial extends Material {
  14160. constructor( parameters ) {
  14161. super();
  14162. this.isMeshToonMaterial = true;
  14163. this.defines = { 'TOON': '' };
  14164. this.type = 'MeshToonMaterial';
  14165. this.color = new Color( 0xffffff );
  14166. this.map = null;
  14167. this.gradientMap = null;
  14168. this.lightMap = null;
  14169. this.lightMapIntensity = 1.0;
  14170. this.aoMap = null;
  14171. this.aoMapIntensity = 1.0;
  14172. this.emissive = new Color( 0x000000 );
  14173. this.emissiveIntensity = 1.0;
  14174. this.emissiveMap = null;
  14175. this.bumpMap = null;
  14176. this.bumpScale = 1;
  14177. this.normalMap = null;
  14178. this.normalMapType = TangentSpaceNormalMap;
  14179. this.normalScale = new Vector2( 1, 1 );
  14180. this.displacementMap = null;
  14181. this.displacementScale = 1;
  14182. this.displacementBias = 0;
  14183. this.alphaMap = null;
  14184. this.wireframe = false;
  14185. this.wireframeLinewidth = 1;
  14186. this.wireframeLinecap = 'round';
  14187. this.wireframeLinejoin = 'round';
  14188. this.fog = true;
  14189. this.setValues( parameters );
  14190. }
  14191. copy( source ) {
  14192. super.copy( source );
  14193. this.color.copy( source.color );
  14194. this.map = source.map;
  14195. this.gradientMap = source.gradientMap;
  14196. this.lightMap = source.lightMap;
  14197. this.lightMapIntensity = source.lightMapIntensity;
  14198. this.aoMap = source.aoMap;
  14199. this.aoMapIntensity = source.aoMapIntensity;
  14200. this.emissive.copy( source.emissive );
  14201. this.emissiveMap = source.emissiveMap;
  14202. this.emissiveIntensity = source.emissiveIntensity;
  14203. this.bumpMap = source.bumpMap;
  14204. this.bumpScale = source.bumpScale;
  14205. this.normalMap = source.normalMap;
  14206. this.normalMapType = source.normalMapType;
  14207. this.normalScale.copy( source.normalScale );
  14208. this.displacementMap = source.displacementMap;
  14209. this.displacementScale = source.displacementScale;
  14210. this.displacementBias = source.displacementBias;
  14211. this.alphaMap = source.alphaMap;
  14212. this.wireframe = source.wireframe;
  14213. this.wireframeLinewidth = source.wireframeLinewidth;
  14214. this.wireframeLinecap = source.wireframeLinecap;
  14215. this.wireframeLinejoin = source.wireframeLinejoin;
  14216. this.fog = source.fog;
  14217. return this;
  14218. }
  14219. }
  14220. class MeshNormalMaterial extends Material {
  14221. constructor( parameters ) {
  14222. super();
  14223. this.isMeshNormalMaterial = true;
  14224. this.type = 'MeshNormalMaterial';
  14225. this.bumpMap = null;
  14226. this.bumpScale = 1;
  14227. this.normalMap = null;
  14228. this.normalMapType = TangentSpaceNormalMap;
  14229. this.normalScale = new Vector2( 1, 1 );
  14230. this.displacementMap = null;
  14231. this.displacementScale = 1;
  14232. this.displacementBias = 0;
  14233. this.wireframe = false;
  14234. this.wireframeLinewidth = 1;
  14235. this.flatShading = false;
  14236. this.setValues( parameters );
  14237. }
  14238. copy( source ) {
  14239. super.copy( source );
  14240. this.bumpMap = source.bumpMap;
  14241. this.bumpScale = source.bumpScale;
  14242. this.normalMap = source.normalMap;
  14243. this.normalMapType = source.normalMapType;
  14244. this.normalScale.copy( source.normalScale );
  14245. this.displacementMap = source.displacementMap;
  14246. this.displacementScale = source.displacementScale;
  14247. this.displacementBias = source.displacementBias;
  14248. this.wireframe = source.wireframe;
  14249. this.wireframeLinewidth = source.wireframeLinewidth;
  14250. this.flatShading = source.flatShading;
  14251. return this;
  14252. }
  14253. }
  14254. class MeshLambertMaterial extends Material {
  14255. constructor( parameters ) {
  14256. super();
  14257. this.isMeshLambertMaterial = true;
  14258. this.type = 'MeshLambertMaterial';
  14259. this.color = new Color( 0xffffff ); // diffuse
  14260. this.map = null;
  14261. this.lightMap = null;
  14262. this.lightMapIntensity = 1.0;
  14263. this.aoMap = null;
  14264. this.aoMapIntensity = 1.0;
  14265. this.emissive = new Color( 0x000000 );
  14266. this.emissiveIntensity = 1.0;
  14267. this.emissiveMap = null;
  14268. this.bumpMap = null;
  14269. this.bumpScale = 1;
  14270. this.normalMap = null;
  14271. this.normalMapType = TangentSpaceNormalMap;
  14272. this.normalScale = new Vector2( 1, 1 );
  14273. this.displacementMap = null;
  14274. this.displacementScale = 1;
  14275. this.displacementBias = 0;
  14276. this.specularMap = null;
  14277. this.alphaMap = null;
  14278. this.envMap = null;
  14279. this.envMapRotation = new Euler();
  14280. this.combine = MultiplyOperation;
  14281. this.reflectivity = 1;
  14282. this.refractionRatio = 0.98;
  14283. this.wireframe = false;
  14284. this.wireframeLinewidth = 1;
  14285. this.wireframeLinecap = 'round';
  14286. this.wireframeLinejoin = 'round';
  14287. this.flatShading = false;
  14288. this.fog = true;
  14289. this.setValues( parameters );
  14290. }
  14291. copy( source ) {
  14292. super.copy( source );
  14293. this.color.copy( source.color );
  14294. this.map = source.map;
  14295. this.lightMap = source.lightMap;
  14296. this.lightMapIntensity = source.lightMapIntensity;
  14297. this.aoMap = source.aoMap;
  14298. this.aoMapIntensity = source.aoMapIntensity;
  14299. this.emissive.copy( source.emissive );
  14300. this.emissiveMap = source.emissiveMap;
  14301. this.emissiveIntensity = source.emissiveIntensity;
  14302. this.bumpMap = source.bumpMap;
  14303. this.bumpScale = source.bumpScale;
  14304. this.normalMap = source.normalMap;
  14305. this.normalMapType = source.normalMapType;
  14306. this.normalScale.copy( source.normalScale );
  14307. this.displacementMap = source.displacementMap;
  14308. this.displacementScale = source.displacementScale;
  14309. this.displacementBias = source.displacementBias;
  14310. this.specularMap = source.specularMap;
  14311. this.alphaMap = source.alphaMap;
  14312. this.envMap = source.envMap;
  14313. this.envMapRotation.copy( source.envMapRotation );
  14314. this.combine = source.combine;
  14315. this.reflectivity = source.reflectivity;
  14316. this.refractionRatio = source.refractionRatio;
  14317. this.wireframe = source.wireframe;
  14318. this.wireframeLinewidth = source.wireframeLinewidth;
  14319. this.wireframeLinecap = source.wireframeLinecap;
  14320. this.wireframeLinejoin = source.wireframeLinejoin;
  14321. this.flatShading = source.flatShading;
  14322. this.fog = source.fog;
  14323. return this;
  14324. }
  14325. }
  14326. class MeshDepthMaterial extends Material {
  14327. constructor( parameters ) {
  14328. super();
  14329. this.isMeshDepthMaterial = true;
  14330. this.type = 'MeshDepthMaterial';
  14331. this.depthPacking = BasicDepthPacking;
  14332. this.map = null;
  14333. this.alphaMap = null;
  14334. this.displacementMap = null;
  14335. this.displacementScale = 1;
  14336. this.displacementBias = 0;
  14337. this.wireframe = false;
  14338. this.wireframeLinewidth = 1;
  14339. this.setValues( parameters );
  14340. }
  14341. copy( source ) {
  14342. super.copy( source );
  14343. this.depthPacking = source.depthPacking;
  14344. this.map = source.map;
  14345. this.alphaMap = source.alphaMap;
  14346. this.displacementMap = source.displacementMap;
  14347. this.displacementScale = source.displacementScale;
  14348. this.displacementBias = source.displacementBias;
  14349. this.wireframe = source.wireframe;
  14350. this.wireframeLinewidth = source.wireframeLinewidth;
  14351. return this;
  14352. }
  14353. }
  14354. class MeshDistanceMaterial extends Material {
  14355. constructor( parameters ) {
  14356. super();
  14357. this.isMeshDistanceMaterial = true;
  14358. this.type = 'MeshDistanceMaterial';
  14359. this.map = null;
  14360. this.alphaMap = null;
  14361. this.displacementMap = null;
  14362. this.displacementScale = 1;
  14363. this.displacementBias = 0;
  14364. this.setValues( parameters );
  14365. }
  14366. copy( source ) {
  14367. super.copy( source );
  14368. this.map = source.map;
  14369. this.alphaMap = source.alphaMap;
  14370. this.displacementMap = source.displacementMap;
  14371. this.displacementScale = source.displacementScale;
  14372. this.displacementBias = source.displacementBias;
  14373. return this;
  14374. }
  14375. }
  14376. class MeshMatcapMaterial extends Material {
  14377. constructor( parameters ) {
  14378. super();
  14379. this.isMeshMatcapMaterial = true;
  14380. this.defines = { 'MATCAP': '' };
  14381. this.type = 'MeshMatcapMaterial';
  14382. this.color = new Color( 0xffffff ); // diffuse
  14383. this.matcap = null;
  14384. this.map = null;
  14385. this.bumpMap = null;
  14386. this.bumpScale = 1;
  14387. this.normalMap = null;
  14388. this.normalMapType = TangentSpaceNormalMap;
  14389. this.normalScale = new Vector2( 1, 1 );
  14390. this.displacementMap = null;
  14391. this.displacementScale = 1;
  14392. this.displacementBias = 0;
  14393. this.alphaMap = null;
  14394. this.flatShading = false;
  14395. this.fog = true;
  14396. this.setValues( parameters );
  14397. }
  14398. copy( source ) {
  14399. super.copy( source );
  14400. this.defines = { 'MATCAP': '' };
  14401. this.color.copy( source.color );
  14402. this.matcap = source.matcap;
  14403. this.map = source.map;
  14404. this.bumpMap = source.bumpMap;
  14405. this.bumpScale = source.bumpScale;
  14406. this.normalMap = source.normalMap;
  14407. this.normalMapType = source.normalMapType;
  14408. this.normalScale.copy( source.normalScale );
  14409. this.displacementMap = source.displacementMap;
  14410. this.displacementScale = source.displacementScale;
  14411. this.displacementBias = source.displacementBias;
  14412. this.alphaMap = source.alphaMap;
  14413. this.flatShading = source.flatShading;
  14414. this.fog = source.fog;
  14415. return this;
  14416. }
  14417. }
  14418. class LineDashedMaterial extends LineBasicMaterial {
  14419. constructor( parameters ) {
  14420. super();
  14421. this.isLineDashedMaterial = true;
  14422. this.type = 'LineDashedMaterial';
  14423. this.scale = 1;
  14424. this.dashSize = 3;
  14425. this.gapSize = 1;
  14426. this.setValues( parameters );
  14427. }
  14428. copy( source ) {
  14429. super.copy( source );
  14430. this.scale = source.scale;
  14431. this.dashSize = source.dashSize;
  14432. this.gapSize = source.gapSize;
  14433. return this;
  14434. }
  14435. }
  14436. // converts an array to a specific type
  14437. function convertArray( array, type, forceClone ) {
  14438. if ( ! array || // let 'undefined' and 'null' pass
  14439. ! forceClone && array.constructor === type ) return array;
  14440. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14441. return new type( array ); // create typed array
  14442. }
  14443. return Array.prototype.slice.call( array ); // create Array
  14444. }
  14445. function isTypedArray( object ) {
  14446. return ArrayBuffer.isView( object ) &&
  14447. ! ( object instanceof DataView );
  14448. }
  14449. // returns an array by which times and values can be sorted
  14450. function getKeyframeOrder( times ) {
  14451. function compareTime( i, j ) {
  14452. return times[ i ] - times[ j ];
  14453. }
  14454. const n = times.length;
  14455. const result = new Array( n );
  14456. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14457. result.sort( compareTime );
  14458. return result;
  14459. }
  14460. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14461. function sortedArray( values, stride, order ) {
  14462. const nValues = values.length;
  14463. const result = new values.constructor( nValues );
  14464. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14465. const srcOffset = order[ i ] * stride;
  14466. for ( let j = 0; j !== stride; ++ j ) {
  14467. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14468. }
  14469. }
  14470. return result;
  14471. }
  14472. // function for parsing AOS keyframe formats
  14473. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14474. let i = 1, key = jsonKeys[ 0 ];
  14475. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14476. key = jsonKeys[ i ++ ];
  14477. }
  14478. if ( key === undefined ) return; // no data
  14479. let value = key[ valuePropertyName ];
  14480. if ( value === undefined ) return; // no data
  14481. if ( Array.isArray( value ) ) {
  14482. do {
  14483. value = key[ valuePropertyName ];
  14484. if ( value !== undefined ) {
  14485. times.push( key.time );
  14486. values.push.apply( values, value ); // push all elements
  14487. }
  14488. key = jsonKeys[ i ++ ];
  14489. } while ( key !== undefined );
  14490. } else if ( value.toArray !== undefined ) {
  14491. // ...assume THREE.Math-ish
  14492. do {
  14493. value = key[ valuePropertyName ];
  14494. if ( value !== undefined ) {
  14495. times.push( key.time );
  14496. value.toArray( values, values.length );
  14497. }
  14498. key = jsonKeys[ i ++ ];
  14499. } while ( key !== undefined );
  14500. } else {
  14501. // otherwise push as-is
  14502. do {
  14503. value = key[ valuePropertyName ];
  14504. if ( value !== undefined ) {
  14505. times.push( key.time );
  14506. values.push( value );
  14507. }
  14508. key = jsonKeys[ i ++ ];
  14509. } while ( key !== undefined );
  14510. }
  14511. }
  14512. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14513. const clip = sourceClip.clone();
  14514. clip.name = name;
  14515. const tracks = [];
  14516. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14517. const track = clip.tracks[ i ];
  14518. const valueSize = track.getValueSize();
  14519. const times = [];
  14520. const values = [];
  14521. for ( let j = 0; j < track.times.length; ++ j ) {
  14522. const frame = track.times[ j ] * fps;
  14523. if ( frame < startFrame || frame >= endFrame ) continue;
  14524. times.push( track.times[ j ] );
  14525. for ( let k = 0; k < valueSize; ++ k ) {
  14526. values.push( track.values[ j * valueSize + k ] );
  14527. }
  14528. }
  14529. if ( times.length === 0 ) continue;
  14530. track.times = convertArray( times, track.times.constructor );
  14531. track.values = convertArray( values, track.values.constructor );
  14532. tracks.push( track );
  14533. }
  14534. clip.tracks = tracks;
  14535. // find minimum .times value across all tracks in the trimmed clip
  14536. let minStartTime = Infinity;
  14537. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14538. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14539. minStartTime = clip.tracks[ i ].times[ 0 ];
  14540. }
  14541. }
  14542. // shift all tracks such that clip begins at t=0
  14543. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14544. clip.tracks[ i ].shift( - 1 * minStartTime );
  14545. }
  14546. clip.resetDuration();
  14547. return clip;
  14548. }
  14549. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14550. if ( fps <= 0 ) fps = 30;
  14551. const numTracks = referenceClip.tracks.length;
  14552. const referenceTime = referenceFrame / fps;
  14553. // Make each track's values relative to the values at the reference frame
  14554. for ( let i = 0; i < numTracks; ++ i ) {
  14555. const referenceTrack = referenceClip.tracks[ i ];
  14556. const referenceTrackType = referenceTrack.ValueTypeName;
  14557. // Skip this track if it's non-numeric
  14558. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14559. // Find the track in the target clip whose name and type matches the reference track
  14560. const targetTrack = targetClip.tracks.find( function ( track ) {
  14561. return track.name === referenceTrack.name
  14562. && track.ValueTypeName === referenceTrackType;
  14563. } );
  14564. if ( targetTrack === undefined ) continue;
  14565. let referenceOffset = 0;
  14566. const referenceValueSize = referenceTrack.getValueSize();
  14567. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14568. referenceOffset = referenceValueSize / 3;
  14569. }
  14570. let targetOffset = 0;
  14571. const targetValueSize = targetTrack.getValueSize();
  14572. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14573. targetOffset = targetValueSize / 3;
  14574. }
  14575. const lastIndex = referenceTrack.times.length - 1;
  14576. let referenceValue;
  14577. // Find the value to subtract out of the track
  14578. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14579. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14580. const startIndex = referenceOffset;
  14581. const endIndex = referenceValueSize - referenceOffset;
  14582. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14583. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14584. // Reference frame is after the last keyframe, so just use the last keyframe
  14585. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14586. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14587. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14588. } else {
  14589. // Interpolate to the reference value
  14590. const interpolant = referenceTrack.createInterpolant();
  14591. const startIndex = referenceOffset;
  14592. const endIndex = referenceValueSize - referenceOffset;
  14593. interpolant.evaluate( referenceTime );
  14594. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14595. }
  14596. // Conjugate the quaternion
  14597. if ( referenceTrackType === 'quaternion' ) {
  14598. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14599. referenceQuat.toArray( referenceValue );
  14600. }
  14601. // Subtract the reference value from all of the track values
  14602. const numTimes = targetTrack.times.length;
  14603. for ( let j = 0; j < numTimes; ++ j ) {
  14604. const valueStart = j * targetValueSize + targetOffset;
  14605. if ( referenceTrackType === 'quaternion' ) {
  14606. // Multiply the conjugate for quaternion track types
  14607. Quaternion.multiplyQuaternionsFlat(
  14608. targetTrack.values,
  14609. valueStart,
  14610. referenceValue,
  14611. 0,
  14612. targetTrack.values,
  14613. valueStart
  14614. );
  14615. } else {
  14616. const valueEnd = targetValueSize - targetOffset * 2;
  14617. // Subtract each value for all other numeric track types
  14618. for ( let k = 0; k < valueEnd; ++ k ) {
  14619. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14620. }
  14621. }
  14622. }
  14623. }
  14624. targetClip.blendMode = AdditiveAnimationBlendMode;
  14625. return targetClip;
  14626. }
  14627. const AnimationUtils = {
  14628. convertArray: convertArray,
  14629. isTypedArray: isTypedArray,
  14630. getKeyframeOrder: getKeyframeOrder,
  14631. sortedArray: sortedArray,
  14632. flattenJSON: flattenJSON,
  14633. subclip: subclip,
  14634. makeClipAdditive: makeClipAdditive
  14635. };
  14636. /**
  14637. * Abstract base class of interpolants over parametric samples.
  14638. *
  14639. * The parameter domain is one dimensional, typically the time or a path
  14640. * along a curve defined by the data.
  14641. *
  14642. * The sample values can have any dimensionality and derived classes may
  14643. * apply special interpretations to the data.
  14644. *
  14645. * This class provides the interval seek in a Template Method, deferring
  14646. * the actual interpolation to derived classes.
  14647. *
  14648. * Time complexity is O(1) for linear access crossing at most two points
  14649. * and O(log N) for random access, where N is the number of positions.
  14650. *
  14651. * References:
  14652. *
  14653. * http://www.oodesign.com/template-method-pattern.html
  14654. *
  14655. */
  14656. class Interpolant {
  14657. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14658. this.parameterPositions = parameterPositions;
  14659. this._cachedIndex = 0;
  14660. this.resultBuffer = resultBuffer !== undefined ?
  14661. resultBuffer : new sampleValues.constructor( sampleSize );
  14662. this.sampleValues = sampleValues;
  14663. this.valueSize = sampleSize;
  14664. this.settings = null;
  14665. this.DefaultSettings_ = {};
  14666. }
  14667. evaluate( t ) {
  14668. const pp = this.parameterPositions;
  14669. let i1 = this._cachedIndex,
  14670. t1 = pp[ i1 ],
  14671. t0 = pp[ i1 - 1 ];
  14672. validate_interval: {
  14673. seek: {
  14674. let right;
  14675. linear_scan: {
  14676. //- See http://jsperf.com/comparison-to-undefined/3
  14677. //- slower code:
  14678. //-
  14679. //- if ( t >= t1 || t1 === undefined ) {
  14680. forward_scan: if ( ! ( t < t1 ) ) {
  14681. for ( let giveUpAt = i1 + 2; ; ) {
  14682. if ( t1 === undefined ) {
  14683. if ( t < t0 ) break forward_scan;
  14684. // after end
  14685. i1 = pp.length;
  14686. this._cachedIndex = i1;
  14687. return this.copySampleValue_( i1 - 1 );
  14688. }
  14689. if ( i1 === giveUpAt ) break; // this loop
  14690. t0 = t1;
  14691. t1 = pp[ ++ i1 ];
  14692. if ( t < t1 ) {
  14693. // we have arrived at the sought interval
  14694. break seek;
  14695. }
  14696. }
  14697. // prepare binary search on the right side of the index
  14698. right = pp.length;
  14699. break linear_scan;
  14700. }
  14701. //- slower code:
  14702. //- if ( t < t0 || t0 === undefined ) {
  14703. if ( ! ( t >= t0 ) ) {
  14704. // looping?
  14705. const t1global = pp[ 1 ];
  14706. if ( t < t1global ) {
  14707. i1 = 2; // + 1, using the scan for the details
  14708. t0 = t1global;
  14709. }
  14710. // linear reverse scan
  14711. for ( let giveUpAt = i1 - 2; ; ) {
  14712. if ( t0 === undefined ) {
  14713. // before start
  14714. this._cachedIndex = 0;
  14715. return this.copySampleValue_( 0 );
  14716. }
  14717. if ( i1 === giveUpAt ) break; // this loop
  14718. t1 = t0;
  14719. t0 = pp[ -- i1 - 1 ];
  14720. if ( t >= t0 ) {
  14721. // we have arrived at the sought interval
  14722. break seek;
  14723. }
  14724. }
  14725. // prepare binary search on the left side of the index
  14726. right = i1;
  14727. i1 = 0;
  14728. break linear_scan;
  14729. }
  14730. // the interval is valid
  14731. break validate_interval;
  14732. } // linear scan
  14733. // binary search
  14734. while ( i1 < right ) {
  14735. const mid = ( i1 + right ) >>> 1;
  14736. if ( t < pp[ mid ] ) {
  14737. right = mid;
  14738. } else {
  14739. i1 = mid + 1;
  14740. }
  14741. }
  14742. t1 = pp[ i1 ];
  14743. t0 = pp[ i1 - 1 ];
  14744. // check boundary cases, again
  14745. if ( t0 === undefined ) {
  14746. this._cachedIndex = 0;
  14747. return this.copySampleValue_( 0 );
  14748. }
  14749. if ( t1 === undefined ) {
  14750. i1 = pp.length;
  14751. this._cachedIndex = i1;
  14752. return this.copySampleValue_( i1 - 1 );
  14753. }
  14754. } // seek
  14755. this._cachedIndex = i1;
  14756. this.intervalChanged_( i1, t0, t1 );
  14757. } // validate_interval
  14758. return this.interpolate_( i1, t0, t, t1 );
  14759. }
  14760. getSettings_() {
  14761. return this.settings || this.DefaultSettings_;
  14762. }
  14763. copySampleValue_( index ) {
  14764. // copies a sample value to the result buffer
  14765. const result = this.resultBuffer,
  14766. values = this.sampleValues,
  14767. stride = this.valueSize,
  14768. offset = index * stride;
  14769. for ( let i = 0; i !== stride; ++ i ) {
  14770. result[ i ] = values[ offset + i ];
  14771. }
  14772. return result;
  14773. }
  14774. // Template methods for derived classes:
  14775. interpolate_( /* i1, t0, t, t1 */ ) {
  14776. throw new Error( 'call to abstract method' );
  14777. // implementations shall return this.resultBuffer
  14778. }
  14779. intervalChanged_( /* i1, t0, t1 */ ) {
  14780. // empty
  14781. }
  14782. }
  14783. /**
  14784. * Fast and simple cubic spline interpolant.
  14785. *
  14786. * It was derived from a Hermitian construction setting the first derivative
  14787. * at each sample position to the linear slope between neighboring positions
  14788. * over their parameter interval.
  14789. */
  14790. class CubicInterpolant extends Interpolant {
  14791. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14792. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14793. this._weightPrev = - 0;
  14794. this._offsetPrev = - 0;
  14795. this._weightNext = - 0;
  14796. this._offsetNext = - 0;
  14797. this.DefaultSettings_ = {
  14798. endingStart: ZeroCurvatureEnding,
  14799. endingEnd: ZeroCurvatureEnding
  14800. };
  14801. }
  14802. intervalChanged_( i1, t0, t1 ) {
  14803. const pp = this.parameterPositions;
  14804. let iPrev = i1 - 2,
  14805. iNext = i1 + 1,
  14806. tPrev = pp[ iPrev ],
  14807. tNext = pp[ iNext ];
  14808. if ( tPrev === undefined ) {
  14809. switch ( this.getSettings_().endingStart ) {
  14810. case ZeroSlopeEnding:
  14811. // f'(t0) = 0
  14812. iPrev = i1;
  14813. tPrev = 2 * t0 - t1;
  14814. break;
  14815. case WrapAroundEnding:
  14816. // use the other end of the curve
  14817. iPrev = pp.length - 2;
  14818. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14819. break;
  14820. default: // ZeroCurvatureEnding
  14821. // f''(t0) = 0 a.k.a. Natural Spline
  14822. iPrev = i1;
  14823. tPrev = t1;
  14824. }
  14825. }
  14826. if ( tNext === undefined ) {
  14827. switch ( this.getSettings_().endingEnd ) {
  14828. case ZeroSlopeEnding:
  14829. // f'(tN) = 0
  14830. iNext = i1;
  14831. tNext = 2 * t1 - t0;
  14832. break;
  14833. case WrapAroundEnding:
  14834. // use the other end of the curve
  14835. iNext = 1;
  14836. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14837. break;
  14838. default: // ZeroCurvatureEnding
  14839. // f''(tN) = 0, a.k.a. Natural Spline
  14840. iNext = i1 - 1;
  14841. tNext = t0;
  14842. }
  14843. }
  14844. const halfDt = ( t1 - t0 ) * 0.5,
  14845. stride = this.valueSize;
  14846. this._weightPrev = halfDt / ( t0 - tPrev );
  14847. this._weightNext = halfDt / ( tNext - t1 );
  14848. this._offsetPrev = iPrev * stride;
  14849. this._offsetNext = iNext * stride;
  14850. }
  14851. interpolate_( i1, t0, t, t1 ) {
  14852. const result = this.resultBuffer,
  14853. values = this.sampleValues,
  14854. stride = this.valueSize,
  14855. o1 = i1 * stride, o0 = o1 - stride,
  14856. oP = this._offsetPrev, oN = this._offsetNext,
  14857. wP = this._weightPrev, wN = this._weightNext,
  14858. p = ( t - t0 ) / ( t1 - t0 ),
  14859. pp = p * p,
  14860. ppp = pp * p;
  14861. // evaluate polynomials
  14862. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14863. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14864. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14865. const sN = wN * ppp - wN * pp;
  14866. // combine data linearly
  14867. for ( let i = 0; i !== stride; ++ i ) {
  14868. result[ i ] =
  14869. sP * values[ oP + i ] +
  14870. s0 * values[ o0 + i ] +
  14871. s1 * values[ o1 + i ] +
  14872. sN * values[ oN + i ];
  14873. }
  14874. return result;
  14875. }
  14876. }
  14877. class LinearInterpolant extends Interpolant {
  14878. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14879. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14880. }
  14881. interpolate_( i1, t0, t, t1 ) {
  14882. const result = this.resultBuffer,
  14883. values = this.sampleValues,
  14884. stride = this.valueSize,
  14885. offset1 = i1 * stride,
  14886. offset0 = offset1 - stride,
  14887. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14888. weight0 = 1 - weight1;
  14889. for ( let i = 0; i !== stride; ++ i ) {
  14890. result[ i ] =
  14891. values[ offset0 + i ] * weight0 +
  14892. values[ offset1 + i ] * weight1;
  14893. }
  14894. return result;
  14895. }
  14896. }
  14897. /**
  14898. *
  14899. * Interpolant that evaluates to the sample value at the position preceding
  14900. * the parameter.
  14901. */
  14902. class DiscreteInterpolant extends Interpolant {
  14903. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14904. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14905. }
  14906. interpolate_( i1 /*, t0, t, t1 */ ) {
  14907. return this.copySampleValue_( i1 - 1 );
  14908. }
  14909. }
  14910. class KeyframeTrack {
  14911. constructor( name, times, values, interpolation ) {
  14912. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14913. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14914. this.name = name;
  14915. this.times = convertArray( times, this.TimeBufferType );
  14916. this.values = convertArray( values, this.ValueBufferType );
  14917. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14918. }
  14919. // Serialization (in static context, because of constructor invocation
  14920. // and automatic invocation of .toJSON):
  14921. static toJSON( track ) {
  14922. const trackType = track.constructor;
  14923. let json;
  14924. // derived classes can define a static toJSON method
  14925. if ( trackType.toJSON !== this.toJSON ) {
  14926. json = trackType.toJSON( track );
  14927. } else {
  14928. // by default, we assume the data can be serialized as-is
  14929. json = {
  14930. 'name': track.name,
  14931. 'times': convertArray( track.times, Array ),
  14932. 'values': convertArray( track.values, Array )
  14933. };
  14934. const interpolation = track.getInterpolation();
  14935. if ( interpolation !== track.DefaultInterpolation ) {
  14936. json.interpolation = interpolation;
  14937. }
  14938. }
  14939. json.type = track.ValueTypeName; // mandatory
  14940. return json;
  14941. }
  14942. InterpolantFactoryMethodDiscrete( result ) {
  14943. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14944. }
  14945. InterpolantFactoryMethodLinear( result ) {
  14946. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14947. }
  14948. InterpolantFactoryMethodSmooth( result ) {
  14949. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14950. }
  14951. setInterpolation( interpolation ) {
  14952. let factoryMethod;
  14953. switch ( interpolation ) {
  14954. case InterpolateDiscrete:
  14955. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14956. break;
  14957. case InterpolateLinear:
  14958. factoryMethod = this.InterpolantFactoryMethodLinear;
  14959. break;
  14960. case InterpolateSmooth:
  14961. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14962. break;
  14963. }
  14964. if ( factoryMethod === undefined ) {
  14965. const message = 'unsupported interpolation for ' +
  14966. this.ValueTypeName + ' keyframe track named ' + this.name;
  14967. if ( this.createInterpolant === undefined ) {
  14968. // fall back to default, unless the default itself is messed up
  14969. if ( interpolation !== this.DefaultInterpolation ) {
  14970. this.setInterpolation( this.DefaultInterpolation );
  14971. } else {
  14972. throw new Error( message ); // fatal, in this case
  14973. }
  14974. }
  14975. console.warn( 'THREE.KeyframeTrack:', message );
  14976. return this;
  14977. }
  14978. this.createInterpolant = factoryMethod;
  14979. return this;
  14980. }
  14981. getInterpolation() {
  14982. switch ( this.createInterpolant ) {
  14983. case this.InterpolantFactoryMethodDiscrete:
  14984. return InterpolateDiscrete;
  14985. case this.InterpolantFactoryMethodLinear:
  14986. return InterpolateLinear;
  14987. case this.InterpolantFactoryMethodSmooth:
  14988. return InterpolateSmooth;
  14989. }
  14990. }
  14991. getValueSize() {
  14992. return this.values.length / this.times.length;
  14993. }
  14994. // move all keyframes either forwards or backwards in time
  14995. shift( timeOffset ) {
  14996. if ( timeOffset !== 0.0 ) {
  14997. const times = this.times;
  14998. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14999. times[ i ] += timeOffset;
  15000. }
  15001. }
  15002. return this;
  15003. }
  15004. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15005. scale( timeScale ) {
  15006. if ( timeScale !== 1.0 ) {
  15007. const times = this.times;
  15008. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15009. times[ i ] *= timeScale;
  15010. }
  15011. }
  15012. return this;
  15013. }
  15014. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15015. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15016. trim( startTime, endTime ) {
  15017. const times = this.times,
  15018. nKeys = times.length;
  15019. let from = 0,
  15020. to = nKeys - 1;
  15021. while ( from !== nKeys && times[ from ] < startTime ) {
  15022. ++ from;
  15023. }
  15024. while ( to !== - 1 && times[ to ] > endTime ) {
  15025. -- to;
  15026. }
  15027. ++ to; // inclusive -> exclusive bound
  15028. if ( from !== 0 || to !== nKeys ) {
  15029. // empty tracks are forbidden, so keep at least one keyframe
  15030. if ( from >= to ) {
  15031. to = Math.max( to, 1 );
  15032. from = to - 1;
  15033. }
  15034. const stride = this.getValueSize();
  15035. this.times = times.slice( from, to );
  15036. this.values = this.values.slice( from * stride, to * stride );
  15037. }
  15038. return this;
  15039. }
  15040. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15041. validate() {
  15042. let valid = true;
  15043. const valueSize = this.getValueSize();
  15044. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15045. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15046. valid = false;
  15047. }
  15048. const times = this.times,
  15049. values = this.values,
  15050. nKeys = times.length;
  15051. if ( nKeys === 0 ) {
  15052. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15053. valid = false;
  15054. }
  15055. let prevTime = null;
  15056. for ( let i = 0; i !== nKeys; i ++ ) {
  15057. const currTime = times[ i ];
  15058. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15059. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15060. valid = false;
  15061. break;
  15062. }
  15063. if ( prevTime !== null && prevTime > currTime ) {
  15064. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15065. valid = false;
  15066. break;
  15067. }
  15068. prevTime = currTime;
  15069. }
  15070. if ( values !== undefined ) {
  15071. if ( isTypedArray( values ) ) {
  15072. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15073. const value = values[ i ];
  15074. if ( isNaN( value ) ) {
  15075. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15076. valid = false;
  15077. break;
  15078. }
  15079. }
  15080. }
  15081. }
  15082. return valid;
  15083. }
  15084. // removes equivalent sequential keys as common in morph target sequences
  15085. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15086. optimize() {
  15087. // times or values may be shared with other tracks, so overwriting is unsafe
  15088. const times = this.times.slice(),
  15089. values = this.values.slice(),
  15090. stride = this.getValueSize(),
  15091. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15092. lastIndex = times.length - 1;
  15093. let writeIndex = 1;
  15094. for ( let i = 1; i < lastIndex; ++ i ) {
  15095. let keep = false;
  15096. const time = times[ i ];
  15097. const timeNext = times[ i + 1 ];
  15098. // remove adjacent keyframes scheduled at the same time
  15099. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15100. if ( ! smoothInterpolation ) {
  15101. // remove unnecessary keyframes same as their neighbors
  15102. const offset = i * stride,
  15103. offsetP = offset - stride,
  15104. offsetN = offset + stride;
  15105. for ( let j = 0; j !== stride; ++ j ) {
  15106. const value = values[ offset + j ];
  15107. if ( value !== values[ offsetP + j ] ||
  15108. value !== values[ offsetN + j ] ) {
  15109. keep = true;
  15110. break;
  15111. }
  15112. }
  15113. } else {
  15114. keep = true;
  15115. }
  15116. }
  15117. // in-place compaction
  15118. if ( keep ) {
  15119. if ( i !== writeIndex ) {
  15120. times[ writeIndex ] = times[ i ];
  15121. const readOffset = i * stride,
  15122. writeOffset = writeIndex * stride;
  15123. for ( let j = 0; j !== stride; ++ j ) {
  15124. values[ writeOffset + j ] = values[ readOffset + j ];
  15125. }
  15126. }
  15127. ++ writeIndex;
  15128. }
  15129. }
  15130. // flush last keyframe (compaction looks ahead)
  15131. if ( lastIndex > 0 ) {
  15132. times[ writeIndex ] = times[ lastIndex ];
  15133. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15134. values[ writeOffset + j ] = values[ readOffset + j ];
  15135. }
  15136. ++ writeIndex;
  15137. }
  15138. if ( writeIndex !== times.length ) {
  15139. this.times = times.slice( 0, writeIndex );
  15140. this.values = values.slice( 0, writeIndex * stride );
  15141. } else {
  15142. this.times = times;
  15143. this.values = values;
  15144. }
  15145. return this;
  15146. }
  15147. clone() {
  15148. const times = this.times.slice();
  15149. const values = this.values.slice();
  15150. const TypedKeyframeTrack = this.constructor;
  15151. const track = new TypedKeyframeTrack( this.name, times, values );
  15152. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15153. track.createInterpolant = this.createInterpolant;
  15154. return track;
  15155. }
  15156. }
  15157. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15158. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15159. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15160. /**
  15161. * A Track of Boolean keyframe values.
  15162. */
  15163. class BooleanKeyframeTrack extends KeyframeTrack {
  15164. // No interpolation parameter because only InterpolateDiscrete is valid.
  15165. constructor( name, times, values ) {
  15166. super( name, times, values );
  15167. }
  15168. }
  15169. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15170. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15171. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15172. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15173. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15174. /**
  15175. * A Track of keyframe values that represent color.
  15176. */
  15177. class ColorKeyframeTrack extends KeyframeTrack {}
  15178. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15179. /**
  15180. * A Track of numeric keyframe values.
  15181. */
  15182. class NumberKeyframeTrack extends KeyframeTrack {}
  15183. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15184. /**
  15185. * Spherical linear unit quaternion interpolant.
  15186. */
  15187. class QuaternionLinearInterpolant extends Interpolant {
  15188. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15189. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15190. }
  15191. interpolate_( i1, t0, t, t1 ) {
  15192. const result = this.resultBuffer,
  15193. values = this.sampleValues,
  15194. stride = this.valueSize,
  15195. alpha = ( t - t0 ) / ( t1 - t0 );
  15196. let offset = i1 * stride;
  15197. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15198. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15199. }
  15200. return result;
  15201. }
  15202. }
  15203. /**
  15204. * A Track of quaternion keyframe values.
  15205. */
  15206. class QuaternionKeyframeTrack extends KeyframeTrack {
  15207. InterpolantFactoryMethodLinear( result ) {
  15208. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15209. }
  15210. }
  15211. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15212. // ValueBufferType is inherited
  15213. // DefaultInterpolation is inherited;
  15214. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15215. /**
  15216. * A Track that interpolates Strings
  15217. */
  15218. class StringKeyframeTrack extends KeyframeTrack {
  15219. // No interpolation parameter because only InterpolateDiscrete is valid.
  15220. constructor( name, times, values ) {
  15221. super( name, times, values );
  15222. }
  15223. }
  15224. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15225. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15226. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15227. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15228. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15229. /**
  15230. * A Track of vectored keyframe values.
  15231. */
  15232. class VectorKeyframeTrack extends KeyframeTrack {}
  15233. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15234. class AnimationClip {
  15235. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15236. this.name = name;
  15237. this.tracks = tracks;
  15238. this.duration = duration;
  15239. this.blendMode = blendMode;
  15240. this.uuid = generateUUID();
  15241. // this means it should figure out its duration by scanning the tracks
  15242. if ( this.duration < 0 ) {
  15243. this.resetDuration();
  15244. }
  15245. }
  15246. static parse( json ) {
  15247. const tracks = [],
  15248. jsonTracks = json.tracks,
  15249. frameTime = 1.0 / ( json.fps || 1.0 );
  15250. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15251. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15252. }
  15253. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15254. clip.uuid = json.uuid;
  15255. return clip;
  15256. }
  15257. static toJSON( clip ) {
  15258. const tracks = [],
  15259. clipTracks = clip.tracks;
  15260. const json = {
  15261. 'name': clip.name,
  15262. 'duration': clip.duration,
  15263. 'tracks': tracks,
  15264. 'uuid': clip.uuid,
  15265. 'blendMode': clip.blendMode
  15266. };
  15267. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15268. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15269. }
  15270. return json;
  15271. }
  15272. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15273. const numMorphTargets = morphTargetSequence.length;
  15274. const tracks = [];
  15275. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15276. let times = [];
  15277. let values = [];
  15278. times.push(
  15279. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15280. i,
  15281. ( i + 1 ) % numMorphTargets );
  15282. values.push( 0, 1, 0 );
  15283. const order = getKeyframeOrder( times );
  15284. times = sortedArray( times, 1, order );
  15285. values = sortedArray( values, 1, order );
  15286. // if there is a key at the first frame, duplicate it as the
  15287. // last frame as well for perfect loop.
  15288. if ( ! noLoop && times[ 0 ] === 0 ) {
  15289. times.push( numMorphTargets );
  15290. values.push( values[ 0 ] );
  15291. }
  15292. tracks.push(
  15293. new NumberKeyframeTrack(
  15294. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15295. times, values
  15296. ).scale( 1.0 / fps ) );
  15297. }
  15298. return new this( name, - 1, tracks );
  15299. }
  15300. static findByName( objectOrClipArray, name ) {
  15301. let clipArray = objectOrClipArray;
  15302. if ( ! Array.isArray( objectOrClipArray ) ) {
  15303. const o = objectOrClipArray;
  15304. clipArray = o.geometry && o.geometry.animations || o.animations;
  15305. }
  15306. for ( let i = 0; i < clipArray.length; i ++ ) {
  15307. if ( clipArray[ i ].name === name ) {
  15308. return clipArray[ i ];
  15309. }
  15310. }
  15311. return null;
  15312. }
  15313. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15314. const animationToMorphTargets = {};
  15315. // tested with https://regex101.com/ on trick sequences
  15316. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15317. const pattern = /^([\w-]*?)([\d]+)$/;
  15318. // sort morph target names into animation groups based
  15319. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15320. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15321. const morphTarget = morphTargets[ i ];
  15322. const parts = morphTarget.name.match( pattern );
  15323. if ( parts && parts.length > 1 ) {
  15324. const name = parts[ 1 ];
  15325. let animationMorphTargets = animationToMorphTargets[ name ];
  15326. if ( ! animationMorphTargets ) {
  15327. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15328. }
  15329. animationMorphTargets.push( morphTarget );
  15330. }
  15331. }
  15332. const clips = [];
  15333. for ( const name in animationToMorphTargets ) {
  15334. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15335. }
  15336. return clips;
  15337. }
  15338. // parse the animation.hierarchy format
  15339. static parseAnimation( animation, bones ) {
  15340. if ( ! animation ) {
  15341. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15342. return null;
  15343. }
  15344. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15345. // only return track if there are actually keys.
  15346. if ( animationKeys.length !== 0 ) {
  15347. const times = [];
  15348. const values = [];
  15349. flattenJSON( animationKeys, times, values, propertyName );
  15350. // empty keys are filtered out, so check again
  15351. if ( times.length !== 0 ) {
  15352. destTracks.push( new trackType( trackName, times, values ) );
  15353. }
  15354. }
  15355. };
  15356. const tracks = [];
  15357. const clipName = animation.name || 'default';
  15358. const fps = animation.fps || 30;
  15359. const blendMode = animation.blendMode;
  15360. // automatic length determination in AnimationClip.
  15361. let duration = animation.length || - 1;
  15362. const hierarchyTracks = animation.hierarchy || [];
  15363. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15364. const animationKeys = hierarchyTracks[ h ].keys;
  15365. // skip empty tracks
  15366. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15367. // process morph targets
  15368. if ( animationKeys[ 0 ].morphTargets ) {
  15369. // figure out all morph targets used in this track
  15370. const morphTargetNames = {};
  15371. let k;
  15372. for ( k = 0; k < animationKeys.length; k ++ ) {
  15373. if ( animationKeys[ k ].morphTargets ) {
  15374. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15375. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15376. }
  15377. }
  15378. }
  15379. // create a track for each morph target with all zero
  15380. // morphTargetInfluences except for the keys in which
  15381. // the morphTarget is named.
  15382. for ( const morphTargetName in morphTargetNames ) {
  15383. const times = [];
  15384. const values = [];
  15385. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15386. const animationKey = animationKeys[ k ];
  15387. times.push( animationKey.time );
  15388. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15389. }
  15390. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15391. }
  15392. duration = morphTargetNames.length * fps;
  15393. } else {
  15394. // ...assume skeletal animation
  15395. const boneName = '.bones[' + bones[ h ].name + ']';
  15396. addNonemptyTrack(
  15397. VectorKeyframeTrack, boneName + '.position',
  15398. animationKeys, 'pos', tracks );
  15399. addNonemptyTrack(
  15400. QuaternionKeyframeTrack, boneName + '.quaternion',
  15401. animationKeys, 'rot', tracks );
  15402. addNonemptyTrack(
  15403. VectorKeyframeTrack, boneName + '.scale',
  15404. animationKeys, 'scl', tracks );
  15405. }
  15406. }
  15407. if ( tracks.length === 0 ) {
  15408. return null;
  15409. }
  15410. const clip = new this( clipName, duration, tracks, blendMode );
  15411. return clip;
  15412. }
  15413. resetDuration() {
  15414. const tracks = this.tracks;
  15415. let duration = 0;
  15416. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15417. const track = this.tracks[ i ];
  15418. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15419. }
  15420. this.duration = duration;
  15421. return this;
  15422. }
  15423. trim() {
  15424. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15425. this.tracks[ i ].trim( 0, this.duration );
  15426. }
  15427. return this;
  15428. }
  15429. validate() {
  15430. let valid = true;
  15431. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15432. valid = valid && this.tracks[ i ].validate();
  15433. }
  15434. return valid;
  15435. }
  15436. optimize() {
  15437. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15438. this.tracks[ i ].optimize();
  15439. }
  15440. return this;
  15441. }
  15442. clone() {
  15443. const tracks = [];
  15444. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15445. tracks.push( this.tracks[ i ].clone() );
  15446. }
  15447. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15448. }
  15449. toJSON() {
  15450. return this.constructor.toJSON( this );
  15451. }
  15452. }
  15453. function getTrackTypeForValueTypeName( typeName ) {
  15454. switch ( typeName.toLowerCase() ) {
  15455. case 'scalar':
  15456. case 'double':
  15457. case 'float':
  15458. case 'number':
  15459. case 'integer':
  15460. return NumberKeyframeTrack;
  15461. case 'vector':
  15462. case 'vector2':
  15463. case 'vector3':
  15464. case 'vector4':
  15465. return VectorKeyframeTrack;
  15466. case 'color':
  15467. return ColorKeyframeTrack;
  15468. case 'quaternion':
  15469. return QuaternionKeyframeTrack;
  15470. case 'bool':
  15471. case 'boolean':
  15472. return BooleanKeyframeTrack;
  15473. case 'string':
  15474. return StringKeyframeTrack;
  15475. }
  15476. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15477. }
  15478. function parseKeyframeTrack( json ) {
  15479. if ( json.type === undefined ) {
  15480. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15481. }
  15482. const trackType = getTrackTypeForValueTypeName( json.type );
  15483. if ( json.times === undefined ) {
  15484. const times = [], values = [];
  15485. flattenJSON( json.keys, times, values, 'value' );
  15486. json.times = times;
  15487. json.values = values;
  15488. }
  15489. // derived classes can define a static parse method
  15490. if ( trackType.parse !== undefined ) {
  15491. return trackType.parse( json );
  15492. } else {
  15493. // by default, we assume a constructor compatible with the base
  15494. return new trackType( json.name, json.times, json.values, json.interpolation );
  15495. }
  15496. }
  15497. const Cache = {
  15498. enabled: false,
  15499. files: {},
  15500. add: function ( key, file ) {
  15501. if ( this.enabled === false ) return;
  15502. // console.log( 'THREE.Cache', 'Adding key:', key );
  15503. this.files[ key ] = file;
  15504. },
  15505. get: function ( key ) {
  15506. if ( this.enabled === false ) return;
  15507. // console.log( 'THREE.Cache', 'Checking key:', key );
  15508. return this.files[ key ];
  15509. },
  15510. remove: function ( key ) {
  15511. delete this.files[ key ];
  15512. },
  15513. clear: function () {
  15514. this.files = {};
  15515. }
  15516. };
  15517. class LoadingManager {
  15518. constructor( onLoad, onProgress, onError ) {
  15519. const scope = this;
  15520. let isLoading = false;
  15521. let itemsLoaded = 0;
  15522. let itemsTotal = 0;
  15523. let urlModifier = undefined;
  15524. const handlers = [];
  15525. // Refer to #5689 for the reason why we don't set .onStart
  15526. // in the constructor
  15527. this.onStart = undefined;
  15528. this.onLoad = onLoad;
  15529. this.onProgress = onProgress;
  15530. this.onError = onError;
  15531. this.itemStart = function ( url ) {
  15532. itemsTotal ++;
  15533. if ( isLoading === false ) {
  15534. if ( scope.onStart !== undefined ) {
  15535. scope.onStart( url, itemsLoaded, itemsTotal );
  15536. }
  15537. }
  15538. isLoading = true;
  15539. };
  15540. this.itemEnd = function ( url ) {
  15541. itemsLoaded ++;
  15542. if ( scope.onProgress !== undefined ) {
  15543. scope.onProgress( url, itemsLoaded, itemsTotal );
  15544. }
  15545. if ( itemsLoaded === itemsTotal ) {
  15546. isLoading = false;
  15547. if ( scope.onLoad !== undefined ) {
  15548. scope.onLoad();
  15549. }
  15550. }
  15551. };
  15552. this.itemError = function ( url ) {
  15553. if ( scope.onError !== undefined ) {
  15554. scope.onError( url );
  15555. }
  15556. };
  15557. this.resolveURL = function ( url ) {
  15558. if ( urlModifier ) {
  15559. return urlModifier( url );
  15560. }
  15561. return url;
  15562. };
  15563. this.setURLModifier = function ( transform ) {
  15564. urlModifier = transform;
  15565. return this;
  15566. };
  15567. this.addHandler = function ( regex, loader ) {
  15568. handlers.push( regex, loader );
  15569. return this;
  15570. };
  15571. this.removeHandler = function ( regex ) {
  15572. const index = handlers.indexOf( regex );
  15573. if ( index !== - 1 ) {
  15574. handlers.splice( index, 2 );
  15575. }
  15576. return this;
  15577. };
  15578. this.getHandler = function ( file ) {
  15579. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15580. const regex = handlers[ i ];
  15581. const loader = handlers[ i + 1 ];
  15582. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15583. if ( regex.test( file ) ) {
  15584. return loader;
  15585. }
  15586. }
  15587. return null;
  15588. };
  15589. }
  15590. }
  15591. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15592. class Loader {
  15593. constructor( manager ) {
  15594. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15595. this.crossOrigin = 'anonymous';
  15596. this.withCredentials = false;
  15597. this.path = '';
  15598. this.resourcePath = '';
  15599. this.requestHeader = {};
  15600. }
  15601. load( /* url, onLoad, onProgress, onError */ ) {}
  15602. loadAsync( url, onProgress ) {
  15603. const scope = this;
  15604. return new Promise( function ( resolve, reject ) {
  15605. scope.load( url, resolve, onProgress, reject );
  15606. } );
  15607. }
  15608. parse( /* data */ ) {}
  15609. setCrossOrigin( crossOrigin ) {
  15610. this.crossOrigin = crossOrigin;
  15611. return this;
  15612. }
  15613. setWithCredentials( value ) {
  15614. this.withCredentials = value;
  15615. return this;
  15616. }
  15617. setPath( path ) {
  15618. this.path = path;
  15619. return this;
  15620. }
  15621. setResourcePath( resourcePath ) {
  15622. this.resourcePath = resourcePath;
  15623. return this;
  15624. }
  15625. setRequestHeader( requestHeader ) {
  15626. this.requestHeader = requestHeader;
  15627. return this;
  15628. }
  15629. }
  15630. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15631. const loading = {};
  15632. class HttpError extends Error {
  15633. constructor( message, response ) {
  15634. super( message );
  15635. this.response = response;
  15636. }
  15637. }
  15638. class FileLoader extends Loader {
  15639. constructor( manager ) {
  15640. super( manager );
  15641. }
  15642. load( url, onLoad, onProgress, onError ) {
  15643. if ( url === undefined ) url = '';
  15644. if ( this.path !== undefined ) url = this.path + url;
  15645. url = this.manager.resolveURL( url );
  15646. const cached = Cache.get( url );
  15647. if ( cached !== undefined ) {
  15648. this.manager.itemStart( url );
  15649. setTimeout( () => {
  15650. if ( onLoad ) onLoad( cached );
  15651. this.manager.itemEnd( url );
  15652. }, 0 );
  15653. return cached;
  15654. }
  15655. // Check if request is duplicate
  15656. if ( loading[ url ] !== undefined ) {
  15657. loading[ url ].push( {
  15658. onLoad: onLoad,
  15659. onProgress: onProgress,
  15660. onError: onError
  15661. } );
  15662. return;
  15663. }
  15664. // Initialise array for duplicate requests
  15665. loading[ url ] = [];
  15666. loading[ url ].push( {
  15667. onLoad: onLoad,
  15668. onProgress: onProgress,
  15669. onError: onError,
  15670. } );
  15671. // create request
  15672. const req = new Request( url, {
  15673. headers: new Headers( this.requestHeader ),
  15674. credentials: this.withCredentials ? 'include' : 'same-origin',
  15675. // An abort controller could be added within a future PR
  15676. } );
  15677. // record states ( avoid data race )
  15678. const mimeType = this.mimeType;
  15679. const responseType = this.responseType;
  15680. // start the fetch
  15681. fetch( req )
  15682. .then( response => {
  15683. if ( response.status === 200 || response.status === 0 ) {
  15684. // Some browsers return HTTP Status 0 when using non-http protocol
  15685. // e.g. 'file://' or 'data://'. Handle as success.
  15686. if ( response.status === 0 ) {
  15687. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15688. }
  15689. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15690. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15691. return response;
  15692. }
  15693. const callbacks = loading[ url ];
  15694. const reader = response.body.getReader();
  15695. // Nginx needs X-File-Size check
  15696. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15697. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15698. const total = contentLength ? parseInt( contentLength ) : 0;
  15699. const lengthComputable = total !== 0;
  15700. let loaded = 0;
  15701. // periodically read data into the new stream tracking while download progress
  15702. const stream = new ReadableStream( {
  15703. start( controller ) {
  15704. readData();
  15705. function readData() {
  15706. reader.read().then( ( { done, value } ) => {
  15707. if ( done ) {
  15708. controller.close();
  15709. } else {
  15710. loaded += value.byteLength;
  15711. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15712. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15713. const callback = callbacks[ i ];
  15714. if ( callback.onProgress ) callback.onProgress( event );
  15715. }
  15716. controller.enqueue( value );
  15717. readData();
  15718. }
  15719. }, ( e ) => {
  15720. controller.error( e );
  15721. } );
  15722. }
  15723. }
  15724. } );
  15725. return new Response( stream );
  15726. } else {
  15727. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15728. }
  15729. } )
  15730. .then( response => {
  15731. switch ( responseType ) {
  15732. case 'arraybuffer':
  15733. return response.arrayBuffer();
  15734. case 'blob':
  15735. return response.blob();
  15736. case 'document':
  15737. return response.text()
  15738. .then( text => {
  15739. const parser = new DOMParser();
  15740. return parser.parseFromString( text, mimeType );
  15741. } );
  15742. case 'json':
  15743. return response.json();
  15744. default:
  15745. if ( mimeType === undefined ) {
  15746. return response.text();
  15747. } else {
  15748. // sniff encoding
  15749. const re = /charset="?([^;"\s]*)"?/i;
  15750. const exec = re.exec( mimeType );
  15751. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15752. const decoder = new TextDecoder( label );
  15753. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15754. }
  15755. }
  15756. } )
  15757. .then( data => {
  15758. // Add to cache only on HTTP success, so that we do not cache
  15759. // error response bodies as proper responses to requests.
  15760. Cache.add( url, data );
  15761. const callbacks = loading[ url ];
  15762. delete loading[ url ];
  15763. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15764. const callback = callbacks[ i ];
  15765. if ( callback.onLoad ) callback.onLoad( data );
  15766. }
  15767. } )
  15768. .catch( err => {
  15769. // Abort errors and other errors are handled the same
  15770. const callbacks = loading[ url ];
  15771. if ( callbacks === undefined ) {
  15772. // When onLoad was called and url was deleted in `loading`
  15773. this.manager.itemError( url );
  15774. throw err;
  15775. }
  15776. delete loading[ url ];
  15777. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15778. const callback = callbacks[ i ];
  15779. if ( callback.onError ) callback.onError( err );
  15780. }
  15781. this.manager.itemError( url );
  15782. } )
  15783. .finally( () => {
  15784. this.manager.itemEnd( url );
  15785. } );
  15786. this.manager.itemStart( url );
  15787. }
  15788. setResponseType( value ) {
  15789. this.responseType = value;
  15790. return this;
  15791. }
  15792. setMimeType( value ) {
  15793. this.mimeType = value;
  15794. return this;
  15795. }
  15796. }
  15797. class AnimationLoader extends Loader {
  15798. constructor( manager ) {
  15799. super( manager );
  15800. }
  15801. load( url, onLoad, onProgress, onError ) {
  15802. const scope = this;
  15803. const loader = new FileLoader( this.manager );
  15804. loader.setPath( this.path );
  15805. loader.setRequestHeader( this.requestHeader );
  15806. loader.setWithCredentials( this.withCredentials );
  15807. loader.load( url, function ( text ) {
  15808. try {
  15809. onLoad( scope.parse( JSON.parse( text ) ) );
  15810. } catch ( e ) {
  15811. if ( onError ) {
  15812. onError( e );
  15813. } else {
  15814. console.error( e );
  15815. }
  15816. scope.manager.itemError( url );
  15817. }
  15818. }, onProgress, onError );
  15819. }
  15820. parse( json ) {
  15821. const animations = [];
  15822. for ( let i = 0; i < json.length; i ++ ) {
  15823. const clip = AnimationClip.parse( json[ i ] );
  15824. animations.push( clip );
  15825. }
  15826. return animations;
  15827. }
  15828. }
  15829. /**
  15830. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15831. *
  15832. * Sub classes have to implement the parse() method which will be used in load().
  15833. */
  15834. class CompressedTextureLoader extends Loader {
  15835. constructor( manager ) {
  15836. super( manager );
  15837. }
  15838. load( url, onLoad, onProgress, onError ) {
  15839. const scope = this;
  15840. const images = [];
  15841. const texture = new CompressedTexture();
  15842. const loader = new FileLoader( this.manager );
  15843. loader.setPath( this.path );
  15844. loader.setResponseType( 'arraybuffer' );
  15845. loader.setRequestHeader( this.requestHeader );
  15846. loader.setWithCredentials( scope.withCredentials );
  15847. let loaded = 0;
  15848. function loadTexture( i ) {
  15849. loader.load( url[ i ], function ( buffer ) {
  15850. const texDatas = scope.parse( buffer, true );
  15851. images[ i ] = {
  15852. width: texDatas.width,
  15853. height: texDatas.height,
  15854. format: texDatas.format,
  15855. mipmaps: texDatas.mipmaps
  15856. };
  15857. loaded += 1;
  15858. if ( loaded === 6 ) {
  15859. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15860. texture.image = images;
  15861. texture.format = texDatas.format;
  15862. texture.needsUpdate = true;
  15863. if ( onLoad ) onLoad( texture );
  15864. }
  15865. }, onProgress, onError );
  15866. }
  15867. if ( Array.isArray( url ) ) {
  15868. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15869. loadTexture( i );
  15870. }
  15871. } else {
  15872. // compressed cubemap texture stored in a single DDS file
  15873. loader.load( url, function ( buffer ) {
  15874. const texDatas = scope.parse( buffer, true );
  15875. if ( texDatas.isCubemap ) {
  15876. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15877. for ( let f = 0; f < faces; f ++ ) {
  15878. images[ f ] = { mipmaps: [] };
  15879. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15880. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15881. images[ f ].format = texDatas.format;
  15882. images[ f ].width = texDatas.width;
  15883. images[ f ].height = texDatas.height;
  15884. }
  15885. }
  15886. texture.image = images;
  15887. } else {
  15888. texture.image.width = texDatas.width;
  15889. texture.image.height = texDatas.height;
  15890. texture.mipmaps = texDatas.mipmaps;
  15891. }
  15892. if ( texDatas.mipmapCount === 1 ) {
  15893. texture.minFilter = LinearFilter;
  15894. }
  15895. texture.format = texDatas.format;
  15896. texture.needsUpdate = true;
  15897. if ( onLoad ) onLoad( texture );
  15898. }, onProgress, onError );
  15899. }
  15900. return texture;
  15901. }
  15902. }
  15903. class ImageLoader extends Loader {
  15904. constructor( manager ) {
  15905. super( manager );
  15906. }
  15907. load( url, onLoad, onProgress, onError ) {
  15908. if ( this.path !== undefined ) url = this.path + url;
  15909. url = this.manager.resolveURL( url );
  15910. const scope = this;
  15911. const cached = Cache.get( url );
  15912. if ( cached !== undefined ) {
  15913. scope.manager.itemStart( url );
  15914. setTimeout( function () {
  15915. if ( onLoad ) onLoad( cached );
  15916. scope.manager.itemEnd( url );
  15917. }, 0 );
  15918. return cached;
  15919. }
  15920. const image = createElementNS( 'img' );
  15921. function onImageLoad() {
  15922. removeEventListeners();
  15923. Cache.add( url, this );
  15924. if ( onLoad ) onLoad( this );
  15925. scope.manager.itemEnd( url );
  15926. }
  15927. function onImageError( event ) {
  15928. removeEventListeners();
  15929. if ( onError ) onError( event );
  15930. scope.manager.itemError( url );
  15931. scope.manager.itemEnd( url );
  15932. }
  15933. function removeEventListeners() {
  15934. image.removeEventListener( 'load', onImageLoad, false );
  15935. image.removeEventListener( 'error', onImageError, false );
  15936. }
  15937. image.addEventListener( 'load', onImageLoad, false );
  15938. image.addEventListener( 'error', onImageError, false );
  15939. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15940. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15941. }
  15942. scope.manager.itemStart( url );
  15943. image.src = url;
  15944. return image;
  15945. }
  15946. }
  15947. class CubeTextureLoader extends Loader {
  15948. constructor( manager ) {
  15949. super( manager );
  15950. }
  15951. load( urls, onLoad, onProgress, onError ) {
  15952. const texture = new CubeTexture();
  15953. texture.colorSpace = SRGBColorSpace;
  15954. const loader = new ImageLoader( this.manager );
  15955. loader.setCrossOrigin( this.crossOrigin );
  15956. loader.setPath( this.path );
  15957. let loaded = 0;
  15958. function loadTexture( i ) {
  15959. loader.load( urls[ i ], function ( image ) {
  15960. texture.images[ i ] = image;
  15961. loaded ++;
  15962. if ( loaded === 6 ) {
  15963. texture.needsUpdate = true;
  15964. if ( onLoad ) onLoad( texture );
  15965. }
  15966. }, undefined, onError );
  15967. }
  15968. for ( let i = 0; i < urls.length; ++ i ) {
  15969. loadTexture( i );
  15970. }
  15971. return texture;
  15972. }
  15973. }
  15974. /**
  15975. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15976. *
  15977. * Sub classes have to implement the parse() method which will be used in load().
  15978. */
  15979. class DataTextureLoader extends Loader {
  15980. constructor( manager ) {
  15981. super( manager );
  15982. }
  15983. load( url, onLoad, onProgress, onError ) {
  15984. const scope = this;
  15985. const texture = new DataTexture();
  15986. const loader = new FileLoader( this.manager );
  15987. loader.setResponseType( 'arraybuffer' );
  15988. loader.setRequestHeader( this.requestHeader );
  15989. loader.setPath( this.path );
  15990. loader.setWithCredentials( scope.withCredentials );
  15991. loader.load( url, function ( buffer ) {
  15992. let texData;
  15993. try {
  15994. texData = scope.parse( buffer );
  15995. } catch ( error ) {
  15996. if ( onError !== undefined ) {
  15997. onError( error );
  15998. } else {
  15999. console.error( error );
  16000. return;
  16001. }
  16002. }
  16003. if ( texData.image !== undefined ) {
  16004. texture.image = texData.image;
  16005. } else if ( texData.data !== undefined ) {
  16006. texture.image.width = texData.width;
  16007. texture.image.height = texData.height;
  16008. texture.image.data = texData.data;
  16009. }
  16010. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16011. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16012. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16013. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16014. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16015. if ( texData.colorSpace !== undefined ) {
  16016. texture.colorSpace = texData.colorSpace;
  16017. }
  16018. if ( texData.flipY !== undefined ) {
  16019. texture.flipY = texData.flipY;
  16020. }
  16021. if ( texData.format !== undefined ) {
  16022. texture.format = texData.format;
  16023. }
  16024. if ( texData.type !== undefined ) {
  16025. texture.type = texData.type;
  16026. }
  16027. if ( texData.mipmaps !== undefined ) {
  16028. texture.mipmaps = texData.mipmaps;
  16029. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16030. }
  16031. if ( texData.mipmapCount === 1 ) {
  16032. texture.minFilter = LinearFilter;
  16033. }
  16034. if ( texData.generateMipmaps !== undefined ) {
  16035. texture.generateMipmaps = texData.generateMipmaps;
  16036. }
  16037. texture.needsUpdate = true;
  16038. if ( onLoad ) onLoad( texture, texData );
  16039. }, onProgress, onError );
  16040. return texture;
  16041. }
  16042. }
  16043. class TextureLoader extends Loader {
  16044. constructor( manager ) {
  16045. super( manager );
  16046. }
  16047. load( url, onLoad, onProgress, onError ) {
  16048. const texture = new Texture();
  16049. const loader = new ImageLoader( this.manager );
  16050. loader.setCrossOrigin( this.crossOrigin );
  16051. loader.setPath( this.path );
  16052. loader.load( url, function ( image ) {
  16053. texture.image = image;
  16054. texture.needsUpdate = true;
  16055. if ( onLoad !== undefined ) {
  16056. onLoad( texture );
  16057. }
  16058. }, onProgress, onError );
  16059. return texture;
  16060. }
  16061. }
  16062. class Light extends Object3D {
  16063. constructor( color, intensity = 1 ) {
  16064. super();
  16065. this.isLight = true;
  16066. this.type = 'Light';
  16067. this.color = new Color( color );
  16068. this.intensity = intensity;
  16069. }
  16070. dispose() {
  16071. // Empty here in base class; some subclasses override.
  16072. }
  16073. copy( source, recursive ) {
  16074. super.copy( source, recursive );
  16075. this.color.copy( source.color );
  16076. this.intensity = source.intensity;
  16077. return this;
  16078. }
  16079. toJSON( meta ) {
  16080. const data = super.toJSON( meta );
  16081. data.object.color = this.color.getHex();
  16082. data.object.intensity = this.intensity;
  16083. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16084. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16085. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16086. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16087. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16088. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16089. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16090. return data;
  16091. }
  16092. }
  16093. class HemisphereLight extends Light {
  16094. constructor( skyColor, groundColor, intensity ) {
  16095. super( skyColor, intensity );
  16096. this.isHemisphereLight = true;
  16097. this.type = 'HemisphereLight';
  16098. this.position.copy( Object3D.DEFAULT_UP );
  16099. this.updateMatrix();
  16100. this.groundColor = new Color( groundColor );
  16101. }
  16102. copy( source, recursive ) {
  16103. super.copy( source, recursive );
  16104. this.groundColor.copy( source.groundColor );
  16105. return this;
  16106. }
  16107. }
  16108. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16109. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16110. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16111. class LightShadow {
  16112. constructor( camera ) {
  16113. this.camera = camera;
  16114. this.intensity = 1;
  16115. this.bias = 0;
  16116. this.normalBias = 0;
  16117. this.radius = 1;
  16118. this.blurSamples = 8;
  16119. this.mapSize = new Vector2( 512, 512 );
  16120. this.map = null;
  16121. this.mapPass = null;
  16122. this.matrix = new Matrix4();
  16123. this.autoUpdate = true;
  16124. this.needsUpdate = false;
  16125. this._frustum = new Frustum();
  16126. this._frameExtents = new Vector2( 1, 1 );
  16127. this._viewportCount = 1;
  16128. this._viewports = [
  16129. new Vector4( 0, 0, 1, 1 )
  16130. ];
  16131. }
  16132. getViewportCount() {
  16133. return this._viewportCount;
  16134. }
  16135. getFrustum() {
  16136. return this._frustum;
  16137. }
  16138. updateMatrices( light ) {
  16139. const shadowCamera = this.camera;
  16140. const shadowMatrix = this.matrix;
  16141. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16142. shadowCamera.position.copy( _lightPositionWorld$1 );
  16143. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16144. shadowCamera.lookAt( _lookTarget$1 );
  16145. shadowCamera.updateMatrixWorld();
  16146. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16147. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16148. shadowMatrix.set(
  16149. 0.5, 0.0, 0.0, 0.5,
  16150. 0.0, 0.5, 0.0, 0.5,
  16151. 0.0, 0.0, 0.5, 0.5,
  16152. 0.0, 0.0, 0.0, 1.0
  16153. );
  16154. shadowMatrix.multiply( _projScreenMatrix$2 );
  16155. }
  16156. getViewport( viewportIndex ) {
  16157. return this._viewports[ viewportIndex ];
  16158. }
  16159. getFrameExtents() {
  16160. return this._frameExtents;
  16161. }
  16162. dispose() {
  16163. if ( this.map ) {
  16164. this.map.dispose();
  16165. }
  16166. if ( this.mapPass ) {
  16167. this.mapPass.dispose();
  16168. }
  16169. }
  16170. copy( source ) {
  16171. this.camera = source.camera.clone();
  16172. this.intensity = source.intensity;
  16173. this.bias = source.bias;
  16174. this.radius = source.radius;
  16175. this.mapSize.copy( source.mapSize );
  16176. return this;
  16177. }
  16178. clone() {
  16179. return new this.constructor().copy( this );
  16180. }
  16181. toJSON() {
  16182. const object = {};
  16183. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16184. if ( this.bias !== 0 ) object.bias = this.bias;
  16185. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16186. if ( this.radius !== 1 ) object.radius = this.radius;
  16187. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16188. object.camera = this.camera.toJSON( false ).object;
  16189. delete object.camera.matrix;
  16190. return object;
  16191. }
  16192. }
  16193. class SpotLightShadow extends LightShadow {
  16194. constructor() {
  16195. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16196. this.isSpotLightShadow = true;
  16197. this.focus = 1;
  16198. }
  16199. updateMatrices( light ) {
  16200. const camera = this.camera;
  16201. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16202. const aspect = this.mapSize.width / this.mapSize.height;
  16203. const far = light.distance || camera.far;
  16204. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16205. camera.fov = fov;
  16206. camera.aspect = aspect;
  16207. camera.far = far;
  16208. camera.updateProjectionMatrix();
  16209. }
  16210. super.updateMatrices( light );
  16211. }
  16212. copy( source ) {
  16213. super.copy( source );
  16214. this.focus = source.focus;
  16215. return this;
  16216. }
  16217. }
  16218. class SpotLight extends Light {
  16219. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16220. super( color, intensity );
  16221. this.isSpotLight = true;
  16222. this.type = 'SpotLight';
  16223. this.position.copy( Object3D.DEFAULT_UP );
  16224. this.updateMatrix();
  16225. this.target = new Object3D();
  16226. this.distance = distance;
  16227. this.angle = angle;
  16228. this.penumbra = penumbra;
  16229. this.decay = decay;
  16230. this.map = null;
  16231. this.shadow = new SpotLightShadow();
  16232. }
  16233. get power() {
  16234. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16235. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16236. return this.intensity * Math.PI;
  16237. }
  16238. set power( power ) {
  16239. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16240. this.intensity = power / Math.PI;
  16241. }
  16242. dispose() {
  16243. this.shadow.dispose();
  16244. }
  16245. copy( source, recursive ) {
  16246. super.copy( source, recursive );
  16247. this.distance = source.distance;
  16248. this.angle = source.angle;
  16249. this.penumbra = source.penumbra;
  16250. this.decay = source.decay;
  16251. this.target = source.target.clone();
  16252. this.shadow = source.shadow.clone();
  16253. return this;
  16254. }
  16255. }
  16256. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16257. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16258. const _lookTarget = /*@__PURE__*/ new Vector3();
  16259. class PointLightShadow extends LightShadow {
  16260. constructor() {
  16261. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16262. this.isPointLightShadow = true;
  16263. this._frameExtents = new Vector2( 4, 2 );
  16264. this._viewportCount = 6;
  16265. this._viewports = [
  16266. // These viewports map a cube-map onto a 2D texture with the
  16267. // following orientation:
  16268. //
  16269. // xzXZ
  16270. // y Y
  16271. //
  16272. // X - Positive x direction
  16273. // x - Negative x direction
  16274. // Y - Positive y direction
  16275. // y - Negative y direction
  16276. // Z - Positive z direction
  16277. // z - Negative z direction
  16278. // positive X
  16279. new Vector4( 2, 1, 1, 1 ),
  16280. // negative X
  16281. new Vector4( 0, 1, 1, 1 ),
  16282. // positive Z
  16283. new Vector4( 3, 1, 1, 1 ),
  16284. // negative Z
  16285. new Vector4( 1, 1, 1, 1 ),
  16286. // positive Y
  16287. new Vector4( 3, 0, 1, 1 ),
  16288. // negative Y
  16289. new Vector4( 1, 0, 1, 1 )
  16290. ];
  16291. this._cubeDirections = [
  16292. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16293. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16294. ];
  16295. this._cubeUps = [
  16296. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16297. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16298. ];
  16299. }
  16300. updateMatrices( light, viewportIndex = 0 ) {
  16301. const camera = this.camera;
  16302. const shadowMatrix = this.matrix;
  16303. const far = light.distance || camera.far;
  16304. if ( far !== camera.far ) {
  16305. camera.far = far;
  16306. camera.updateProjectionMatrix();
  16307. }
  16308. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16309. camera.position.copy( _lightPositionWorld );
  16310. _lookTarget.copy( camera.position );
  16311. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16312. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16313. camera.lookAt( _lookTarget );
  16314. camera.updateMatrixWorld();
  16315. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16316. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16317. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16318. }
  16319. }
  16320. class PointLight extends Light {
  16321. constructor( color, intensity, distance = 0, decay = 2 ) {
  16322. super( color, intensity );
  16323. this.isPointLight = true;
  16324. this.type = 'PointLight';
  16325. this.distance = distance;
  16326. this.decay = decay;
  16327. this.shadow = new PointLightShadow();
  16328. }
  16329. get power() {
  16330. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16331. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16332. return this.intensity * 4 * Math.PI;
  16333. }
  16334. set power( power ) {
  16335. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16336. this.intensity = power / ( 4 * Math.PI );
  16337. }
  16338. dispose() {
  16339. this.shadow.dispose();
  16340. }
  16341. copy( source, recursive ) {
  16342. super.copy( source, recursive );
  16343. this.distance = source.distance;
  16344. this.decay = source.decay;
  16345. this.shadow = source.shadow.clone();
  16346. return this;
  16347. }
  16348. }
  16349. class OrthographicCamera extends Camera {
  16350. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16351. super();
  16352. this.isOrthographicCamera = true;
  16353. this.type = 'OrthographicCamera';
  16354. this.zoom = 1;
  16355. this.view = null;
  16356. this.left = left;
  16357. this.right = right;
  16358. this.top = top;
  16359. this.bottom = bottom;
  16360. this.near = near;
  16361. this.far = far;
  16362. this.updateProjectionMatrix();
  16363. }
  16364. copy( source, recursive ) {
  16365. super.copy( source, recursive );
  16366. this.left = source.left;
  16367. this.right = source.right;
  16368. this.top = source.top;
  16369. this.bottom = source.bottom;
  16370. this.near = source.near;
  16371. this.far = source.far;
  16372. this.zoom = source.zoom;
  16373. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16374. return this;
  16375. }
  16376. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16377. if ( this.view === null ) {
  16378. this.view = {
  16379. enabled: true,
  16380. fullWidth: 1,
  16381. fullHeight: 1,
  16382. offsetX: 0,
  16383. offsetY: 0,
  16384. width: 1,
  16385. height: 1
  16386. };
  16387. }
  16388. this.view.enabled = true;
  16389. this.view.fullWidth = fullWidth;
  16390. this.view.fullHeight = fullHeight;
  16391. this.view.offsetX = x;
  16392. this.view.offsetY = y;
  16393. this.view.width = width;
  16394. this.view.height = height;
  16395. this.updateProjectionMatrix();
  16396. }
  16397. clearViewOffset() {
  16398. if ( this.view !== null ) {
  16399. this.view.enabled = false;
  16400. }
  16401. this.updateProjectionMatrix();
  16402. }
  16403. updateProjectionMatrix() {
  16404. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16405. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16406. const cx = ( this.right + this.left ) / 2;
  16407. const cy = ( this.top + this.bottom ) / 2;
  16408. let left = cx - dx;
  16409. let right = cx + dx;
  16410. let top = cy + dy;
  16411. let bottom = cy - dy;
  16412. if ( this.view !== null && this.view.enabled ) {
  16413. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16414. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16415. left += scaleW * this.view.offsetX;
  16416. right = left + scaleW * this.view.width;
  16417. top -= scaleH * this.view.offsetY;
  16418. bottom = top - scaleH * this.view.height;
  16419. }
  16420. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16421. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16422. }
  16423. toJSON( meta ) {
  16424. const data = super.toJSON( meta );
  16425. data.object.zoom = this.zoom;
  16426. data.object.left = this.left;
  16427. data.object.right = this.right;
  16428. data.object.top = this.top;
  16429. data.object.bottom = this.bottom;
  16430. data.object.near = this.near;
  16431. data.object.far = this.far;
  16432. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16433. return data;
  16434. }
  16435. }
  16436. class DirectionalLightShadow extends LightShadow {
  16437. constructor() {
  16438. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16439. this.isDirectionalLightShadow = true;
  16440. }
  16441. }
  16442. class DirectionalLight extends Light {
  16443. constructor( color, intensity ) {
  16444. super( color, intensity );
  16445. this.isDirectionalLight = true;
  16446. this.type = 'DirectionalLight';
  16447. this.position.copy( Object3D.DEFAULT_UP );
  16448. this.updateMatrix();
  16449. this.target = new Object3D();
  16450. this.shadow = new DirectionalLightShadow();
  16451. }
  16452. dispose() {
  16453. this.shadow.dispose();
  16454. }
  16455. copy( source ) {
  16456. super.copy( source );
  16457. this.target = source.target.clone();
  16458. this.shadow = source.shadow.clone();
  16459. return this;
  16460. }
  16461. }
  16462. class AmbientLight extends Light {
  16463. constructor( color, intensity ) {
  16464. super( color, intensity );
  16465. this.isAmbientLight = true;
  16466. this.type = 'AmbientLight';
  16467. }
  16468. }
  16469. class RectAreaLight extends Light {
  16470. constructor( color, intensity, width = 10, height = 10 ) {
  16471. super( color, intensity );
  16472. this.isRectAreaLight = true;
  16473. this.type = 'RectAreaLight';
  16474. this.width = width;
  16475. this.height = height;
  16476. }
  16477. get power() {
  16478. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16479. return this.intensity * this.width * this.height * Math.PI;
  16480. }
  16481. set power( power ) {
  16482. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16483. this.intensity = power / ( this.width * this.height * Math.PI );
  16484. }
  16485. copy( source ) {
  16486. super.copy( source );
  16487. this.width = source.width;
  16488. this.height = source.height;
  16489. return this;
  16490. }
  16491. toJSON( meta ) {
  16492. const data = super.toJSON( meta );
  16493. data.object.width = this.width;
  16494. data.object.height = this.height;
  16495. return data;
  16496. }
  16497. }
  16498. /**
  16499. * Primary reference:
  16500. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16501. *
  16502. * Secondary reference:
  16503. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16504. */
  16505. // 3-band SH defined by 9 coefficients
  16506. class SphericalHarmonics3 {
  16507. constructor() {
  16508. this.isSphericalHarmonics3 = true;
  16509. this.coefficients = [];
  16510. for ( let i = 0; i < 9; i ++ ) {
  16511. this.coefficients.push( new Vector3() );
  16512. }
  16513. }
  16514. set( coefficients ) {
  16515. for ( let i = 0; i < 9; i ++ ) {
  16516. this.coefficients[ i ].copy( coefficients[ i ] );
  16517. }
  16518. return this;
  16519. }
  16520. zero() {
  16521. for ( let i = 0; i < 9; i ++ ) {
  16522. this.coefficients[ i ].set( 0, 0, 0 );
  16523. }
  16524. return this;
  16525. }
  16526. // get the radiance in the direction of the normal
  16527. // target is a Vector3
  16528. getAt( normal, target ) {
  16529. // normal is assumed to be unit length
  16530. const x = normal.x, y = normal.y, z = normal.z;
  16531. const coeff = this.coefficients;
  16532. // band 0
  16533. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16534. // band 1
  16535. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16536. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16537. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16538. // band 2
  16539. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16540. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16541. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16542. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16543. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16544. return target;
  16545. }
  16546. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16547. // target is a Vector3
  16548. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16549. getIrradianceAt( normal, target ) {
  16550. // normal is assumed to be unit length
  16551. const x = normal.x, y = normal.y, z = normal.z;
  16552. const coeff = this.coefficients;
  16553. // band 0
  16554. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16555. // band 1
  16556. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16557. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16558. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16559. // band 2
  16560. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16561. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16562. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16563. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16564. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16565. return target;
  16566. }
  16567. add( sh ) {
  16568. for ( let i = 0; i < 9; i ++ ) {
  16569. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16570. }
  16571. return this;
  16572. }
  16573. addScaledSH( sh, s ) {
  16574. for ( let i = 0; i < 9; i ++ ) {
  16575. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16576. }
  16577. return this;
  16578. }
  16579. scale( s ) {
  16580. for ( let i = 0; i < 9; i ++ ) {
  16581. this.coefficients[ i ].multiplyScalar( s );
  16582. }
  16583. return this;
  16584. }
  16585. lerp( sh, alpha ) {
  16586. for ( let i = 0; i < 9; i ++ ) {
  16587. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16588. }
  16589. return this;
  16590. }
  16591. equals( sh ) {
  16592. for ( let i = 0; i < 9; i ++ ) {
  16593. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16594. return false;
  16595. }
  16596. }
  16597. return true;
  16598. }
  16599. copy( sh ) {
  16600. return this.set( sh.coefficients );
  16601. }
  16602. clone() {
  16603. return new this.constructor().copy( this );
  16604. }
  16605. fromArray( array, offset = 0 ) {
  16606. const coefficients = this.coefficients;
  16607. for ( let i = 0; i < 9; i ++ ) {
  16608. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16609. }
  16610. return this;
  16611. }
  16612. toArray( array = [], offset = 0 ) {
  16613. const coefficients = this.coefficients;
  16614. for ( let i = 0; i < 9; i ++ ) {
  16615. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16616. }
  16617. return array;
  16618. }
  16619. // evaluate the basis functions
  16620. // shBasis is an Array[ 9 ]
  16621. static getBasisAt( normal, shBasis ) {
  16622. // normal is assumed to be unit length
  16623. const x = normal.x, y = normal.y, z = normal.z;
  16624. // band 0
  16625. shBasis[ 0 ] = 0.282095;
  16626. // band 1
  16627. shBasis[ 1 ] = 0.488603 * y;
  16628. shBasis[ 2 ] = 0.488603 * z;
  16629. shBasis[ 3 ] = 0.488603 * x;
  16630. // band 2
  16631. shBasis[ 4 ] = 1.092548 * x * y;
  16632. shBasis[ 5 ] = 1.092548 * y * z;
  16633. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16634. shBasis[ 7 ] = 1.092548 * x * z;
  16635. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16636. }
  16637. }
  16638. class LightProbe extends Light {
  16639. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16640. super( undefined, intensity );
  16641. this.isLightProbe = true;
  16642. this.sh = sh;
  16643. }
  16644. copy( source ) {
  16645. super.copy( source );
  16646. this.sh.copy( source.sh );
  16647. return this;
  16648. }
  16649. fromJSON( json ) {
  16650. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16651. this.sh.fromArray( json.sh );
  16652. return this;
  16653. }
  16654. toJSON( meta ) {
  16655. const data = super.toJSON( meta );
  16656. data.object.sh = this.sh.toArray();
  16657. return data;
  16658. }
  16659. }
  16660. class MaterialLoader extends Loader {
  16661. constructor( manager ) {
  16662. super( manager );
  16663. this.textures = {};
  16664. }
  16665. load( url, onLoad, onProgress, onError ) {
  16666. const scope = this;
  16667. const loader = new FileLoader( scope.manager );
  16668. loader.setPath( scope.path );
  16669. loader.setRequestHeader( scope.requestHeader );
  16670. loader.setWithCredentials( scope.withCredentials );
  16671. loader.load( url, function ( text ) {
  16672. try {
  16673. onLoad( scope.parse( JSON.parse( text ) ) );
  16674. } catch ( e ) {
  16675. if ( onError ) {
  16676. onError( e );
  16677. } else {
  16678. console.error( e );
  16679. }
  16680. scope.manager.itemError( url );
  16681. }
  16682. }, onProgress, onError );
  16683. }
  16684. parse( json ) {
  16685. const textures = this.textures;
  16686. function getTexture( name ) {
  16687. if ( textures[ name ] === undefined ) {
  16688. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16689. }
  16690. return textures[ name ];
  16691. }
  16692. const material = this.createMaterialFromType( json.type );
  16693. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16694. if ( json.name !== undefined ) material.name = json.name;
  16695. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16696. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16697. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16698. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16699. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16700. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16701. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16702. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16703. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16704. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16705. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16706. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16707. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16708. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16709. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16710. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16711. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16712. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16713. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16714. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16715. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16716. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16717. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16718. if ( json.fog !== undefined ) material.fog = json.fog;
  16719. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16720. if ( json.blending !== undefined ) material.blending = json.blending;
  16721. if ( json.combine !== undefined ) material.combine = json.combine;
  16722. if ( json.side !== undefined ) material.side = json.side;
  16723. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16724. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16725. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16726. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16727. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16728. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16729. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16730. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16731. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16732. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16733. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16734. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16735. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16736. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16737. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16738. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16739. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16740. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16741. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16742. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16743. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16744. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16745. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16746. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16747. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16748. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16749. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16750. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16751. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16752. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16753. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16754. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16755. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16756. if ( json.scale !== undefined ) material.scale = json.scale;
  16757. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16758. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16759. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16760. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16761. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16762. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16763. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16764. if ( json.visible !== undefined ) material.visible = json.visible;
  16765. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16766. if ( json.userData !== undefined ) material.userData = json.userData;
  16767. if ( json.vertexColors !== undefined ) {
  16768. if ( typeof json.vertexColors === 'number' ) {
  16769. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16770. } else {
  16771. material.vertexColors = json.vertexColors;
  16772. }
  16773. }
  16774. // Shader Material
  16775. if ( json.uniforms !== undefined ) {
  16776. for ( const name in json.uniforms ) {
  16777. const uniform = json.uniforms[ name ];
  16778. material.uniforms[ name ] = {};
  16779. switch ( uniform.type ) {
  16780. case 't':
  16781. material.uniforms[ name ].value = getTexture( uniform.value );
  16782. break;
  16783. case 'c':
  16784. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16785. break;
  16786. case 'v2':
  16787. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16788. break;
  16789. case 'v3':
  16790. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16791. break;
  16792. case 'v4':
  16793. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16794. break;
  16795. case 'm3':
  16796. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16797. break;
  16798. case 'm4':
  16799. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16800. break;
  16801. default:
  16802. material.uniforms[ name ].value = uniform.value;
  16803. }
  16804. }
  16805. }
  16806. if ( json.defines !== undefined ) material.defines = json.defines;
  16807. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16808. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16809. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16810. if ( json.extensions !== undefined ) {
  16811. for ( const key in json.extensions ) {
  16812. material.extensions[ key ] = json.extensions[ key ];
  16813. }
  16814. }
  16815. if ( json.lights !== undefined ) material.lights = json.lights;
  16816. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16817. // for PointsMaterial
  16818. if ( json.size !== undefined ) material.size = json.size;
  16819. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16820. // maps
  16821. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16822. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16823. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16824. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16825. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16826. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16827. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16828. if ( json.normalScale !== undefined ) {
  16829. let normalScale = json.normalScale;
  16830. if ( Array.isArray( normalScale ) === false ) {
  16831. // Blender exporter used to export a scalar. See #7459
  16832. normalScale = [ normalScale, normalScale ];
  16833. }
  16834. material.normalScale = new Vector2().fromArray( normalScale );
  16835. }
  16836. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16837. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16838. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16839. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16840. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16841. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16842. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16843. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16844. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16845. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16846. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16847. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16848. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16849. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16850. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16851. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16852. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16853. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16854. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16855. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16856. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16857. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16858. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16859. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16860. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16861. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16862. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16863. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16864. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16865. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16866. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16867. return material;
  16868. }
  16869. setTextures( value ) {
  16870. this.textures = value;
  16871. return this;
  16872. }
  16873. createMaterialFromType( type ) {
  16874. return MaterialLoader.createMaterialFromType( type );
  16875. }
  16876. static createMaterialFromType( type ) {
  16877. const materialLib = {
  16878. ShadowMaterial,
  16879. SpriteMaterial,
  16880. RawShaderMaterial,
  16881. ShaderMaterial,
  16882. PointsMaterial,
  16883. MeshPhysicalMaterial,
  16884. MeshStandardMaterial,
  16885. MeshPhongMaterial,
  16886. MeshToonMaterial,
  16887. MeshNormalMaterial,
  16888. MeshLambertMaterial,
  16889. MeshDepthMaterial,
  16890. MeshDistanceMaterial,
  16891. MeshBasicMaterial,
  16892. MeshMatcapMaterial,
  16893. LineDashedMaterial,
  16894. LineBasicMaterial,
  16895. Material
  16896. };
  16897. return new materialLib[ type ]();
  16898. }
  16899. }
  16900. class LoaderUtils {
  16901. static decodeText( array ) { // @deprecated, r165
  16902. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16903. if ( typeof TextDecoder !== 'undefined' ) {
  16904. return new TextDecoder().decode( array );
  16905. }
  16906. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16907. // throws a "maximum call stack size exceeded" error for large arrays.
  16908. let s = '';
  16909. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16910. // Implicitly assumes little-endian.
  16911. s += String.fromCharCode( array[ i ] );
  16912. }
  16913. try {
  16914. // merges multi-byte utf-8 characters.
  16915. return decodeURIComponent( escape( s ) );
  16916. } catch ( e ) { // see #16358
  16917. return s;
  16918. }
  16919. }
  16920. static extractUrlBase( url ) {
  16921. const index = url.lastIndexOf( '/' );
  16922. if ( index === - 1 ) return './';
  16923. return url.slice( 0, index + 1 );
  16924. }
  16925. static resolveURL( url, path ) {
  16926. // Invalid URL
  16927. if ( typeof url !== 'string' || url === '' ) return '';
  16928. // Host Relative URL
  16929. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16930. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16931. }
  16932. // Absolute URL http://,https://,//
  16933. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16934. // Data URI
  16935. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16936. // Blob URL
  16937. if ( /^blob:.*$/i.test( url ) ) return url;
  16938. // Relative URL
  16939. return path + url;
  16940. }
  16941. }
  16942. class InstancedBufferGeometry extends BufferGeometry {
  16943. constructor() {
  16944. super();
  16945. this.isInstancedBufferGeometry = true;
  16946. this.type = 'InstancedBufferGeometry';
  16947. this.instanceCount = Infinity;
  16948. }
  16949. copy( source ) {
  16950. super.copy( source );
  16951. this.instanceCount = source.instanceCount;
  16952. return this;
  16953. }
  16954. toJSON() {
  16955. const data = super.toJSON();
  16956. data.instanceCount = this.instanceCount;
  16957. data.isInstancedBufferGeometry = true;
  16958. return data;
  16959. }
  16960. }
  16961. class BufferGeometryLoader extends Loader {
  16962. constructor( manager ) {
  16963. super( manager );
  16964. }
  16965. load( url, onLoad, onProgress, onError ) {
  16966. const scope = this;
  16967. const loader = new FileLoader( scope.manager );
  16968. loader.setPath( scope.path );
  16969. loader.setRequestHeader( scope.requestHeader );
  16970. loader.setWithCredentials( scope.withCredentials );
  16971. loader.load( url, function ( text ) {
  16972. try {
  16973. onLoad( scope.parse( JSON.parse( text ) ) );
  16974. } catch ( e ) {
  16975. if ( onError ) {
  16976. onError( e );
  16977. } else {
  16978. console.error( e );
  16979. }
  16980. scope.manager.itemError( url );
  16981. }
  16982. }, onProgress, onError );
  16983. }
  16984. parse( json ) {
  16985. const interleavedBufferMap = {};
  16986. const arrayBufferMap = {};
  16987. function getInterleavedBuffer( json, uuid ) {
  16988. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16989. const interleavedBuffers = json.interleavedBuffers;
  16990. const interleavedBuffer = interleavedBuffers[ uuid ];
  16991. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16992. const array = getTypedArray( interleavedBuffer.type, buffer );
  16993. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16994. ib.uuid = interleavedBuffer.uuid;
  16995. interleavedBufferMap[ uuid ] = ib;
  16996. return ib;
  16997. }
  16998. function getArrayBuffer( json, uuid ) {
  16999. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  17000. const arrayBuffers = json.arrayBuffers;
  17001. const arrayBuffer = arrayBuffers[ uuid ];
  17002. const ab = new Uint32Array( arrayBuffer ).buffer;
  17003. arrayBufferMap[ uuid ] = ab;
  17004. return ab;
  17005. }
  17006. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  17007. const index = json.data.index;
  17008. if ( index !== undefined ) {
  17009. const typedArray = getTypedArray( index.type, index.array );
  17010. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17011. }
  17012. const attributes = json.data.attributes;
  17013. for ( const key in attributes ) {
  17014. const attribute = attributes[ key ];
  17015. let bufferAttribute;
  17016. if ( attribute.isInterleavedBufferAttribute ) {
  17017. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17018. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17019. } else {
  17020. const typedArray = getTypedArray( attribute.type, attribute.array );
  17021. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17022. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17023. }
  17024. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17025. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17026. geometry.setAttribute( key, bufferAttribute );
  17027. }
  17028. const morphAttributes = json.data.morphAttributes;
  17029. if ( morphAttributes ) {
  17030. for ( const key in morphAttributes ) {
  17031. const attributeArray = morphAttributes[ key ];
  17032. const array = [];
  17033. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17034. const attribute = attributeArray[ i ];
  17035. let bufferAttribute;
  17036. if ( attribute.isInterleavedBufferAttribute ) {
  17037. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17038. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17039. } else {
  17040. const typedArray = getTypedArray( attribute.type, attribute.array );
  17041. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17042. }
  17043. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17044. array.push( bufferAttribute );
  17045. }
  17046. geometry.morphAttributes[ key ] = array;
  17047. }
  17048. }
  17049. const morphTargetsRelative = json.data.morphTargetsRelative;
  17050. if ( morphTargetsRelative ) {
  17051. geometry.morphTargetsRelative = true;
  17052. }
  17053. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17054. if ( groups !== undefined ) {
  17055. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17056. const group = groups[ i ];
  17057. geometry.addGroup( group.start, group.count, group.materialIndex );
  17058. }
  17059. }
  17060. const boundingSphere = json.data.boundingSphere;
  17061. if ( boundingSphere !== undefined ) {
  17062. const center = new Vector3();
  17063. if ( boundingSphere.center !== undefined ) {
  17064. center.fromArray( boundingSphere.center );
  17065. }
  17066. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17067. }
  17068. if ( json.name ) geometry.name = json.name;
  17069. if ( json.userData ) geometry.userData = json.userData;
  17070. return geometry;
  17071. }
  17072. }
  17073. class ObjectLoader extends Loader {
  17074. constructor( manager ) {
  17075. super( manager );
  17076. }
  17077. load( url, onLoad, onProgress, onError ) {
  17078. const scope = this;
  17079. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17080. this.resourcePath = this.resourcePath || path;
  17081. const loader = new FileLoader( this.manager );
  17082. loader.setPath( this.path );
  17083. loader.setRequestHeader( this.requestHeader );
  17084. loader.setWithCredentials( this.withCredentials );
  17085. loader.load( url, function ( text ) {
  17086. let json = null;
  17087. try {
  17088. json = JSON.parse( text );
  17089. } catch ( error ) {
  17090. if ( onError !== undefined ) onError( error );
  17091. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17092. return;
  17093. }
  17094. const metadata = json.metadata;
  17095. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17096. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17097. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17098. return;
  17099. }
  17100. scope.parse( json, onLoad );
  17101. }, onProgress, onError );
  17102. }
  17103. async loadAsync( url, onProgress ) {
  17104. const scope = this;
  17105. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17106. this.resourcePath = this.resourcePath || path;
  17107. const loader = new FileLoader( this.manager );
  17108. loader.setPath( this.path );
  17109. loader.setRequestHeader( this.requestHeader );
  17110. loader.setWithCredentials( this.withCredentials );
  17111. const text = await loader.loadAsync( url, onProgress );
  17112. const json = JSON.parse( text );
  17113. const metadata = json.metadata;
  17114. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17115. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17116. }
  17117. return await scope.parseAsync( json );
  17118. }
  17119. parse( json, onLoad ) {
  17120. const animations = this.parseAnimations( json.animations );
  17121. const shapes = this.parseShapes( json.shapes );
  17122. const geometries = this.parseGeometries( json.geometries, shapes );
  17123. const images = this.parseImages( json.images, function () {
  17124. if ( onLoad !== undefined ) onLoad( object );
  17125. } );
  17126. const textures = this.parseTextures( json.textures, images );
  17127. const materials = this.parseMaterials( json.materials, textures );
  17128. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17129. const skeletons = this.parseSkeletons( json.skeletons, object );
  17130. this.bindSkeletons( object, skeletons );
  17131. this.bindLightTargets( object );
  17132. //
  17133. if ( onLoad !== undefined ) {
  17134. let hasImages = false;
  17135. for ( const uuid in images ) {
  17136. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17137. hasImages = true;
  17138. break;
  17139. }
  17140. }
  17141. if ( hasImages === false ) onLoad( object );
  17142. }
  17143. return object;
  17144. }
  17145. async parseAsync( json ) {
  17146. const animations = this.parseAnimations( json.animations );
  17147. const shapes = this.parseShapes( json.shapes );
  17148. const geometries = this.parseGeometries( json.geometries, shapes );
  17149. const images = await this.parseImagesAsync( json.images );
  17150. const textures = this.parseTextures( json.textures, images );
  17151. const materials = this.parseMaterials( json.materials, textures );
  17152. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17153. const skeletons = this.parseSkeletons( json.skeletons, object );
  17154. this.bindSkeletons( object, skeletons );
  17155. this.bindLightTargets( object );
  17156. return object;
  17157. }
  17158. parseShapes( json ) {
  17159. const shapes = {};
  17160. if ( json !== undefined ) {
  17161. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17162. const shape = new Shape().fromJSON( json[ i ] );
  17163. shapes[ shape.uuid ] = shape;
  17164. }
  17165. }
  17166. return shapes;
  17167. }
  17168. parseSkeletons( json, object ) {
  17169. const skeletons = {};
  17170. const bones = {};
  17171. // generate bone lookup table
  17172. object.traverse( function ( child ) {
  17173. if ( child.isBone ) bones[ child.uuid ] = child;
  17174. } );
  17175. // create skeletons
  17176. if ( json !== undefined ) {
  17177. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17178. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17179. skeletons[ skeleton.uuid ] = skeleton;
  17180. }
  17181. }
  17182. return skeletons;
  17183. }
  17184. parseGeometries( json, shapes ) {
  17185. const geometries = {};
  17186. if ( json !== undefined ) {
  17187. const bufferGeometryLoader = new BufferGeometryLoader();
  17188. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17189. let geometry;
  17190. const data = json[ i ];
  17191. switch ( data.type ) {
  17192. case 'BufferGeometry':
  17193. case 'InstancedBufferGeometry':
  17194. geometry = bufferGeometryLoader.parse( data );
  17195. break;
  17196. default:
  17197. if ( data.type in Geometries$1 ) {
  17198. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17199. } else {
  17200. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17201. }
  17202. }
  17203. geometry.uuid = data.uuid;
  17204. if ( data.name !== undefined ) geometry.name = data.name;
  17205. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17206. geometries[ data.uuid ] = geometry;
  17207. }
  17208. }
  17209. return geometries;
  17210. }
  17211. parseMaterials( json, textures ) {
  17212. const cache = {}; // MultiMaterial
  17213. const materials = {};
  17214. if ( json !== undefined ) {
  17215. const loader = new MaterialLoader();
  17216. loader.setTextures( textures );
  17217. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17218. const data = json[ i ];
  17219. if ( cache[ data.uuid ] === undefined ) {
  17220. cache[ data.uuid ] = loader.parse( data );
  17221. }
  17222. materials[ data.uuid ] = cache[ data.uuid ];
  17223. }
  17224. }
  17225. return materials;
  17226. }
  17227. parseAnimations( json ) {
  17228. const animations = {};
  17229. if ( json !== undefined ) {
  17230. for ( let i = 0; i < json.length; i ++ ) {
  17231. const data = json[ i ];
  17232. const clip = AnimationClip.parse( data );
  17233. animations[ clip.uuid ] = clip;
  17234. }
  17235. }
  17236. return animations;
  17237. }
  17238. parseImages( json, onLoad ) {
  17239. const scope = this;
  17240. const images = {};
  17241. let loader;
  17242. function loadImage( url ) {
  17243. scope.manager.itemStart( url );
  17244. return loader.load( url, function () {
  17245. scope.manager.itemEnd( url );
  17246. }, undefined, function () {
  17247. scope.manager.itemError( url );
  17248. scope.manager.itemEnd( url );
  17249. } );
  17250. }
  17251. function deserializeImage( image ) {
  17252. if ( typeof image === 'string' ) {
  17253. const url = image;
  17254. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17255. return loadImage( path );
  17256. } else {
  17257. if ( image.data ) {
  17258. return {
  17259. data: getTypedArray( image.type, image.data ),
  17260. width: image.width,
  17261. height: image.height
  17262. };
  17263. } else {
  17264. return null;
  17265. }
  17266. }
  17267. }
  17268. if ( json !== undefined && json.length > 0 ) {
  17269. const manager = new LoadingManager( onLoad );
  17270. loader = new ImageLoader( manager );
  17271. loader.setCrossOrigin( this.crossOrigin );
  17272. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17273. const image = json[ i ];
  17274. const url = image.url;
  17275. if ( Array.isArray( url ) ) {
  17276. // load array of images e.g CubeTexture
  17277. const imageArray = [];
  17278. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17279. const currentUrl = url[ j ];
  17280. const deserializedImage = deserializeImage( currentUrl );
  17281. if ( deserializedImage !== null ) {
  17282. if ( deserializedImage instanceof HTMLImageElement ) {
  17283. imageArray.push( deserializedImage );
  17284. } else {
  17285. // special case: handle array of data textures for cube textures
  17286. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17287. }
  17288. }
  17289. }
  17290. images[ image.uuid ] = new Source( imageArray );
  17291. } else {
  17292. // load single image
  17293. const deserializedImage = deserializeImage( image.url );
  17294. images[ image.uuid ] = new Source( deserializedImage );
  17295. }
  17296. }
  17297. }
  17298. return images;
  17299. }
  17300. async parseImagesAsync( json ) {
  17301. const scope = this;
  17302. const images = {};
  17303. let loader;
  17304. async function deserializeImage( image ) {
  17305. if ( typeof image === 'string' ) {
  17306. const url = image;
  17307. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17308. return await loader.loadAsync( path );
  17309. } else {
  17310. if ( image.data ) {
  17311. return {
  17312. data: getTypedArray( image.type, image.data ),
  17313. width: image.width,
  17314. height: image.height
  17315. };
  17316. } else {
  17317. return null;
  17318. }
  17319. }
  17320. }
  17321. if ( json !== undefined && json.length > 0 ) {
  17322. loader = new ImageLoader( this.manager );
  17323. loader.setCrossOrigin( this.crossOrigin );
  17324. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17325. const image = json[ i ];
  17326. const url = image.url;
  17327. if ( Array.isArray( url ) ) {
  17328. // load array of images e.g CubeTexture
  17329. const imageArray = [];
  17330. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17331. const currentUrl = url[ j ];
  17332. const deserializedImage = await deserializeImage( currentUrl );
  17333. if ( deserializedImage !== null ) {
  17334. if ( deserializedImage instanceof HTMLImageElement ) {
  17335. imageArray.push( deserializedImage );
  17336. } else {
  17337. // special case: handle array of data textures for cube textures
  17338. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17339. }
  17340. }
  17341. }
  17342. images[ image.uuid ] = new Source( imageArray );
  17343. } else {
  17344. // load single image
  17345. const deserializedImage = await deserializeImage( image.url );
  17346. images[ image.uuid ] = new Source( deserializedImage );
  17347. }
  17348. }
  17349. }
  17350. return images;
  17351. }
  17352. parseTextures( json, images ) {
  17353. function parseConstant( value, type ) {
  17354. if ( typeof value === 'number' ) return value;
  17355. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17356. return type[ value ];
  17357. }
  17358. const textures = {};
  17359. if ( json !== undefined ) {
  17360. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17361. const data = json[ i ];
  17362. if ( data.image === undefined ) {
  17363. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17364. }
  17365. if ( images[ data.image ] === undefined ) {
  17366. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17367. }
  17368. const source = images[ data.image ];
  17369. const image = source.data;
  17370. let texture;
  17371. if ( Array.isArray( image ) ) {
  17372. texture = new CubeTexture();
  17373. if ( image.length === 6 ) texture.needsUpdate = true;
  17374. } else {
  17375. if ( image && image.data ) {
  17376. texture = new DataTexture();
  17377. } else {
  17378. texture = new Texture();
  17379. }
  17380. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17381. }
  17382. texture.source = source;
  17383. texture.uuid = data.uuid;
  17384. if ( data.name !== undefined ) texture.name = data.name;
  17385. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17386. if ( data.channel !== undefined ) texture.channel = data.channel;
  17387. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17388. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17389. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17390. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17391. if ( data.wrap !== undefined ) {
  17392. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17393. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17394. }
  17395. if ( data.format !== undefined ) texture.format = data.format;
  17396. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17397. if ( data.type !== undefined ) texture.type = data.type;
  17398. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17399. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17400. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17401. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17402. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17403. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17404. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17405. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17406. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17407. if ( data.userData !== undefined ) texture.userData = data.userData;
  17408. textures[ data.uuid ] = texture;
  17409. }
  17410. }
  17411. return textures;
  17412. }
  17413. parseObject( data, geometries, materials, textures, animations ) {
  17414. let object;
  17415. function getGeometry( name ) {
  17416. if ( geometries[ name ] === undefined ) {
  17417. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17418. }
  17419. return geometries[ name ];
  17420. }
  17421. function getMaterial( name ) {
  17422. if ( name === undefined ) return undefined;
  17423. if ( Array.isArray( name ) ) {
  17424. const array = [];
  17425. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17426. const uuid = name[ i ];
  17427. if ( materials[ uuid ] === undefined ) {
  17428. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17429. }
  17430. array.push( materials[ uuid ] );
  17431. }
  17432. return array;
  17433. }
  17434. if ( materials[ name ] === undefined ) {
  17435. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17436. }
  17437. return materials[ name ];
  17438. }
  17439. function getTexture( uuid ) {
  17440. if ( textures[ uuid ] === undefined ) {
  17441. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17442. }
  17443. return textures[ uuid ];
  17444. }
  17445. let geometry, material;
  17446. switch ( data.type ) {
  17447. case 'Scene':
  17448. object = new Scene();
  17449. if ( data.background !== undefined ) {
  17450. if ( Number.isInteger( data.background ) ) {
  17451. object.background = new Color( data.background );
  17452. } else {
  17453. object.background = getTexture( data.background );
  17454. }
  17455. }
  17456. if ( data.environment !== undefined ) {
  17457. object.environment = getTexture( data.environment );
  17458. }
  17459. if ( data.fog !== undefined ) {
  17460. if ( data.fog.type === 'Fog' ) {
  17461. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17462. } else if ( data.fog.type === 'FogExp2' ) {
  17463. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17464. }
  17465. if ( data.fog.name !== '' ) {
  17466. object.fog.name = data.fog.name;
  17467. }
  17468. }
  17469. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17470. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17471. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17472. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17473. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17474. break;
  17475. case 'PerspectiveCamera':
  17476. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17477. if ( data.focus !== undefined ) object.focus = data.focus;
  17478. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17479. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17480. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17481. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17482. break;
  17483. case 'OrthographicCamera':
  17484. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17485. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17486. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17487. break;
  17488. case 'AmbientLight':
  17489. object = new AmbientLight( data.color, data.intensity );
  17490. break;
  17491. case 'DirectionalLight':
  17492. object = new DirectionalLight( data.color, data.intensity );
  17493. object.target = data.target || '';
  17494. break;
  17495. case 'PointLight':
  17496. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17497. break;
  17498. case 'RectAreaLight':
  17499. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17500. break;
  17501. case 'SpotLight':
  17502. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17503. object.target = data.target || '';
  17504. break;
  17505. case 'HemisphereLight':
  17506. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17507. break;
  17508. case 'LightProbe':
  17509. object = new LightProbe().fromJSON( data );
  17510. break;
  17511. case 'SkinnedMesh':
  17512. geometry = getGeometry( data.geometry );
  17513. material = getMaterial( data.material );
  17514. object = new SkinnedMesh( geometry, material );
  17515. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17516. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17517. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17518. break;
  17519. case 'Mesh':
  17520. geometry = getGeometry( data.geometry );
  17521. material = getMaterial( data.material );
  17522. object = new Mesh( geometry, material );
  17523. break;
  17524. case 'InstancedMesh':
  17525. geometry = getGeometry( data.geometry );
  17526. material = getMaterial( data.material );
  17527. const count = data.count;
  17528. const instanceMatrix = data.instanceMatrix;
  17529. const instanceColor = data.instanceColor;
  17530. object = new InstancedMesh( geometry, material, count );
  17531. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17532. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17533. break;
  17534. case 'BatchedMesh':
  17535. geometry = getGeometry( data.geometry );
  17536. material = getMaterial( data.material );
  17537. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17538. object.geometry = geometry;
  17539. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17540. object.sortObjects = data.sortObjects;
  17541. object._drawRanges = data.drawRanges;
  17542. object._reservedRanges = data.reservedRanges;
  17543. object._visibility = data.visibility;
  17544. object._active = data.active;
  17545. object._bounds = data.bounds.map( bound => {
  17546. const box = new Box3();
  17547. box.min.fromArray( bound.boxMin );
  17548. box.max.fromArray( bound.boxMax );
  17549. const sphere = new Sphere();
  17550. sphere.radius = bound.sphereRadius;
  17551. sphere.center.fromArray( bound.sphereCenter );
  17552. return {
  17553. boxInitialized: bound.boxInitialized,
  17554. box: box,
  17555. sphereInitialized: bound.sphereInitialized,
  17556. sphere: sphere
  17557. };
  17558. } );
  17559. object._maxInstanceCount = data.maxInstanceCount;
  17560. object._maxVertexCount = data.maxVertexCount;
  17561. object._maxIndexCount = data.maxIndexCount;
  17562. object._geometryInitialized = data.geometryInitialized;
  17563. object._geometryCount = data.geometryCount;
  17564. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17565. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17566. break;
  17567. case 'LOD':
  17568. object = new LOD();
  17569. break;
  17570. case 'Line':
  17571. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17572. break;
  17573. case 'LineLoop':
  17574. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17575. break;
  17576. case 'LineSegments':
  17577. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17578. break;
  17579. case 'PointCloud':
  17580. case 'Points':
  17581. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17582. break;
  17583. case 'Sprite':
  17584. object = new Sprite( getMaterial( data.material ) );
  17585. break;
  17586. case 'Group':
  17587. object = new Group();
  17588. break;
  17589. case 'Bone':
  17590. object = new Bone();
  17591. break;
  17592. default:
  17593. object = new Object3D();
  17594. }
  17595. object.uuid = data.uuid;
  17596. if ( data.name !== undefined ) object.name = data.name;
  17597. if ( data.matrix !== undefined ) {
  17598. object.matrix.fromArray( data.matrix );
  17599. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17600. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17601. } else {
  17602. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17603. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17604. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17605. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17606. }
  17607. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17608. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17609. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17610. if ( data.shadow ) {
  17611. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17612. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17613. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17614. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17615. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17616. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17617. }
  17618. if ( data.visible !== undefined ) object.visible = data.visible;
  17619. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17620. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17621. if ( data.userData !== undefined ) object.userData = data.userData;
  17622. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17623. if ( data.children !== undefined ) {
  17624. const children = data.children;
  17625. for ( let i = 0; i < children.length; i ++ ) {
  17626. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17627. }
  17628. }
  17629. if ( data.animations !== undefined ) {
  17630. const objectAnimations = data.animations;
  17631. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17632. const uuid = objectAnimations[ i ];
  17633. object.animations.push( animations[ uuid ] );
  17634. }
  17635. }
  17636. if ( data.type === 'LOD' ) {
  17637. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17638. const levels = data.levels;
  17639. for ( let l = 0; l < levels.length; l ++ ) {
  17640. const level = levels[ l ];
  17641. const child = object.getObjectByProperty( 'uuid', level.object );
  17642. if ( child !== undefined ) {
  17643. object.addLevel( child, level.distance, level.hysteresis );
  17644. }
  17645. }
  17646. }
  17647. return object;
  17648. }
  17649. bindSkeletons( object, skeletons ) {
  17650. if ( Object.keys( skeletons ).length === 0 ) return;
  17651. object.traverse( function ( child ) {
  17652. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17653. const skeleton = skeletons[ child.skeleton ];
  17654. if ( skeleton === undefined ) {
  17655. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17656. } else {
  17657. child.bind( skeleton, child.bindMatrix );
  17658. }
  17659. }
  17660. } );
  17661. }
  17662. bindLightTargets( object ) {
  17663. object.traverse( function ( child ) {
  17664. if ( child.isDirectionalLight || child.isSpotLight ) {
  17665. const uuid = child.target;
  17666. const target = object.getObjectByProperty( 'uuid', uuid );
  17667. if ( target !== undefined ) {
  17668. child.target = target;
  17669. } else {
  17670. child.target = new Object3D();
  17671. }
  17672. }
  17673. } );
  17674. }
  17675. }
  17676. const TEXTURE_MAPPING = {
  17677. UVMapping: UVMapping,
  17678. CubeReflectionMapping: CubeReflectionMapping,
  17679. CubeRefractionMapping: CubeRefractionMapping,
  17680. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17681. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17682. CubeUVReflectionMapping: CubeUVReflectionMapping
  17683. };
  17684. const TEXTURE_WRAPPING = {
  17685. RepeatWrapping: RepeatWrapping,
  17686. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17687. MirroredRepeatWrapping: MirroredRepeatWrapping
  17688. };
  17689. const TEXTURE_FILTER = {
  17690. NearestFilter: NearestFilter,
  17691. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17692. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17693. LinearFilter: LinearFilter,
  17694. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17695. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17696. };
  17697. class ImageBitmapLoader extends Loader {
  17698. constructor( manager ) {
  17699. super( manager );
  17700. this.isImageBitmapLoader = true;
  17701. if ( typeof createImageBitmap === 'undefined' ) {
  17702. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17703. }
  17704. if ( typeof fetch === 'undefined' ) {
  17705. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17706. }
  17707. this.options = { premultiplyAlpha: 'none' };
  17708. }
  17709. setOptions( options ) {
  17710. this.options = options;
  17711. return this;
  17712. }
  17713. load( url, onLoad, onProgress, onError ) {
  17714. if ( url === undefined ) url = '';
  17715. if ( this.path !== undefined ) url = this.path + url;
  17716. url = this.manager.resolveURL( url );
  17717. const scope = this;
  17718. const cached = Cache.get( url );
  17719. if ( cached !== undefined ) {
  17720. scope.manager.itemStart( url );
  17721. // If cached is a promise, wait for it to resolve
  17722. if ( cached.then ) {
  17723. cached.then( imageBitmap => {
  17724. if ( onLoad ) onLoad( imageBitmap );
  17725. scope.manager.itemEnd( url );
  17726. } ).catch( e => {
  17727. if ( onError ) onError( e );
  17728. } );
  17729. return;
  17730. }
  17731. // If cached is not a promise (i.e., it's already an imageBitmap)
  17732. setTimeout( function () {
  17733. if ( onLoad ) onLoad( cached );
  17734. scope.manager.itemEnd( url );
  17735. }, 0 );
  17736. return cached;
  17737. }
  17738. const fetchOptions = {};
  17739. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17740. fetchOptions.headers = this.requestHeader;
  17741. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17742. return res.blob();
  17743. } ).then( function ( blob ) {
  17744. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17745. } ).then( function ( imageBitmap ) {
  17746. Cache.add( url, imageBitmap );
  17747. if ( onLoad ) onLoad( imageBitmap );
  17748. scope.manager.itemEnd( url );
  17749. return imageBitmap;
  17750. } ).catch( function ( e ) {
  17751. if ( onError ) onError( e );
  17752. Cache.remove( url );
  17753. scope.manager.itemError( url );
  17754. scope.manager.itemEnd( url );
  17755. } );
  17756. Cache.add( url, promise );
  17757. scope.manager.itemStart( url );
  17758. }
  17759. }
  17760. let _context;
  17761. class AudioContext {
  17762. static getContext() {
  17763. if ( _context === undefined ) {
  17764. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17765. }
  17766. return _context;
  17767. }
  17768. static setContext( value ) {
  17769. _context = value;
  17770. }
  17771. }
  17772. class AudioLoader extends Loader {
  17773. constructor( manager ) {
  17774. super( manager );
  17775. }
  17776. load( url, onLoad, onProgress, onError ) {
  17777. const scope = this;
  17778. const loader = new FileLoader( this.manager );
  17779. loader.setResponseType( 'arraybuffer' );
  17780. loader.setPath( this.path );
  17781. loader.setRequestHeader( this.requestHeader );
  17782. loader.setWithCredentials( this.withCredentials );
  17783. loader.load( url, function ( buffer ) {
  17784. try {
  17785. // Create a copy of the buffer. The `decodeAudioData` method
  17786. // detaches the buffer when complete, preventing reuse.
  17787. const bufferCopy = buffer.slice( 0 );
  17788. const context = AudioContext.getContext();
  17789. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17790. onLoad( audioBuffer );
  17791. } ).catch( handleError );
  17792. } catch ( e ) {
  17793. handleError( e );
  17794. }
  17795. }, onProgress, onError );
  17796. function handleError( e ) {
  17797. if ( onError ) {
  17798. onError( e );
  17799. } else {
  17800. console.error( e );
  17801. }
  17802. scope.manager.itemError( url );
  17803. }
  17804. }
  17805. }
  17806. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17807. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17808. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17809. class StereoCamera {
  17810. constructor() {
  17811. this.type = 'StereoCamera';
  17812. this.aspect = 1;
  17813. this.eyeSep = 0.064;
  17814. this.cameraL = new PerspectiveCamera();
  17815. this.cameraL.layers.enable( 1 );
  17816. this.cameraL.matrixAutoUpdate = false;
  17817. this.cameraR = new PerspectiveCamera();
  17818. this.cameraR.layers.enable( 2 );
  17819. this.cameraR.matrixAutoUpdate = false;
  17820. this._cache = {
  17821. focus: null,
  17822. fov: null,
  17823. aspect: null,
  17824. near: null,
  17825. far: null,
  17826. zoom: null,
  17827. eyeSep: null
  17828. };
  17829. }
  17830. update( camera ) {
  17831. const cache = this._cache;
  17832. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17833. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17834. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17835. if ( needsUpdate ) {
  17836. cache.focus = camera.focus;
  17837. cache.fov = camera.fov;
  17838. cache.aspect = camera.aspect * this.aspect;
  17839. cache.near = camera.near;
  17840. cache.far = camera.far;
  17841. cache.zoom = camera.zoom;
  17842. cache.eyeSep = this.eyeSep;
  17843. // Off-axis stereoscopic effect based on
  17844. // http://paulbourke.net/stereographics/stereorender/
  17845. _projectionMatrix.copy( camera.projectionMatrix );
  17846. const eyeSepHalf = cache.eyeSep / 2;
  17847. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17848. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17849. let xmin, xmax;
  17850. // translate xOffset
  17851. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17852. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17853. // for left eye
  17854. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17855. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17856. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17857. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17858. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17859. // for right eye
  17860. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17861. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17862. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17863. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17864. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17865. }
  17866. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17867. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17868. }
  17869. }
  17870. class ArrayCamera extends PerspectiveCamera {
  17871. constructor( array = [] ) {
  17872. super();
  17873. this.isArrayCamera = true;
  17874. this.cameras = array;
  17875. }
  17876. }
  17877. class Clock {
  17878. constructor( autoStart = true ) {
  17879. this.autoStart = autoStart;
  17880. this.startTime = 0;
  17881. this.oldTime = 0;
  17882. this.elapsedTime = 0;
  17883. this.running = false;
  17884. }
  17885. start() {
  17886. this.startTime = now();
  17887. this.oldTime = this.startTime;
  17888. this.elapsedTime = 0;
  17889. this.running = true;
  17890. }
  17891. stop() {
  17892. this.getElapsedTime();
  17893. this.running = false;
  17894. this.autoStart = false;
  17895. }
  17896. getElapsedTime() {
  17897. this.getDelta();
  17898. return this.elapsedTime;
  17899. }
  17900. getDelta() {
  17901. let diff = 0;
  17902. if ( this.autoStart && ! this.running ) {
  17903. this.start();
  17904. return 0;
  17905. }
  17906. if ( this.running ) {
  17907. const newTime = now();
  17908. diff = ( newTime - this.oldTime ) / 1000;
  17909. this.oldTime = newTime;
  17910. this.elapsedTime += diff;
  17911. }
  17912. return diff;
  17913. }
  17914. }
  17915. function now() {
  17916. return performance.now();
  17917. }
  17918. const _position$1 = /*@__PURE__*/ new Vector3();
  17919. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17920. const _scale$1 = /*@__PURE__*/ new Vector3();
  17921. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17922. class AudioListener extends Object3D {
  17923. constructor() {
  17924. super();
  17925. this.type = 'AudioListener';
  17926. this.context = AudioContext.getContext();
  17927. this.gain = this.context.createGain();
  17928. this.gain.connect( this.context.destination );
  17929. this.filter = null;
  17930. this.timeDelta = 0;
  17931. // private
  17932. this._clock = new Clock();
  17933. }
  17934. getInput() {
  17935. return this.gain;
  17936. }
  17937. removeFilter() {
  17938. if ( this.filter !== null ) {
  17939. this.gain.disconnect( this.filter );
  17940. this.filter.disconnect( this.context.destination );
  17941. this.gain.connect( this.context.destination );
  17942. this.filter = null;
  17943. }
  17944. return this;
  17945. }
  17946. getFilter() {
  17947. return this.filter;
  17948. }
  17949. setFilter( value ) {
  17950. if ( this.filter !== null ) {
  17951. this.gain.disconnect( this.filter );
  17952. this.filter.disconnect( this.context.destination );
  17953. } else {
  17954. this.gain.disconnect( this.context.destination );
  17955. }
  17956. this.filter = value;
  17957. this.gain.connect( this.filter );
  17958. this.filter.connect( this.context.destination );
  17959. return this;
  17960. }
  17961. getMasterVolume() {
  17962. return this.gain.gain.value;
  17963. }
  17964. setMasterVolume( value ) {
  17965. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17966. return this;
  17967. }
  17968. updateMatrixWorld( force ) {
  17969. super.updateMatrixWorld( force );
  17970. const listener = this.context.listener;
  17971. const up = this.up;
  17972. this.timeDelta = this._clock.getDelta();
  17973. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17974. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17975. if ( listener.positionX ) {
  17976. // code path for Chrome (see #14393)
  17977. const endTime = this.context.currentTime + this.timeDelta;
  17978. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17979. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17980. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17981. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17982. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17983. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17984. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17985. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17986. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17987. } else {
  17988. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17989. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17990. }
  17991. }
  17992. }
  17993. class Audio extends Object3D {
  17994. constructor( listener ) {
  17995. super();
  17996. this.type = 'Audio';
  17997. this.listener = listener;
  17998. this.context = listener.context;
  17999. this.gain = this.context.createGain();
  18000. this.gain.connect( listener.getInput() );
  18001. this.autoplay = false;
  18002. this.buffer = null;
  18003. this.detune = 0;
  18004. this.loop = false;
  18005. this.loopStart = 0;
  18006. this.loopEnd = 0;
  18007. this.offset = 0;
  18008. this.duration = undefined;
  18009. this.playbackRate = 1;
  18010. this.isPlaying = false;
  18011. this.hasPlaybackControl = true;
  18012. this.source = null;
  18013. this.sourceType = 'empty';
  18014. this._startedAt = 0;
  18015. this._progress = 0;
  18016. this._connected = false;
  18017. this.filters = [];
  18018. }
  18019. getOutput() {
  18020. return this.gain;
  18021. }
  18022. setNodeSource( audioNode ) {
  18023. this.hasPlaybackControl = false;
  18024. this.sourceType = 'audioNode';
  18025. this.source = audioNode;
  18026. this.connect();
  18027. return this;
  18028. }
  18029. setMediaElementSource( mediaElement ) {
  18030. this.hasPlaybackControl = false;
  18031. this.sourceType = 'mediaNode';
  18032. this.source = this.context.createMediaElementSource( mediaElement );
  18033. this.connect();
  18034. return this;
  18035. }
  18036. setMediaStreamSource( mediaStream ) {
  18037. this.hasPlaybackControl = false;
  18038. this.sourceType = 'mediaStreamNode';
  18039. this.source = this.context.createMediaStreamSource( mediaStream );
  18040. this.connect();
  18041. return this;
  18042. }
  18043. setBuffer( audioBuffer ) {
  18044. this.buffer = audioBuffer;
  18045. this.sourceType = 'buffer';
  18046. if ( this.autoplay ) this.play();
  18047. return this;
  18048. }
  18049. play( delay = 0 ) {
  18050. if ( this.isPlaying === true ) {
  18051. console.warn( 'THREE.Audio: Audio is already playing.' );
  18052. return;
  18053. }
  18054. if ( this.hasPlaybackControl === false ) {
  18055. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18056. return;
  18057. }
  18058. this._startedAt = this.context.currentTime + delay;
  18059. const source = this.context.createBufferSource();
  18060. source.buffer = this.buffer;
  18061. source.loop = this.loop;
  18062. source.loopStart = this.loopStart;
  18063. source.loopEnd = this.loopEnd;
  18064. source.onended = this.onEnded.bind( this );
  18065. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18066. this.isPlaying = true;
  18067. this.source = source;
  18068. this.setDetune( this.detune );
  18069. this.setPlaybackRate( this.playbackRate );
  18070. return this.connect();
  18071. }
  18072. pause() {
  18073. if ( this.hasPlaybackControl === false ) {
  18074. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18075. return;
  18076. }
  18077. if ( this.isPlaying === true ) {
  18078. // update current progress
  18079. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18080. if ( this.loop === true ) {
  18081. // ensure _progress does not exceed duration with looped audios
  18082. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18083. }
  18084. this.source.stop();
  18085. this.source.onended = null;
  18086. this.isPlaying = false;
  18087. }
  18088. return this;
  18089. }
  18090. stop( delay = 0 ) {
  18091. if ( this.hasPlaybackControl === false ) {
  18092. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18093. return;
  18094. }
  18095. this._progress = 0;
  18096. if ( this.source !== null ) {
  18097. this.source.stop( this.context.currentTime + delay );
  18098. this.source.onended = null;
  18099. }
  18100. this.isPlaying = false;
  18101. return this;
  18102. }
  18103. connect() {
  18104. if ( this.filters.length > 0 ) {
  18105. this.source.connect( this.filters[ 0 ] );
  18106. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18107. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18108. }
  18109. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18110. } else {
  18111. this.source.connect( this.getOutput() );
  18112. }
  18113. this._connected = true;
  18114. return this;
  18115. }
  18116. disconnect() {
  18117. if ( this._connected === false ) {
  18118. return;
  18119. }
  18120. if ( this.filters.length > 0 ) {
  18121. this.source.disconnect( this.filters[ 0 ] );
  18122. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18123. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18124. }
  18125. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18126. } else {
  18127. this.source.disconnect( this.getOutput() );
  18128. }
  18129. this._connected = false;
  18130. return this;
  18131. }
  18132. getFilters() {
  18133. return this.filters;
  18134. }
  18135. setFilters( value ) {
  18136. if ( ! value ) value = [];
  18137. if ( this._connected === true ) {
  18138. this.disconnect();
  18139. this.filters = value.slice();
  18140. this.connect();
  18141. } else {
  18142. this.filters = value.slice();
  18143. }
  18144. return this;
  18145. }
  18146. setDetune( value ) {
  18147. this.detune = value;
  18148. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18149. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18150. }
  18151. return this;
  18152. }
  18153. getDetune() {
  18154. return this.detune;
  18155. }
  18156. getFilter() {
  18157. return this.getFilters()[ 0 ];
  18158. }
  18159. setFilter( filter ) {
  18160. return this.setFilters( filter ? [ filter ] : [] );
  18161. }
  18162. setPlaybackRate( value ) {
  18163. if ( this.hasPlaybackControl === false ) {
  18164. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18165. return;
  18166. }
  18167. this.playbackRate = value;
  18168. if ( this.isPlaying === true ) {
  18169. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18170. }
  18171. return this;
  18172. }
  18173. getPlaybackRate() {
  18174. return this.playbackRate;
  18175. }
  18176. onEnded() {
  18177. this.isPlaying = false;
  18178. }
  18179. getLoop() {
  18180. if ( this.hasPlaybackControl === false ) {
  18181. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18182. return false;
  18183. }
  18184. return this.loop;
  18185. }
  18186. setLoop( value ) {
  18187. if ( this.hasPlaybackControl === false ) {
  18188. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18189. return;
  18190. }
  18191. this.loop = value;
  18192. if ( this.isPlaying === true ) {
  18193. this.source.loop = this.loop;
  18194. }
  18195. return this;
  18196. }
  18197. setLoopStart( value ) {
  18198. this.loopStart = value;
  18199. return this;
  18200. }
  18201. setLoopEnd( value ) {
  18202. this.loopEnd = value;
  18203. return this;
  18204. }
  18205. getVolume() {
  18206. return this.gain.gain.value;
  18207. }
  18208. setVolume( value ) {
  18209. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18210. return this;
  18211. }
  18212. }
  18213. const _position = /*@__PURE__*/ new Vector3();
  18214. const _quaternion = /*@__PURE__*/ new Quaternion();
  18215. const _scale = /*@__PURE__*/ new Vector3();
  18216. const _orientation = /*@__PURE__*/ new Vector3();
  18217. class PositionalAudio extends Audio {
  18218. constructor( listener ) {
  18219. super( listener );
  18220. this.panner = this.context.createPanner();
  18221. this.panner.panningModel = 'HRTF';
  18222. this.panner.connect( this.gain );
  18223. }
  18224. connect() {
  18225. super.connect();
  18226. this.panner.connect( this.gain );
  18227. }
  18228. disconnect() {
  18229. super.disconnect();
  18230. this.panner.disconnect( this.gain );
  18231. }
  18232. getOutput() {
  18233. return this.panner;
  18234. }
  18235. getRefDistance() {
  18236. return this.panner.refDistance;
  18237. }
  18238. setRefDistance( value ) {
  18239. this.panner.refDistance = value;
  18240. return this;
  18241. }
  18242. getRolloffFactor() {
  18243. return this.panner.rolloffFactor;
  18244. }
  18245. setRolloffFactor( value ) {
  18246. this.panner.rolloffFactor = value;
  18247. return this;
  18248. }
  18249. getDistanceModel() {
  18250. return this.panner.distanceModel;
  18251. }
  18252. setDistanceModel( value ) {
  18253. this.panner.distanceModel = value;
  18254. return this;
  18255. }
  18256. getMaxDistance() {
  18257. return this.panner.maxDistance;
  18258. }
  18259. setMaxDistance( value ) {
  18260. this.panner.maxDistance = value;
  18261. return this;
  18262. }
  18263. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18264. this.panner.coneInnerAngle = coneInnerAngle;
  18265. this.panner.coneOuterAngle = coneOuterAngle;
  18266. this.panner.coneOuterGain = coneOuterGain;
  18267. return this;
  18268. }
  18269. updateMatrixWorld( force ) {
  18270. super.updateMatrixWorld( force );
  18271. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18272. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18273. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18274. const panner = this.panner;
  18275. if ( panner.positionX ) {
  18276. // code path for Chrome and Firefox (see #14393)
  18277. const endTime = this.context.currentTime + this.listener.timeDelta;
  18278. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18279. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18280. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18281. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18282. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18283. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18284. } else {
  18285. panner.setPosition( _position.x, _position.y, _position.z );
  18286. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18287. }
  18288. }
  18289. }
  18290. class AudioAnalyser {
  18291. constructor( audio, fftSize = 2048 ) {
  18292. this.analyser = audio.context.createAnalyser();
  18293. this.analyser.fftSize = fftSize;
  18294. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18295. audio.getOutput().connect( this.analyser );
  18296. }
  18297. getFrequencyData() {
  18298. this.analyser.getByteFrequencyData( this.data );
  18299. return this.data;
  18300. }
  18301. getAverageFrequency() {
  18302. let value = 0;
  18303. const data = this.getFrequencyData();
  18304. for ( let i = 0; i < data.length; i ++ ) {
  18305. value += data[ i ];
  18306. }
  18307. return value / data.length;
  18308. }
  18309. }
  18310. class PropertyMixer {
  18311. constructor( binding, typeName, valueSize ) {
  18312. this.binding = binding;
  18313. this.valueSize = valueSize;
  18314. let mixFunction,
  18315. mixFunctionAdditive,
  18316. setIdentity;
  18317. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18318. //
  18319. // interpolators can use .buffer as their .result
  18320. // the data then goes to 'incoming'
  18321. //
  18322. // 'accu0' and 'accu1' are used frame-interleaved for
  18323. // the cumulative result and are compared to detect
  18324. // changes
  18325. //
  18326. // 'orig' stores the original state of the property
  18327. //
  18328. // 'add' is used for additive cumulative results
  18329. //
  18330. // 'work' is optional and is only present for quaternion types. It is used
  18331. // to store intermediate quaternion multiplication results
  18332. switch ( typeName ) {
  18333. case 'quaternion':
  18334. mixFunction = this._slerp;
  18335. mixFunctionAdditive = this._slerpAdditive;
  18336. setIdentity = this._setAdditiveIdentityQuaternion;
  18337. this.buffer = new Float64Array( valueSize * 6 );
  18338. this._workIndex = 5;
  18339. break;
  18340. case 'string':
  18341. case 'bool':
  18342. mixFunction = this._select;
  18343. // Use the regular mix function and for additive on these types,
  18344. // additive is not relevant for non-numeric types
  18345. mixFunctionAdditive = this._select;
  18346. setIdentity = this._setAdditiveIdentityOther;
  18347. this.buffer = new Array( valueSize * 5 );
  18348. break;
  18349. default:
  18350. mixFunction = this._lerp;
  18351. mixFunctionAdditive = this._lerpAdditive;
  18352. setIdentity = this._setAdditiveIdentityNumeric;
  18353. this.buffer = new Float64Array( valueSize * 5 );
  18354. }
  18355. this._mixBufferRegion = mixFunction;
  18356. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18357. this._setIdentity = setIdentity;
  18358. this._origIndex = 3;
  18359. this._addIndex = 4;
  18360. this.cumulativeWeight = 0;
  18361. this.cumulativeWeightAdditive = 0;
  18362. this.useCount = 0;
  18363. this.referenceCount = 0;
  18364. }
  18365. // accumulate data in the 'incoming' region into 'accu<i>'
  18366. accumulate( accuIndex, weight ) {
  18367. // note: happily accumulating nothing when weight = 0, the caller knows
  18368. // the weight and shouldn't have made the call in the first place
  18369. const buffer = this.buffer,
  18370. stride = this.valueSize,
  18371. offset = accuIndex * stride + stride;
  18372. let currentWeight = this.cumulativeWeight;
  18373. if ( currentWeight === 0 ) {
  18374. // accuN := incoming * weight
  18375. for ( let i = 0; i !== stride; ++ i ) {
  18376. buffer[ offset + i ] = buffer[ i ];
  18377. }
  18378. currentWeight = weight;
  18379. } else {
  18380. // accuN := accuN + incoming * weight
  18381. currentWeight += weight;
  18382. const mix = weight / currentWeight;
  18383. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18384. }
  18385. this.cumulativeWeight = currentWeight;
  18386. }
  18387. // accumulate data in the 'incoming' region into 'add'
  18388. accumulateAdditive( weight ) {
  18389. const buffer = this.buffer,
  18390. stride = this.valueSize,
  18391. offset = stride * this._addIndex;
  18392. if ( this.cumulativeWeightAdditive === 0 ) {
  18393. // add = identity
  18394. this._setIdentity();
  18395. }
  18396. // add := add + incoming * weight
  18397. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18398. this.cumulativeWeightAdditive += weight;
  18399. }
  18400. // apply the state of 'accu<i>' to the binding when accus differ
  18401. apply( accuIndex ) {
  18402. const stride = this.valueSize,
  18403. buffer = this.buffer,
  18404. offset = accuIndex * stride + stride,
  18405. weight = this.cumulativeWeight,
  18406. weightAdditive = this.cumulativeWeightAdditive,
  18407. binding = this.binding;
  18408. this.cumulativeWeight = 0;
  18409. this.cumulativeWeightAdditive = 0;
  18410. if ( weight < 1 ) {
  18411. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18412. const originalValueOffset = stride * this._origIndex;
  18413. this._mixBufferRegion(
  18414. buffer, offset, originalValueOffset, 1 - weight, stride );
  18415. }
  18416. if ( weightAdditive > 0 ) {
  18417. // accuN := accuN + additive accuN
  18418. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18419. }
  18420. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18421. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18422. // value has changed -> update scene graph
  18423. binding.setValue( buffer, offset );
  18424. break;
  18425. }
  18426. }
  18427. }
  18428. // remember the state of the bound property and copy it to both accus
  18429. saveOriginalState() {
  18430. const binding = this.binding;
  18431. const buffer = this.buffer,
  18432. stride = this.valueSize,
  18433. originalValueOffset = stride * this._origIndex;
  18434. binding.getValue( buffer, originalValueOffset );
  18435. // accu[0..1] := orig -- initially detect changes against the original
  18436. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18437. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18438. }
  18439. // Add to identity for additive
  18440. this._setIdentity();
  18441. this.cumulativeWeight = 0;
  18442. this.cumulativeWeightAdditive = 0;
  18443. }
  18444. // apply the state previously taken via 'saveOriginalState' to the binding
  18445. restoreOriginalState() {
  18446. const originalValueOffset = this.valueSize * 3;
  18447. this.binding.setValue( this.buffer, originalValueOffset );
  18448. }
  18449. _setAdditiveIdentityNumeric() {
  18450. const startIndex = this._addIndex * this.valueSize;
  18451. const endIndex = startIndex + this.valueSize;
  18452. for ( let i = startIndex; i < endIndex; i ++ ) {
  18453. this.buffer[ i ] = 0;
  18454. }
  18455. }
  18456. _setAdditiveIdentityQuaternion() {
  18457. this._setAdditiveIdentityNumeric();
  18458. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18459. }
  18460. _setAdditiveIdentityOther() {
  18461. const startIndex = this._origIndex * this.valueSize;
  18462. const targetIndex = this._addIndex * this.valueSize;
  18463. for ( let i = 0; i < this.valueSize; i ++ ) {
  18464. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18465. }
  18466. }
  18467. // mix functions
  18468. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18469. if ( t >= 0.5 ) {
  18470. for ( let i = 0; i !== stride; ++ i ) {
  18471. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18472. }
  18473. }
  18474. }
  18475. _slerp( buffer, dstOffset, srcOffset, t ) {
  18476. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18477. }
  18478. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18479. const workOffset = this._workIndex * stride;
  18480. // Store result in intermediate buffer offset
  18481. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18482. // Slerp to the intermediate result
  18483. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18484. }
  18485. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18486. const s = 1 - t;
  18487. for ( let i = 0; i !== stride; ++ i ) {
  18488. const j = dstOffset + i;
  18489. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18490. }
  18491. }
  18492. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18493. for ( let i = 0; i !== stride; ++ i ) {
  18494. const j = dstOffset + i;
  18495. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18496. }
  18497. }
  18498. }
  18499. // Characters [].:/ are reserved for track binding syntax.
  18500. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18501. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18502. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18503. // only latin characters, and the unicode \p{L} is not yet supported. So
  18504. // instead, we exclude reserved characters and match everything else.
  18505. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18506. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18507. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18508. // be matched to parse the rest of the track name.
  18509. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18510. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18511. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18512. // Object on target node, and accessor. May not contain reserved
  18513. // characters. Accessor may contain any character except closing bracket.
  18514. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18515. // Property and accessor. May not contain reserved characters. Accessor may
  18516. // contain any non-bracket characters.
  18517. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18518. const _trackRe = new RegExp( ''
  18519. + '^'
  18520. + _directoryRe
  18521. + _nodeRe
  18522. + _objectRe
  18523. + _propertyRe
  18524. + '$'
  18525. );
  18526. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18527. class Composite {
  18528. constructor( targetGroup, path, optionalParsedPath ) {
  18529. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18530. this._targetGroup = targetGroup;
  18531. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18532. }
  18533. getValue( array, offset ) {
  18534. this.bind(); // bind all binding
  18535. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18536. binding = this._bindings[ firstValidIndex ];
  18537. // and only call .getValue on the first
  18538. if ( binding !== undefined ) binding.getValue( array, offset );
  18539. }
  18540. setValue( array, offset ) {
  18541. const bindings = this._bindings;
  18542. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18543. bindings[ i ].setValue( array, offset );
  18544. }
  18545. }
  18546. bind() {
  18547. const bindings = this._bindings;
  18548. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18549. bindings[ i ].bind();
  18550. }
  18551. }
  18552. unbind() {
  18553. const bindings = this._bindings;
  18554. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18555. bindings[ i ].unbind();
  18556. }
  18557. }
  18558. }
  18559. // Note: This class uses a State pattern on a per-method basis:
  18560. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18561. // prototype version of these methods with one that represents
  18562. // the bound state. When the property is not found, the methods
  18563. // become no-ops.
  18564. class PropertyBinding {
  18565. constructor( rootNode, path, parsedPath ) {
  18566. this.path = path;
  18567. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18568. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18569. this.rootNode = rootNode;
  18570. // initial state of these methods that calls 'bind'
  18571. this.getValue = this._getValue_unbound;
  18572. this.setValue = this._setValue_unbound;
  18573. }
  18574. static create( root, path, parsedPath ) {
  18575. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18576. return new PropertyBinding( root, path, parsedPath );
  18577. } else {
  18578. return new PropertyBinding.Composite( root, path, parsedPath );
  18579. }
  18580. }
  18581. /**
  18582. * Replaces spaces with underscores and removes unsupported characters from
  18583. * node names, to ensure compatibility with parseTrackName().
  18584. *
  18585. * @param {string} name Node name to be sanitized.
  18586. * @return {string}
  18587. */
  18588. static sanitizeNodeName( name ) {
  18589. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18590. }
  18591. static parseTrackName( trackName ) {
  18592. const matches = _trackRe.exec( trackName );
  18593. if ( matches === null ) {
  18594. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18595. }
  18596. const results = {
  18597. // directoryName: matches[ 1 ], // (tschw) currently unused
  18598. nodeName: matches[ 2 ],
  18599. objectName: matches[ 3 ],
  18600. objectIndex: matches[ 4 ],
  18601. propertyName: matches[ 5 ], // required
  18602. propertyIndex: matches[ 6 ]
  18603. };
  18604. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18605. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18606. const objectName = results.nodeName.substring( lastDot + 1 );
  18607. // Object names must be checked against an allowlist. Otherwise, there
  18608. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18609. // 'bar' could be the objectName, or part of a nodeName (which can
  18610. // include '.' characters).
  18611. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18612. results.nodeName = results.nodeName.substring( 0, lastDot );
  18613. results.objectName = objectName;
  18614. }
  18615. }
  18616. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18617. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18618. }
  18619. return results;
  18620. }
  18621. static findNode( root, nodeName ) {
  18622. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18623. return root;
  18624. }
  18625. // search into skeleton bones.
  18626. if ( root.skeleton ) {
  18627. const bone = root.skeleton.getBoneByName( nodeName );
  18628. if ( bone !== undefined ) {
  18629. return bone;
  18630. }
  18631. }
  18632. // search into node subtree.
  18633. if ( root.children ) {
  18634. const searchNodeSubtree = function ( children ) {
  18635. for ( let i = 0; i < children.length; i ++ ) {
  18636. const childNode = children[ i ];
  18637. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18638. return childNode;
  18639. }
  18640. const result = searchNodeSubtree( childNode.children );
  18641. if ( result ) return result;
  18642. }
  18643. return null;
  18644. };
  18645. const subTreeNode = searchNodeSubtree( root.children );
  18646. if ( subTreeNode ) {
  18647. return subTreeNode;
  18648. }
  18649. }
  18650. return null;
  18651. }
  18652. // these are used to "bind" a nonexistent property
  18653. _getValue_unavailable() {}
  18654. _setValue_unavailable() {}
  18655. // Getters
  18656. _getValue_direct( buffer, offset ) {
  18657. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18658. }
  18659. _getValue_array( buffer, offset ) {
  18660. const source = this.resolvedProperty;
  18661. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18662. buffer[ offset ++ ] = source[ i ];
  18663. }
  18664. }
  18665. _getValue_arrayElement( buffer, offset ) {
  18666. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18667. }
  18668. _getValue_toArray( buffer, offset ) {
  18669. this.resolvedProperty.toArray( buffer, offset );
  18670. }
  18671. // Direct
  18672. _setValue_direct( buffer, offset ) {
  18673. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18674. }
  18675. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18676. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18677. this.targetObject.needsUpdate = true;
  18678. }
  18679. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18680. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18681. this.targetObject.matrixWorldNeedsUpdate = true;
  18682. }
  18683. // EntireArray
  18684. _setValue_array( buffer, offset ) {
  18685. const dest = this.resolvedProperty;
  18686. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18687. dest[ i ] = buffer[ offset ++ ];
  18688. }
  18689. }
  18690. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18691. const dest = this.resolvedProperty;
  18692. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18693. dest[ i ] = buffer[ offset ++ ];
  18694. }
  18695. this.targetObject.needsUpdate = true;
  18696. }
  18697. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18698. const dest = this.resolvedProperty;
  18699. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18700. dest[ i ] = buffer[ offset ++ ];
  18701. }
  18702. this.targetObject.matrixWorldNeedsUpdate = true;
  18703. }
  18704. // ArrayElement
  18705. _setValue_arrayElement( buffer, offset ) {
  18706. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18707. }
  18708. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18709. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18710. this.targetObject.needsUpdate = true;
  18711. }
  18712. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18713. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18714. this.targetObject.matrixWorldNeedsUpdate = true;
  18715. }
  18716. // HasToFromArray
  18717. _setValue_fromArray( buffer, offset ) {
  18718. this.resolvedProperty.fromArray( buffer, offset );
  18719. }
  18720. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18721. this.resolvedProperty.fromArray( buffer, offset );
  18722. this.targetObject.needsUpdate = true;
  18723. }
  18724. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18725. this.resolvedProperty.fromArray( buffer, offset );
  18726. this.targetObject.matrixWorldNeedsUpdate = true;
  18727. }
  18728. _getValue_unbound( targetArray, offset ) {
  18729. this.bind();
  18730. this.getValue( targetArray, offset );
  18731. }
  18732. _setValue_unbound( sourceArray, offset ) {
  18733. this.bind();
  18734. this.setValue( sourceArray, offset );
  18735. }
  18736. // create getter / setter pair for a property in the scene graph
  18737. bind() {
  18738. let targetObject = this.node;
  18739. const parsedPath = this.parsedPath;
  18740. const objectName = parsedPath.objectName;
  18741. const propertyName = parsedPath.propertyName;
  18742. let propertyIndex = parsedPath.propertyIndex;
  18743. if ( ! targetObject ) {
  18744. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18745. this.node = targetObject;
  18746. }
  18747. // set fail state so we can just 'return' on error
  18748. this.getValue = this._getValue_unavailable;
  18749. this.setValue = this._setValue_unavailable;
  18750. // ensure there is a value node
  18751. if ( ! targetObject ) {
  18752. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18753. return;
  18754. }
  18755. if ( objectName ) {
  18756. let objectIndex = parsedPath.objectIndex;
  18757. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18758. switch ( objectName ) {
  18759. case 'materials':
  18760. if ( ! targetObject.material ) {
  18761. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18762. return;
  18763. }
  18764. if ( ! targetObject.material.materials ) {
  18765. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18766. return;
  18767. }
  18768. targetObject = targetObject.material.materials;
  18769. break;
  18770. case 'bones':
  18771. if ( ! targetObject.skeleton ) {
  18772. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18773. return;
  18774. }
  18775. // potential future optimization: skip this if propertyIndex is already an integer
  18776. // and convert the integer string to a true integer.
  18777. targetObject = targetObject.skeleton.bones;
  18778. // support resolving morphTarget names into indices.
  18779. for ( let i = 0; i < targetObject.length; i ++ ) {
  18780. if ( targetObject[ i ].name === objectIndex ) {
  18781. objectIndex = i;
  18782. break;
  18783. }
  18784. }
  18785. break;
  18786. case 'map':
  18787. if ( 'map' in targetObject ) {
  18788. targetObject = targetObject.map;
  18789. break;
  18790. }
  18791. if ( ! targetObject.material ) {
  18792. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18793. return;
  18794. }
  18795. if ( ! targetObject.material.map ) {
  18796. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18797. return;
  18798. }
  18799. targetObject = targetObject.material.map;
  18800. break;
  18801. default:
  18802. if ( targetObject[ objectName ] === undefined ) {
  18803. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18804. return;
  18805. }
  18806. targetObject = targetObject[ objectName ];
  18807. }
  18808. if ( objectIndex !== undefined ) {
  18809. if ( targetObject[ objectIndex ] === undefined ) {
  18810. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18811. return;
  18812. }
  18813. targetObject = targetObject[ objectIndex ];
  18814. }
  18815. }
  18816. // resolve property
  18817. const nodeProperty = targetObject[ propertyName ];
  18818. if ( nodeProperty === undefined ) {
  18819. const nodeName = parsedPath.nodeName;
  18820. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18821. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18822. return;
  18823. }
  18824. // determine versioning scheme
  18825. let versioning = this.Versioning.None;
  18826. this.targetObject = targetObject;
  18827. if ( targetObject.needsUpdate !== undefined ) { // material
  18828. versioning = this.Versioning.NeedsUpdate;
  18829. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18830. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18831. }
  18832. // determine how the property gets bound
  18833. let bindingType = this.BindingType.Direct;
  18834. if ( propertyIndex !== undefined ) {
  18835. // access a sub element of the property array (only primitives are supported right now)
  18836. if ( propertyName === 'morphTargetInfluences' ) {
  18837. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18838. // support resolving morphTarget names into indices.
  18839. if ( ! targetObject.geometry ) {
  18840. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18841. return;
  18842. }
  18843. if ( ! targetObject.geometry.morphAttributes ) {
  18844. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18845. return;
  18846. }
  18847. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18848. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18849. }
  18850. }
  18851. bindingType = this.BindingType.ArrayElement;
  18852. this.resolvedProperty = nodeProperty;
  18853. this.propertyIndex = propertyIndex;
  18854. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18855. // must use copy for Object3D.Euler/Quaternion
  18856. bindingType = this.BindingType.HasFromToArray;
  18857. this.resolvedProperty = nodeProperty;
  18858. } else if ( Array.isArray( nodeProperty ) ) {
  18859. bindingType = this.BindingType.EntireArray;
  18860. this.resolvedProperty = nodeProperty;
  18861. } else {
  18862. this.propertyName = propertyName;
  18863. }
  18864. // select getter / setter
  18865. this.getValue = this.GetterByBindingType[ bindingType ];
  18866. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18867. }
  18868. unbind() {
  18869. this.node = null;
  18870. // back to the prototype version of getValue / setValue
  18871. // note: avoiding to mutate the shape of 'this' via 'delete'
  18872. this.getValue = this._getValue_unbound;
  18873. this.setValue = this._setValue_unbound;
  18874. }
  18875. }
  18876. PropertyBinding.Composite = Composite;
  18877. PropertyBinding.prototype.BindingType = {
  18878. Direct: 0,
  18879. EntireArray: 1,
  18880. ArrayElement: 2,
  18881. HasFromToArray: 3
  18882. };
  18883. PropertyBinding.prototype.Versioning = {
  18884. None: 0,
  18885. NeedsUpdate: 1,
  18886. MatrixWorldNeedsUpdate: 2
  18887. };
  18888. PropertyBinding.prototype.GetterByBindingType = [
  18889. PropertyBinding.prototype._getValue_direct,
  18890. PropertyBinding.prototype._getValue_array,
  18891. PropertyBinding.prototype._getValue_arrayElement,
  18892. PropertyBinding.prototype._getValue_toArray,
  18893. ];
  18894. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18895. [
  18896. // Direct
  18897. PropertyBinding.prototype._setValue_direct,
  18898. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18899. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18900. ], [
  18901. // EntireArray
  18902. PropertyBinding.prototype._setValue_array,
  18903. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18904. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18905. ], [
  18906. // ArrayElement
  18907. PropertyBinding.prototype._setValue_arrayElement,
  18908. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18909. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18910. ], [
  18911. // HasToFromArray
  18912. PropertyBinding.prototype._setValue_fromArray,
  18913. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18914. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18915. ]
  18916. ];
  18917. /**
  18918. *
  18919. * A group of objects that receives a shared animation state.
  18920. *
  18921. * Usage:
  18922. *
  18923. * - Add objects you would otherwise pass as 'root' to the
  18924. * constructor or the .clipAction method of AnimationMixer.
  18925. *
  18926. * - Instead pass this object as 'root'.
  18927. *
  18928. * - You can also add and remove objects later when the mixer
  18929. * is running.
  18930. *
  18931. * Note:
  18932. *
  18933. * Objects of this class appear as one object to the mixer,
  18934. * so cache control of the individual objects must be done
  18935. * on the group.
  18936. *
  18937. * Limitation:
  18938. *
  18939. * - The animated properties must be compatible among the
  18940. * all objects in the group.
  18941. *
  18942. * - A single property can either be controlled through a
  18943. * target group or directly, but not both.
  18944. */
  18945. class AnimationObjectGroup {
  18946. constructor() {
  18947. this.isAnimationObjectGroup = true;
  18948. this.uuid = generateUUID();
  18949. // cached objects followed by the active ones
  18950. this._objects = Array.prototype.slice.call( arguments );
  18951. this.nCachedObjects_ = 0; // threshold
  18952. // note: read by PropertyBinding.Composite
  18953. const indices = {};
  18954. this._indicesByUUID = indices; // for bookkeeping
  18955. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18956. indices[ arguments[ i ].uuid ] = i;
  18957. }
  18958. this._paths = []; // inside: string
  18959. this._parsedPaths = []; // inside: { we don't care, here }
  18960. this._bindings = []; // inside: Array< PropertyBinding >
  18961. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18962. const scope = this;
  18963. this.stats = {
  18964. objects: {
  18965. get total() {
  18966. return scope._objects.length;
  18967. },
  18968. get inUse() {
  18969. return this.total - scope.nCachedObjects_;
  18970. }
  18971. },
  18972. get bindingsPerObject() {
  18973. return scope._bindings.length;
  18974. }
  18975. };
  18976. }
  18977. add() {
  18978. const objects = this._objects,
  18979. indicesByUUID = this._indicesByUUID,
  18980. paths = this._paths,
  18981. parsedPaths = this._parsedPaths,
  18982. bindings = this._bindings,
  18983. nBindings = bindings.length;
  18984. let knownObject = undefined,
  18985. nObjects = objects.length,
  18986. nCachedObjects = this.nCachedObjects_;
  18987. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18988. const object = arguments[ i ],
  18989. uuid = object.uuid;
  18990. let index = indicesByUUID[ uuid ];
  18991. if ( index === undefined ) {
  18992. // unknown object -> add it to the ACTIVE region
  18993. index = nObjects ++;
  18994. indicesByUUID[ uuid ] = index;
  18995. objects.push( object );
  18996. // accounting is done, now do the same for all bindings
  18997. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18998. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18999. }
  19000. } else if ( index < nCachedObjects ) {
  19001. knownObject = objects[ index ];
  19002. // move existing object to the ACTIVE region
  19003. const firstActiveIndex = -- nCachedObjects,
  19004. lastCachedObject = objects[ firstActiveIndex ];
  19005. indicesByUUID[ lastCachedObject.uuid ] = index;
  19006. objects[ index ] = lastCachedObject;
  19007. indicesByUUID[ uuid ] = firstActiveIndex;
  19008. objects[ firstActiveIndex ] = object;
  19009. // accounting is done, now do the same for all bindings
  19010. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19011. const bindingsForPath = bindings[ j ],
  19012. lastCached = bindingsForPath[ firstActiveIndex ];
  19013. let binding = bindingsForPath[ index ];
  19014. bindingsForPath[ index ] = lastCached;
  19015. if ( binding === undefined ) {
  19016. // since we do not bother to create new bindings
  19017. // for objects that are cached, the binding may
  19018. // or may not exist
  19019. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19020. }
  19021. bindingsForPath[ firstActiveIndex ] = binding;
  19022. }
  19023. } else if ( objects[ index ] !== knownObject ) {
  19024. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19025. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19026. } // else the object is already where we want it to be
  19027. } // for arguments
  19028. this.nCachedObjects_ = nCachedObjects;
  19029. }
  19030. remove() {
  19031. const objects = this._objects,
  19032. indicesByUUID = this._indicesByUUID,
  19033. bindings = this._bindings,
  19034. nBindings = bindings.length;
  19035. let nCachedObjects = this.nCachedObjects_;
  19036. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19037. const object = arguments[ i ],
  19038. uuid = object.uuid,
  19039. index = indicesByUUID[ uuid ];
  19040. if ( index !== undefined && index >= nCachedObjects ) {
  19041. // move existing object into the CACHED region
  19042. const lastCachedIndex = nCachedObjects ++,
  19043. firstActiveObject = objects[ lastCachedIndex ];
  19044. indicesByUUID[ firstActiveObject.uuid ] = index;
  19045. objects[ index ] = firstActiveObject;
  19046. indicesByUUID[ uuid ] = lastCachedIndex;
  19047. objects[ lastCachedIndex ] = object;
  19048. // accounting is done, now do the same for all bindings
  19049. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19050. const bindingsForPath = bindings[ j ],
  19051. firstActive = bindingsForPath[ lastCachedIndex ],
  19052. binding = bindingsForPath[ index ];
  19053. bindingsForPath[ index ] = firstActive;
  19054. bindingsForPath[ lastCachedIndex ] = binding;
  19055. }
  19056. }
  19057. } // for arguments
  19058. this.nCachedObjects_ = nCachedObjects;
  19059. }
  19060. // remove & forget
  19061. uncache() {
  19062. const objects = this._objects,
  19063. indicesByUUID = this._indicesByUUID,
  19064. bindings = this._bindings,
  19065. nBindings = bindings.length;
  19066. let nCachedObjects = this.nCachedObjects_,
  19067. nObjects = objects.length;
  19068. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19069. const object = arguments[ i ],
  19070. uuid = object.uuid,
  19071. index = indicesByUUID[ uuid ];
  19072. if ( index !== undefined ) {
  19073. delete indicesByUUID[ uuid ];
  19074. if ( index < nCachedObjects ) {
  19075. // object is cached, shrink the CACHED region
  19076. const firstActiveIndex = -- nCachedObjects,
  19077. lastCachedObject = objects[ firstActiveIndex ],
  19078. lastIndex = -- nObjects,
  19079. lastObject = objects[ lastIndex ];
  19080. // last cached object takes this object's place
  19081. indicesByUUID[ lastCachedObject.uuid ] = index;
  19082. objects[ index ] = lastCachedObject;
  19083. // last object goes to the activated slot and pop
  19084. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19085. objects[ firstActiveIndex ] = lastObject;
  19086. objects.pop();
  19087. // accounting is done, now do the same for all bindings
  19088. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19089. const bindingsForPath = bindings[ j ],
  19090. lastCached = bindingsForPath[ firstActiveIndex ],
  19091. last = bindingsForPath[ lastIndex ];
  19092. bindingsForPath[ index ] = lastCached;
  19093. bindingsForPath[ firstActiveIndex ] = last;
  19094. bindingsForPath.pop();
  19095. }
  19096. } else {
  19097. // object is active, just swap with the last and pop
  19098. const lastIndex = -- nObjects,
  19099. lastObject = objects[ lastIndex ];
  19100. if ( lastIndex > 0 ) {
  19101. indicesByUUID[ lastObject.uuid ] = index;
  19102. }
  19103. objects[ index ] = lastObject;
  19104. objects.pop();
  19105. // accounting is done, now do the same for all bindings
  19106. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19107. const bindingsForPath = bindings[ j ];
  19108. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19109. bindingsForPath.pop();
  19110. }
  19111. } // cached or active
  19112. } // if object is known
  19113. } // for arguments
  19114. this.nCachedObjects_ = nCachedObjects;
  19115. }
  19116. // Internal interface used by befriended PropertyBinding.Composite:
  19117. subscribe_( path, parsedPath ) {
  19118. // returns an array of bindings for the given path that is changed
  19119. // according to the contained objects in the group
  19120. const indicesByPath = this._bindingsIndicesByPath;
  19121. let index = indicesByPath[ path ];
  19122. const bindings = this._bindings;
  19123. if ( index !== undefined ) return bindings[ index ];
  19124. const paths = this._paths,
  19125. parsedPaths = this._parsedPaths,
  19126. objects = this._objects,
  19127. nObjects = objects.length,
  19128. nCachedObjects = this.nCachedObjects_,
  19129. bindingsForPath = new Array( nObjects );
  19130. index = bindings.length;
  19131. indicesByPath[ path ] = index;
  19132. paths.push( path );
  19133. parsedPaths.push( parsedPath );
  19134. bindings.push( bindingsForPath );
  19135. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19136. const object = objects[ i ];
  19137. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19138. }
  19139. return bindingsForPath;
  19140. }
  19141. unsubscribe_( path ) {
  19142. // tells the group to forget about a property path and no longer
  19143. // update the array previously obtained with 'subscribe_'
  19144. const indicesByPath = this._bindingsIndicesByPath,
  19145. index = indicesByPath[ path ];
  19146. if ( index !== undefined ) {
  19147. const paths = this._paths,
  19148. parsedPaths = this._parsedPaths,
  19149. bindings = this._bindings,
  19150. lastBindingsIndex = bindings.length - 1,
  19151. lastBindings = bindings[ lastBindingsIndex ],
  19152. lastBindingsPath = path[ lastBindingsIndex ];
  19153. indicesByPath[ lastBindingsPath ] = index;
  19154. bindings[ index ] = lastBindings;
  19155. bindings.pop();
  19156. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19157. parsedPaths.pop();
  19158. paths[ index ] = paths[ lastBindingsIndex ];
  19159. paths.pop();
  19160. }
  19161. }
  19162. }
  19163. class AnimationAction {
  19164. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19165. this._mixer = mixer;
  19166. this._clip = clip;
  19167. this._localRoot = localRoot;
  19168. this.blendMode = blendMode;
  19169. const tracks = clip.tracks,
  19170. nTracks = tracks.length,
  19171. interpolants = new Array( nTracks );
  19172. const interpolantSettings = {
  19173. endingStart: ZeroCurvatureEnding,
  19174. endingEnd: ZeroCurvatureEnding
  19175. };
  19176. for ( let i = 0; i !== nTracks; ++ i ) {
  19177. const interpolant = tracks[ i ].createInterpolant( null );
  19178. interpolants[ i ] = interpolant;
  19179. interpolant.settings = interpolantSettings;
  19180. }
  19181. this._interpolantSettings = interpolantSettings;
  19182. this._interpolants = interpolants; // bound by the mixer
  19183. // inside: PropertyMixer (managed by the mixer)
  19184. this._propertyBindings = new Array( nTracks );
  19185. this._cacheIndex = null; // for the memory manager
  19186. this._byClipCacheIndex = null; // for the memory manager
  19187. this._timeScaleInterpolant = null;
  19188. this._weightInterpolant = null;
  19189. this.loop = LoopRepeat;
  19190. this._loopCount = - 1;
  19191. // global mixer time when the action is to be started
  19192. // it's set back to 'null' upon start of the action
  19193. this._startTime = null;
  19194. // scaled local time of the action
  19195. // gets clamped or wrapped to 0..clip.duration according to loop
  19196. this.time = 0;
  19197. this.timeScale = 1;
  19198. this._effectiveTimeScale = 1;
  19199. this.weight = 1;
  19200. this._effectiveWeight = 1;
  19201. this.repetitions = Infinity; // no. of repetitions when looping
  19202. this.paused = false; // true -> zero effective time scale
  19203. this.enabled = true; // false -> zero effective weight
  19204. this.clampWhenFinished = false;// keep feeding the last frame?
  19205. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19206. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19207. }
  19208. // State & Scheduling
  19209. play() {
  19210. this._mixer._activateAction( this );
  19211. return this;
  19212. }
  19213. stop() {
  19214. this._mixer._deactivateAction( this );
  19215. return this.reset();
  19216. }
  19217. reset() {
  19218. this.paused = false;
  19219. this.enabled = true;
  19220. this.time = 0; // restart clip
  19221. this._loopCount = - 1;// forget previous loops
  19222. this._startTime = null;// forget scheduling
  19223. return this.stopFading().stopWarping();
  19224. }
  19225. isRunning() {
  19226. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19227. this._startTime === null && this._mixer._isActiveAction( this );
  19228. }
  19229. // return true when play has been called
  19230. isScheduled() {
  19231. return this._mixer._isActiveAction( this );
  19232. }
  19233. startAt( time ) {
  19234. this._startTime = time;
  19235. return this;
  19236. }
  19237. setLoop( mode, repetitions ) {
  19238. this.loop = mode;
  19239. this.repetitions = repetitions;
  19240. return this;
  19241. }
  19242. // Weight
  19243. // set the weight stopping any scheduled fading
  19244. // although .enabled = false yields an effective weight of zero, this
  19245. // method does *not* change .enabled, because it would be confusing
  19246. setEffectiveWeight( weight ) {
  19247. this.weight = weight;
  19248. // note: same logic as when updated at runtime
  19249. this._effectiveWeight = this.enabled ? weight : 0;
  19250. return this.stopFading();
  19251. }
  19252. // return the weight considering fading and .enabled
  19253. getEffectiveWeight() {
  19254. return this._effectiveWeight;
  19255. }
  19256. fadeIn( duration ) {
  19257. return this._scheduleFading( duration, 0, 1 );
  19258. }
  19259. fadeOut( duration ) {
  19260. return this._scheduleFading( duration, 1, 0 );
  19261. }
  19262. crossFadeFrom( fadeOutAction, duration, warp ) {
  19263. fadeOutAction.fadeOut( duration );
  19264. this.fadeIn( duration );
  19265. if ( warp ) {
  19266. const fadeInDuration = this._clip.duration,
  19267. fadeOutDuration = fadeOutAction._clip.duration,
  19268. startEndRatio = fadeOutDuration / fadeInDuration,
  19269. endStartRatio = fadeInDuration / fadeOutDuration;
  19270. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19271. this.warp( endStartRatio, 1.0, duration );
  19272. }
  19273. return this;
  19274. }
  19275. crossFadeTo( fadeInAction, duration, warp ) {
  19276. return fadeInAction.crossFadeFrom( this, duration, warp );
  19277. }
  19278. stopFading() {
  19279. const weightInterpolant = this._weightInterpolant;
  19280. if ( weightInterpolant !== null ) {
  19281. this._weightInterpolant = null;
  19282. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19283. }
  19284. return this;
  19285. }
  19286. // Time Scale Control
  19287. // set the time scale stopping any scheduled warping
  19288. // although .paused = true yields an effective time scale of zero, this
  19289. // method does *not* change .paused, because it would be confusing
  19290. setEffectiveTimeScale( timeScale ) {
  19291. this.timeScale = timeScale;
  19292. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19293. return this.stopWarping();
  19294. }
  19295. // return the time scale considering warping and .paused
  19296. getEffectiveTimeScale() {
  19297. return this._effectiveTimeScale;
  19298. }
  19299. setDuration( duration ) {
  19300. this.timeScale = this._clip.duration / duration;
  19301. return this.stopWarping();
  19302. }
  19303. syncWith( action ) {
  19304. this.time = action.time;
  19305. this.timeScale = action.timeScale;
  19306. return this.stopWarping();
  19307. }
  19308. halt( duration ) {
  19309. return this.warp( this._effectiveTimeScale, 0, duration );
  19310. }
  19311. warp( startTimeScale, endTimeScale, duration ) {
  19312. const mixer = this._mixer,
  19313. now = mixer.time,
  19314. timeScale = this.timeScale;
  19315. let interpolant = this._timeScaleInterpolant;
  19316. if ( interpolant === null ) {
  19317. interpolant = mixer._lendControlInterpolant();
  19318. this._timeScaleInterpolant = interpolant;
  19319. }
  19320. const times = interpolant.parameterPositions,
  19321. values = interpolant.sampleValues;
  19322. times[ 0 ] = now;
  19323. times[ 1 ] = now + duration;
  19324. values[ 0 ] = startTimeScale / timeScale;
  19325. values[ 1 ] = endTimeScale / timeScale;
  19326. return this;
  19327. }
  19328. stopWarping() {
  19329. const timeScaleInterpolant = this._timeScaleInterpolant;
  19330. if ( timeScaleInterpolant !== null ) {
  19331. this._timeScaleInterpolant = null;
  19332. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19333. }
  19334. return this;
  19335. }
  19336. // Object Accessors
  19337. getMixer() {
  19338. return this._mixer;
  19339. }
  19340. getClip() {
  19341. return this._clip;
  19342. }
  19343. getRoot() {
  19344. return this._localRoot || this._mixer._root;
  19345. }
  19346. // Interna
  19347. _update( time, deltaTime, timeDirection, accuIndex ) {
  19348. // called by the mixer
  19349. if ( ! this.enabled ) {
  19350. // call ._updateWeight() to update ._effectiveWeight
  19351. this._updateWeight( time );
  19352. return;
  19353. }
  19354. const startTime = this._startTime;
  19355. if ( startTime !== null ) {
  19356. // check for scheduled start of action
  19357. const timeRunning = ( time - startTime ) * timeDirection;
  19358. if ( timeRunning < 0 || timeDirection === 0 ) {
  19359. deltaTime = 0;
  19360. } else {
  19361. this._startTime = null; // unschedule
  19362. deltaTime = timeDirection * timeRunning;
  19363. }
  19364. }
  19365. // apply time scale and advance time
  19366. deltaTime *= this._updateTimeScale( time );
  19367. const clipTime = this._updateTime( deltaTime );
  19368. // note: _updateTime may disable the action resulting in
  19369. // an effective weight of 0
  19370. const weight = this._updateWeight( time );
  19371. if ( weight > 0 ) {
  19372. const interpolants = this._interpolants;
  19373. const propertyMixers = this._propertyBindings;
  19374. switch ( this.blendMode ) {
  19375. case AdditiveAnimationBlendMode:
  19376. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19377. interpolants[ j ].evaluate( clipTime );
  19378. propertyMixers[ j ].accumulateAdditive( weight );
  19379. }
  19380. break;
  19381. case NormalAnimationBlendMode:
  19382. default:
  19383. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19384. interpolants[ j ].evaluate( clipTime );
  19385. propertyMixers[ j ].accumulate( accuIndex, weight );
  19386. }
  19387. }
  19388. }
  19389. }
  19390. _updateWeight( time ) {
  19391. let weight = 0;
  19392. if ( this.enabled ) {
  19393. weight = this.weight;
  19394. const interpolant = this._weightInterpolant;
  19395. if ( interpolant !== null ) {
  19396. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19397. weight *= interpolantValue;
  19398. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19399. this.stopFading();
  19400. if ( interpolantValue === 0 ) {
  19401. // faded out, disable
  19402. this.enabled = false;
  19403. }
  19404. }
  19405. }
  19406. }
  19407. this._effectiveWeight = weight;
  19408. return weight;
  19409. }
  19410. _updateTimeScale( time ) {
  19411. let timeScale = 0;
  19412. if ( ! this.paused ) {
  19413. timeScale = this.timeScale;
  19414. const interpolant = this._timeScaleInterpolant;
  19415. if ( interpolant !== null ) {
  19416. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19417. timeScale *= interpolantValue;
  19418. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19419. this.stopWarping();
  19420. if ( timeScale === 0 ) {
  19421. // motion has halted, pause
  19422. this.paused = true;
  19423. } else {
  19424. // warp done - apply final time scale
  19425. this.timeScale = timeScale;
  19426. }
  19427. }
  19428. }
  19429. }
  19430. this._effectiveTimeScale = timeScale;
  19431. return timeScale;
  19432. }
  19433. _updateTime( deltaTime ) {
  19434. const duration = this._clip.duration;
  19435. const loop = this.loop;
  19436. let time = this.time + deltaTime;
  19437. let loopCount = this._loopCount;
  19438. const pingPong = ( loop === LoopPingPong );
  19439. if ( deltaTime === 0 ) {
  19440. if ( loopCount === - 1 ) return time;
  19441. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19442. }
  19443. if ( loop === LoopOnce ) {
  19444. if ( loopCount === - 1 ) {
  19445. // just started
  19446. this._loopCount = 0;
  19447. this._setEndings( true, true, false );
  19448. }
  19449. handle_stop: {
  19450. if ( time >= duration ) {
  19451. time = duration;
  19452. } else if ( time < 0 ) {
  19453. time = 0;
  19454. } else {
  19455. this.time = time;
  19456. break handle_stop;
  19457. }
  19458. if ( this.clampWhenFinished ) this.paused = true;
  19459. else this.enabled = false;
  19460. this.time = time;
  19461. this._mixer.dispatchEvent( {
  19462. type: 'finished', action: this,
  19463. direction: deltaTime < 0 ? - 1 : 1
  19464. } );
  19465. }
  19466. } else { // repetitive Repeat or PingPong
  19467. if ( loopCount === - 1 ) {
  19468. // just started
  19469. if ( deltaTime >= 0 ) {
  19470. loopCount = 0;
  19471. this._setEndings( true, this.repetitions === 0, pingPong );
  19472. } else {
  19473. // when looping in reverse direction, the initial
  19474. // transition through zero counts as a repetition,
  19475. // so leave loopCount at -1
  19476. this._setEndings( this.repetitions === 0, true, pingPong );
  19477. }
  19478. }
  19479. if ( time >= duration || time < 0 ) {
  19480. // wrap around
  19481. const loopDelta = Math.floor( time / duration ); // signed
  19482. time -= duration * loopDelta;
  19483. loopCount += Math.abs( loopDelta );
  19484. const pending = this.repetitions - loopCount;
  19485. if ( pending <= 0 ) {
  19486. // have to stop (switch state, clamp time, fire event)
  19487. if ( this.clampWhenFinished ) this.paused = true;
  19488. else this.enabled = false;
  19489. time = deltaTime > 0 ? duration : 0;
  19490. this.time = time;
  19491. this._mixer.dispatchEvent( {
  19492. type: 'finished', action: this,
  19493. direction: deltaTime > 0 ? 1 : - 1
  19494. } );
  19495. } else {
  19496. // keep running
  19497. if ( pending === 1 ) {
  19498. // entering the last round
  19499. const atStart = deltaTime < 0;
  19500. this._setEndings( atStart, ! atStart, pingPong );
  19501. } else {
  19502. this._setEndings( false, false, pingPong );
  19503. }
  19504. this._loopCount = loopCount;
  19505. this.time = time;
  19506. this._mixer.dispatchEvent( {
  19507. type: 'loop', action: this, loopDelta: loopDelta
  19508. } );
  19509. }
  19510. } else {
  19511. this.time = time;
  19512. }
  19513. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19514. // invert time for the "pong round"
  19515. return duration - time;
  19516. }
  19517. }
  19518. return time;
  19519. }
  19520. _setEndings( atStart, atEnd, pingPong ) {
  19521. const settings = this._interpolantSettings;
  19522. if ( pingPong ) {
  19523. settings.endingStart = ZeroSlopeEnding;
  19524. settings.endingEnd = ZeroSlopeEnding;
  19525. } else {
  19526. // assuming for LoopOnce atStart == atEnd == true
  19527. if ( atStart ) {
  19528. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19529. } else {
  19530. settings.endingStart = WrapAroundEnding;
  19531. }
  19532. if ( atEnd ) {
  19533. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19534. } else {
  19535. settings.endingEnd = WrapAroundEnding;
  19536. }
  19537. }
  19538. }
  19539. _scheduleFading( duration, weightNow, weightThen ) {
  19540. const mixer = this._mixer, now = mixer.time;
  19541. let interpolant = this._weightInterpolant;
  19542. if ( interpolant === null ) {
  19543. interpolant = mixer._lendControlInterpolant();
  19544. this._weightInterpolant = interpolant;
  19545. }
  19546. const times = interpolant.parameterPositions,
  19547. values = interpolant.sampleValues;
  19548. times[ 0 ] = now;
  19549. values[ 0 ] = weightNow;
  19550. times[ 1 ] = now + duration;
  19551. values[ 1 ] = weightThen;
  19552. return this;
  19553. }
  19554. }
  19555. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19556. class AnimationMixer extends EventDispatcher {
  19557. constructor( root ) {
  19558. super();
  19559. this._root = root;
  19560. this._initMemoryManager();
  19561. this._accuIndex = 0;
  19562. this.time = 0;
  19563. this.timeScale = 1.0;
  19564. }
  19565. _bindAction( action, prototypeAction ) {
  19566. const root = action._localRoot || this._root,
  19567. tracks = action._clip.tracks,
  19568. nTracks = tracks.length,
  19569. bindings = action._propertyBindings,
  19570. interpolants = action._interpolants,
  19571. rootUuid = root.uuid,
  19572. bindingsByRoot = this._bindingsByRootAndName;
  19573. let bindingsByName = bindingsByRoot[ rootUuid ];
  19574. if ( bindingsByName === undefined ) {
  19575. bindingsByName = {};
  19576. bindingsByRoot[ rootUuid ] = bindingsByName;
  19577. }
  19578. for ( let i = 0; i !== nTracks; ++ i ) {
  19579. const track = tracks[ i ],
  19580. trackName = track.name;
  19581. let binding = bindingsByName[ trackName ];
  19582. if ( binding !== undefined ) {
  19583. ++ binding.referenceCount;
  19584. bindings[ i ] = binding;
  19585. } else {
  19586. binding = bindings[ i ];
  19587. if ( binding !== undefined ) {
  19588. // existing binding, make sure the cache knows
  19589. if ( binding._cacheIndex === null ) {
  19590. ++ binding.referenceCount;
  19591. this._addInactiveBinding( binding, rootUuid, trackName );
  19592. }
  19593. continue;
  19594. }
  19595. const path = prototypeAction && prototypeAction.
  19596. _propertyBindings[ i ].binding.parsedPath;
  19597. binding = new PropertyMixer(
  19598. PropertyBinding.create( root, trackName, path ),
  19599. track.ValueTypeName, track.getValueSize() );
  19600. ++ binding.referenceCount;
  19601. this._addInactiveBinding( binding, rootUuid, trackName );
  19602. bindings[ i ] = binding;
  19603. }
  19604. interpolants[ i ].resultBuffer = binding.buffer;
  19605. }
  19606. }
  19607. _activateAction( action ) {
  19608. if ( ! this._isActiveAction( action ) ) {
  19609. if ( action._cacheIndex === null ) {
  19610. // this action has been forgotten by the cache, but the user
  19611. // appears to be still using it -> rebind
  19612. const rootUuid = ( action._localRoot || this._root ).uuid,
  19613. clipUuid = action._clip.uuid,
  19614. actionsForClip = this._actionsByClip[ clipUuid ];
  19615. this._bindAction( action,
  19616. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19617. this._addInactiveAction( action, clipUuid, rootUuid );
  19618. }
  19619. const bindings = action._propertyBindings;
  19620. // increment reference counts / sort out state
  19621. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19622. const binding = bindings[ i ];
  19623. if ( binding.useCount ++ === 0 ) {
  19624. this._lendBinding( binding );
  19625. binding.saveOriginalState();
  19626. }
  19627. }
  19628. this._lendAction( action );
  19629. }
  19630. }
  19631. _deactivateAction( action ) {
  19632. if ( this._isActiveAction( action ) ) {
  19633. const bindings = action._propertyBindings;
  19634. // decrement reference counts / sort out state
  19635. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19636. const binding = bindings[ i ];
  19637. if ( -- binding.useCount === 0 ) {
  19638. binding.restoreOriginalState();
  19639. this._takeBackBinding( binding );
  19640. }
  19641. }
  19642. this._takeBackAction( action );
  19643. }
  19644. }
  19645. // Memory manager
  19646. _initMemoryManager() {
  19647. this._actions = []; // 'nActiveActions' followed by inactive ones
  19648. this._nActiveActions = 0;
  19649. this._actionsByClip = {};
  19650. // inside:
  19651. // {
  19652. // knownActions: Array< AnimationAction > - used as prototypes
  19653. // actionByRoot: AnimationAction - lookup
  19654. // }
  19655. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19656. this._nActiveBindings = 0;
  19657. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19658. this._controlInterpolants = []; // same game as above
  19659. this._nActiveControlInterpolants = 0;
  19660. const scope = this;
  19661. this.stats = {
  19662. actions: {
  19663. get total() {
  19664. return scope._actions.length;
  19665. },
  19666. get inUse() {
  19667. return scope._nActiveActions;
  19668. }
  19669. },
  19670. bindings: {
  19671. get total() {
  19672. return scope._bindings.length;
  19673. },
  19674. get inUse() {
  19675. return scope._nActiveBindings;
  19676. }
  19677. },
  19678. controlInterpolants: {
  19679. get total() {
  19680. return scope._controlInterpolants.length;
  19681. },
  19682. get inUse() {
  19683. return scope._nActiveControlInterpolants;
  19684. }
  19685. }
  19686. };
  19687. }
  19688. // Memory management for AnimationAction objects
  19689. _isActiveAction( action ) {
  19690. const index = action._cacheIndex;
  19691. return index !== null && index < this._nActiveActions;
  19692. }
  19693. _addInactiveAction( action, clipUuid, rootUuid ) {
  19694. const actions = this._actions,
  19695. actionsByClip = this._actionsByClip;
  19696. let actionsForClip = actionsByClip[ clipUuid ];
  19697. if ( actionsForClip === undefined ) {
  19698. actionsForClip = {
  19699. knownActions: [ action ],
  19700. actionByRoot: {}
  19701. };
  19702. action._byClipCacheIndex = 0;
  19703. actionsByClip[ clipUuid ] = actionsForClip;
  19704. } else {
  19705. const knownActions = actionsForClip.knownActions;
  19706. action._byClipCacheIndex = knownActions.length;
  19707. knownActions.push( action );
  19708. }
  19709. action._cacheIndex = actions.length;
  19710. actions.push( action );
  19711. actionsForClip.actionByRoot[ rootUuid ] = action;
  19712. }
  19713. _removeInactiveAction( action ) {
  19714. const actions = this._actions,
  19715. lastInactiveAction = actions[ actions.length - 1 ],
  19716. cacheIndex = action._cacheIndex;
  19717. lastInactiveAction._cacheIndex = cacheIndex;
  19718. actions[ cacheIndex ] = lastInactiveAction;
  19719. actions.pop();
  19720. action._cacheIndex = null;
  19721. const clipUuid = action._clip.uuid,
  19722. actionsByClip = this._actionsByClip,
  19723. actionsForClip = actionsByClip[ clipUuid ],
  19724. knownActionsForClip = actionsForClip.knownActions,
  19725. lastKnownAction =
  19726. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19727. byClipCacheIndex = action._byClipCacheIndex;
  19728. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19729. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19730. knownActionsForClip.pop();
  19731. action._byClipCacheIndex = null;
  19732. const actionByRoot = actionsForClip.actionByRoot,
  19733. rootUuid = ( action._localRoot || this._root ).uuid;
  19734. delete actionByRoot[ rootUuid ];
  19735. if ( knownActionsForClip.length === 0 ) {
  19736. delete actionsByClip[ clipUuid ];
  19737. }
  19738. this._removeInactiveBindingsForAction( action );
  19739. }
  19740. _removeInactiveBindingsForAction( action ) {
  19741. const bindings = action._propertyBindings;
  19742. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19743. const binding = bindings[ i ];
  19744. if ( -- binding.referenceCount === 0 ) {
  19745. this._removeInactiveBinding( binding );
  19746. }
  19747. }
  19748. }
  19749. _lendAction( action ) {
  19750. // [ active actions | inactive actions ]
  19751. // [ active actions >| inactive actions ]
  19752. // s a
  19753. // <-swap->
  19754. // a s
  19755. const actions = this._actions,
  19756. prevIndex = action._cacheIndex,
  19757. lastActiveIndex = this._nActiveActions ++,
  19758. firstInactiveAction = actions[ lastActiveIndex ];
  19759. action._cacheIndex = lastActiveIndex;
  19760. actions[ lastActiveIndex ] = action;
  19761. firstInactiveAction._cacheIndex = prevIndex;
  19762. actions[ prevIndex ] = firstInactiveAction;
  19763. }
  19764. _takeBackAction( action ) {
  19765. // [ active actions | inactive actions ]
  19766. // [ active actions |< inactive actions ]
  19767. // a s
  19768. // <-swap->
  19769. // s a
  19770. const actions = this._actions,
  19771. prevIndex = action._cacheIndex,
  19772. firstInactiveIndex = -- this._nActiveActions,
  19773. lastActiveAction = actions[ firstInactiveIndex ];
  19774. action._cacheIndex = firstInactiveIndex;
  19775. actions[ firstInactiveIndex ] = action;
  19776. lastActiveAction._cacheIndex = prevIndex;
  19777. actions[ prevIndex ] = lastActiveAction;
  19778. }
  19779. // Memory management for PropertyMixer objects
  19780. _addInactiveBinding( binding, rootUuid, trackName ) {
  19781. const bindingsByRoot = this._bindingsByRootAndName,
  19782. bindings = this._bindings;
  19783. let bindingByName = bindingsByRoot[ rootUuid ];
  19784. if ( bindingByName === undefined ) {
  19785. bindingByName = {};
  19786. bindingsByRoot[ rootUuid ] = bindingByName;
  19787. }
  19788. bindingByName[ trackName ] = binding;
  19789. binding._cacheIndex = bindings.length;
  19790. bindings.push( binding );
  19791. }
  19792. _removeInactiveBinding( binding ) {
  19793. const bindings = this._bindings,
  19794. propBinding = binding.binding,
  19795. rootUuid = propBinding.rootNode.uuid,
  19796. trackName = propBinding.path,
  19797. bindingsByRoot = this._bindingsByRootAndName,
  19798. bindingByName = bindingsByRoot[ rootUuid ],
  19799. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19800. cacheIndex = binding._cacheIndex;
  19801. lastInactiveBinding._cacheIndex = cacheIndex;
  19802. bindings[ cacheIndex ] = lastInactiveBinding;
  19803. bindings.pop();
  19804. delete bindingByName[ trackName ];
  19805. if ( Object.keys( bindingByName ).length === 0 ) {
  19806. delete bindingsByRoot[ rootUuid ];
  19807. }
  19808. }
  19809. _lendBinding( binding ) {
  19810. const bindings = this._bindings,
  19811. prevIndex = binding._cacheIndex,
  19812. lastActiveIndex = this._nActiveBindings ++,
  19813. firstInactiveBinding = bindings[ lastActiveIndex ];
  19814. binding._cacheIndex = lastActiveIndex;
  19815. bindings[ lastActiveIndex ] = binding;
  19816. firstInactiveBinding._cacheIndex = prevIndex;
  19817. bindings[ prevIndex ] = firstInactiveBinding;
  19818. }
  19819. _takeBackBinding( binding ) {
  19820. const bindings = this._bindings,
  19821. prevIndex = binding._cacheIndex,
  19822. firstInactiveIndex = -- this._nActiveBindings,
  19823. lastActiveBinding = bindings[ firstInactiveIndex ];
  19824. binding._cacheIndex = firstInactiveIndex;
  19825. bindings[ firstInactiveIndex ] = binding;
  19826. lastActiveBinding._cacheIndex = prevIndex;
  19827. bindings[ prevIndex ] = lastActiveBinding;
  19828. }
  19829. // Memory management of Interpolants for weight and time scale
  19830. _lendControlInterpolant() {
  19831. const interpolants = this._controlInterpolants,
  19832. lastActiveIndex = this._nActiveControlInterpolants ++;
  19833. let interpolant = interpolants[ lastActiveIndex ];
  19834. if ( interpolant === undefined ) {
  19835. interpolant = new LinearInterpolant(
  19836. new Float32Array( 2 ), new Float32Array( 2 ),
  19837. 1, _controlInterpolantsResultBuffer );
  19838. interpolant.__cacheIndex = lastActiveIndex;
  19839. interpolants[ lastActiveIndex ] = interpolant;
  19840. }
  19841. return interpolant;
  19842. }
  19843. _takeBackControlInterpolant( interpolant ) {
  19844. const interpolants = this._controlInterpolants,
  19845. prevIndex = interpolant.__cacheIndex,
  19846. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19847. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19848. interpolant.__cacheIndex = firstInactiveIndex;
  19849. interpolants[ firstInactiveIndex ] = interpolant;
  19850. lastActiveInterpolant.__cacheIndex = prevIndex;
  19851. interpolants[ prevIndex ] = lastActiveInterpolant;
  19852. }
  19853. // return an action for a clip optionally using a custom root target
  19854. // object (this method allocates a lot of dynamic memory in case a
  19855. // previously unknown clip/root combination is specified)
  19856. clipAction( clip, optionalRoot, blendMode ) {
  19857. const root = optionalRoot || this._root,
  19858. rootUuid = root.uuid;
  19859. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19860. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19861. const actionsForClip = this._actionsByClip[ clipUuid ];
  19862. let prototypeAction = null;
  19863. if ( blendMode === undefined ) {
  19864. if ( clipObject !== null ) {
  19865. blendMode = clipObject.blendMode;
  19866. } else {
  19867. blendMode = NormalAnimationBlendMode;
  19868. }
  19869. }
  19870. if ( actionsForClip !== undefined ) {
  19871. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19872. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19873. return existingAction;
  19874. }
  19875. // we know the clip, so we don't have to parse all
  19876. // the bindings again but can just copy
  19877. prototypeAction = actionsForClip.knownActions[ 0 ];
  19878. // also, take the clip from the prototype action
  19879. if ( clipObject === null )
  19880. clipObject = prototypeAction._clip;
  19881. }
  19882. // clip must be known when specified via string
  19883. if ( clipObject === null ) return null;
  19884. // allocate all resources required to run it
  19885. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19886. this._bindAction( newAction, prototypeAction );
  19887. // and make the action known to the memory manager
  19888. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19889. return newAction;
  19890. }
  19891. // get an existing action
  19892. existingAction( clip, optionalRoot ) {
  19893. const root = optionalRoot || this._root,
  19894. rootUuid = root.uuid,
  19895. clipObject = typeof clip === 'string' ?
  19896. AnimationClip.findByName( root, clip ) : clip,
  19897. clipUuid = clipObject ? clipObject.uuid : clip,
  19898. actionsForClip = this._actionsByClip[ clipUuid ];
  19899. if ( actionsForClip !== undefined ) {
  19900. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19901. }
  19902. return null;
  19903. }
  19904. // deactivates all previously scheduled actions
  19905. stopAllAction() {
  19906. const actions = this._actions,
  19907. nActions = this._nActiveActions;
  19908. for ( let i = nActions - 1; i >= 0; -- i ) {
  19909. actions[ i ].stop();
  19910. }
  19911. return this;
  19912. }
  19913. // advance the time and update apply the animation
  19914. update( deltaTime ) {
  19915. deltaTime *= this.timeScale;
  19916. const actions = this._actions,
  19917. nActions = this._nActiveActions,
  19918. time = this.time += deltaTime,
  19919. timeDirection = Math.sign( deltaTime ),
  19920. accuIndex = this._accuIndex ^= 1;
  19921. // run active actions
  19922. for ( let i = 0; i !== nActions; ++ i ) {
  19923. const action = actions[ i ];
  19924. action._update( time, deltaTime, timeDirection, accuIndex );
  19925. }
  19926. // update scene graph
  19927. const bindings = this._bindings,
  19928. nBindings = this._nActiveBindings;
  19929. for ( let i = 0; i !== nBindings; ++ i ) {
  19930. bindings[ i ].apply( accuIndex );
  19931. }
  19932. return this;
  19933. }
  19934. // Allows you to seek to a specific time in an animation.
  19935. setTime( timeInSeconds ) {
  19936. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19937. for ( let i = 0; i < this._actions.length; i ++ ) {
  19938. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19939. }
  19940. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19941. }
  19942. // return this mixer's root target object
  19943. getRoot() {
  19944. return this._root;
  19945. }
  19946. // free all resources specific to a particular clip
  19947. uncacheClip( clip ) {
  19948. const actions = this._actions,
  19949. clipUuid = clip.uuid,
  19950. actionsByClip = this._actionsByClip,
  19951. actionsForClip = actionsByClip[ clipUuid ];
  19952. if ( actionsForClip !== undefined ) {
  19953. // note: just calling _removeInactiveAction would mess up the
  19954. // iteration state and also require updating the state we can
  19955. // just throw away
  19956. const actionsToRemove = actionsForClip.knownActions;
  19957. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19958. const action = actionsToRemove[ i ];
  19959. this._deactivateAction( action );
  19960. const cacheIndex = action._cacheIndex,
  19961. lastInactiveAction = actions[ actions.length - 1 ];
  19962. action._cacheIndex = null;
  19963. action._byClipCacheIndex = null;
  19964. lastInactiveAction._cacheIndex = cacheIndex;
  19965. actions[ cacheIndex ] = lastInactiveAction;
  19966. actions.pop();
  19967. this._removeInactiveBindingsForAction( action );
  19968. }
  19969. delete actionsByClip[ clipUuid ];
  19970. }
  19971. }
  19972. // free all resources specific to a particular root target object
  19973. uncacheRoot( root ) {
  19974. const rootUuid = root.uuid,
  19975. actionsByClip = this._actionsByClip;
  19976. for ( const clipUuid in actionsByClip ) {
  19977. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19978. action = actionByRoot[ rootUuid ];
  19979. if ( action !== undefined ) {
  19980. this._deactivateAction( action );
  19981. this._removeInactiveAction( action );
  19982. }
  19983. }
  19984. const bindingsByRoot = this._bindingsByRootAndName,
  19985. bindingByName = bindingsByRoot[ rootUuid ];
  19986. if ( bindingByName !== undefined ) {
  19987. for ( const trackName in bindingByName ) {
  19988. const binding = bindingByName[ trackName ];
  19989. binding.restoreOriginalState();
  19990. this._removeInactiveBinding( binding );
  19991. }
  19992. }
  19993. }
  19994. // remove a targeted clip from the cache
  19995. uncacheAction( clip, optionalRoot ) {
  19996. const action = this.existingAction( clip, optionalRoot );
  19997. if ( action !== null ) {
  19998. this._deactivateAction( action );
  19999. this._removeInactiveAction( action );
  20000. }
  20001. }
  20002. }
  20003. let Uniform$1 = class Uniform {
  20004. constructor( value ) {
  20005. this.value = value;
  20006. }
  20007. clone() {
  20008. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20009. }
  20010. };
  20011. let _id$8 = 0;
  20012. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  20013. constructor() {
  20014. super();
  20015. this.isUniformsGroup = true;
  20016. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  20017. this.name = '';
  20018. this.usage = StaticDrawUsage;
  20019. this.uniforms = [];
  20020. }
  20021. add( uniform ) {
  20022. this.uniforms.push( uniform );
  20023. return this;
  20024. }
  20025. remove( uniform ) {
  20026. const index = this.uniforms.indexOf( uniform );
  20027. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20028. return this;
  20029. }
  20030. setName( name ) {
  20031. this.name = name;
  20032. return this;
  20033. }
  20034. setUsage( value ) {
  20035. this.usage = value;
  20036. return this;
  20037. }
  20038. dispose() {
  20039. this.dispatchEvent( { type: 'dispose' } );
  20040. return this;
  20041. }
  20042. copy( source ) {
  20043. this.name = source.name;
  20044. this.usage = source.usage;
  20045. const uniformsSource = source.uniforms;
  20046. this.uniforms.length = 0;
  20047. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20048. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20049. for ( let j = 0; j < uniforms.length; j ++ ) {
  20050. this.uniforms.push( uniforms[ j ].clone() );
  20051. }
  20052. }
  20053. return this;
  20054. }
  20055. clone() {
  20056. return new this.constructor().copy( this );
  20057. }
  20058. };
  20059. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20060. constructor( array, stride, meshPerAttribute = 1 ) {
  20061. super( array, stride );
  20062. this.isInstancedInterleavedBuffer = true;
  20063. this.meshPerAttribute = meshPerAttribute;
  20064. }
  20065. copy( source ) {
  20066. super.copy( source );
  20067. this.meshPerAttribute = source.meshPerAttribute;
  20068. return this;
  20069. }
  20070. clone( data ) {
  20071. const ib = super.clone( data );
  20072. ib.meshPerAttribute = this.meshPerAttribute;
  20073. return ib;
  20074. }
  20075. toJSON( data ) {
  20076. const json = super.toJSON( data );
  20077. json.isInstancedInterleavedBuffer = true;
  20078. json.meshPerAttribute = this.meshPerAttribute;
  20079. return json;
  20080. }
  20081. }
  20082. class GLBufferAttribute {
  20083. constructor( buffer, type, itemSize, elementSize, count ) {
  20084. this.isGLBufferAttribute = true;
  20085. this.name = '';
  20086. this.buffer = buffer;
  20087. this.type = type;
  20088. this.itemSize = itemSize;
  20089. this.elementSize = elementSize;
  20090. this.count = count;
  20091. this.version = 0;
  20092. }
  20093. set needsUpdate( value ) {
  20094. if ( value === true ) this.version ++;
  20095. }
  20096. setBuffer( buffer ) {
  20097. this.buffer = buffer;
  20098. return this;
  20099. }
  20100. setType( type, elementSize ) {
  20101. this.type = type;
  20102. this.elementSize = elementSize;
  20103. return this;
  20104. }
  20105. setItemSize( itemSize ) {
  20106. this.itemSize = itemSize;
  20107. return this;
  20108. }
  20109. setCount( count ) {
  20110. this.count = count;
  20111. return this;
  20112. }
  20113. }
  20114. const _matrix = /*@__PURE__*/ new Matrix4();
  20115. class Raycaster {
  20116. constructor( origin, direction, near = 0, far = Infinity ) {
  20117. this.ray = new Ray( origin, direction );
  20118. // direction is assumed to be normalized (for accurate distance calculations)
  20119. this.near = near;
  20120. this.far = far;
  20121. this.camera = null;
  20122. this.layers = new Layers();
  20123. this.params = {
  20124. Mesh: {},
  20125. Line: { threshold: 1 },
  20126. LOD: {},
  20127. Points: { threshold: 1 },
  20128. Sprite: {}
  20129. };
  20130. }
  20131. set( origin, direction ) {
  20132. // direction is assumed to be normalized (for accurate distance calculations)
  20133. this.ray.set( origin, direction );
  20134. }
  20135. setFromCamera( coords, camera ) {
  20136. if ( camera.isPerspectiveCamera ) {
  20137. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20138. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20139. this.camera = camera;
  20140. } else if ( camera.isOrthographicCamera ) {
  20141. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20142. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20143. this.camera = camera;
  20144. } else {
  20145. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20146. }
  20147. }
  20148. setFromXRController( controller ) {
  20149. _matrix.identity().extractRotation( controller.matrixWorld );
  20150. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20151. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20152. return this;
  20153. }
  20154. intersectObject( object, recursive = true, intersects = [] ) {
  20155. intersect( object, this, intersects, recursive );
  20156. intersects.sort( ascSort );
  20157. return intersects;
  20158. }
  20159. intersectObjects( objects, recursive = true, intersects = [] ) {
  20160. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20161. intersect( objects[ i ], this, intersects, recursive );
  20162. }
  20163. intersects.sort( ascSort );
  20164. return intersects;
  20165. }
  20166. }
  20167. function ascSort( a, b ) {
  20168. return a.distance - b.distance;
  20169. }
  20170. function intersect( object, raycaster, intersects, recursive ) {
  20171. let propagate = true;
  20172. if ( object.layers.test( raycaster.layers ) ) {
  20173. const result = object.raycast( raycaster, intersects );
  20174. if ( result === false ) propagate = false;
  20175. }
  20176. if ( propagate === true && recursive === true ) {
  20177. const children = object.children;
  20178. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20179. intersect( children[ i ], raycaster, intersects, true );
  20180. }
  20181. }
  20182. }
  20183. /**
  20184. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20185. *
  20186. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20187. * theta (the azimuthal angle) is measured from the positive z-axis.
  20188. */
  20189. class Spherical {
  20190. constructor( radius = 1, phi = 0, theta = 0 ) {
  20191. this.radius = radius;
  20192. this.phi = phi; // polar angle
  20193. this.theta = theta; // azimuthal angle
  20194. return this;
  20195. }
  20196. set( radius, phi, theta ) {
  20197. this.radius = radius;
  20198. this.phi = phi;
  20199. this.theta = theta;
  20200. return this;
  20201. }
  20202. copy( other ) {
  20203. this.radius = other.radius;
  20204. this.phi = other.phi;
  20205. this.theta = other.theta;
  20206. return this;
  20207. }
  20208. // restrict phi to be between EPS and PI-EPS
  20209. makeSafe() {
  20210. const EPS = 0.000001;
  20211. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20212. return this;
  20213. }
  20214. setFromVector3( v ) {
  20215. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20216. }
  20217. setFromCartesianCoords( x, y, z ) {
  20218. this.radius = Math.sqrt( x * x + y * y + z * z );
  20219. if ( this.radius === 0 ) {
  20220. this.theta = 0;
  20221. this.phi = 0;
  20222. } else {
  20223. this.theta = Math.atan2( x, z );
  20224. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20225. }
  20226. return this;
  20227. }
  20228. clone() {
  20229. return new this.constructor().copy( this );
  20230. }
  20231. }
  20232. /**
  20233. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20234. */
  20235. class Cylindrical {
  20236. constructor( radius = 1, theta = 0, y = 0 ) {
  20237. this.radius = radius; // distance from the origin to a point in the x-z plane
  20238. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20239. this.y = y; // height above the x-z plane
  20240. return this;
  20241. }
  20242. set( radius, theta, y ) {
  20243. this.radius = radius;
  20244. this.theta = theta;
  20245. this.y = y;
  20246. return this;
  20247. }
  20248. copy( other ) {
  20249. this.radius = other.radius;
  20250. this.theta = other.theta;
  20251. this.y = other.y;
  20252. return this;
  20253. }
  20254. setFromVector3( v ) {
  20255. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20256. }
  20257. setFromCartesianCoords( x, y, z ) {
  20258. this.radius = Math.sqrt( x * x + z * z );
  20259. this.theta = Math.atan2( x, z );
  20260. this.y = y;
  20261. return this;
  20262. }
  20263. clone() {
  20264. return new this.constructor().copy( this );
  20265. }
  20266. }
  20267. class Matrix2 {
  20268. constructor( n11, n12, n21, n22 ) {
  20269. Matrix2.prototype.isMatrix2 = true;
  20270. this.elements = [
  20271. 1, 0,
  20272. 0, 1,
  20273. ];
  20274. if ( n11 !== undefined ) {
  20275. this.set( n11, n12, n21, n22 );
  20276. }
  20277. }
  20278. identity() {
  20279. this.set(
  20280. 1, 0,
  20281. 0, 1,
  20282. );
  20283. return this;
  20284. }
  20285. fromArray( array, offset = 0 ) {
  20286. for ( let i = 0; i < 4; i ++ ) {
  20287. this.elements[ i ] = array[ i + offset ];
  20288. }
  20289. return this;
  20290. }
  20291. set( n11, n12, n21, n22 ) {
  20292. const te = this.elements;
  20293. te[ 0 ] = n11; te[ 2 ] = n12;
  20294. te[ 1 ] = n21; te[ 3 ] = n22;
  20295. return this;
  20296. }
  20297. }
  20298. const _vector$4 = /*@__PURE__*/ new Vector2();
  20299. class Box2 {
  20300. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20301. this.isBox2 = true;
  20302. this.min = min;
  20303. this.max = max;
  20304. }
  20305. set( min, max ) {
  20306. this.min.copy( min );
  20307. this.max.copy( max );
  20308. return this;
  20309. }
  20310. setFromPoints( points ) {
  20311. this.makeEmpty();
  20312. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20313. this.expandByPoint( points[ i ] );
  20314. }
  20315. return this;
  20316. }
  20317. setFromCenterAndSize( center, size ) {
  20318. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20319. this.min.copy( center ).sub( halfSize );
  20320. this.max.copy( center ).add( halfSize );
  20321. return this;
  20322. }
  20323. clone() {
  20324. return new this.constructor().copy( this );
  20325. }
  20326. copy( box ) {
  20327. this.min.copy( box.min );
  20328. this.max.copy( box.max );
  20329. return this;
  20330. }
  20331. makeEmpty() {
  20332. this.min.x = this.min.y = + Infinity;
  20333. this.max.x = this.max.y = - Infinity;
  20334. return this;
  20335. }
  20336. isEmpty() {
  20337. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20338. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20339. }
  20340. getCenter( target ) {
  20341. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20342. }
  20343. getSize( target ) {
  20344. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20345. }
  20346. expandByPoint( point ) {
  20347. this.min.min( point );
  20348. this.max.max( point );
  20349. return this;
  20350. }
  20351. expandByVector( vector ) {
  20352. this.min.sub( vector );
  20353. this.max.add( vector );
  20354. return this;
  20355. }
  20356. expandByScalar( scalar ) {
  20357. this.min.addScalar( - scalar );
  20358. this.max.addScalar( scalar );
  20359. return this;
  20360. }
  20361. containsPoint( point ) {
  20362. return point.x >= this.min.x && point.x <= this.max.x &&
  20363. point.y >= this.min.y && point.y <= this.max.y;
  20364. }
  20365. containsBox( box ) {
  20366. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20367. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20368. }
  20369. getParameter( point, target ) {
  20370. // This can potentially have a divide by zero if the box
  20371. // has a size dimension of 0.
  20372. return target.set(
  20373. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20374. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20375. );
  20376. }
  20377. intersectsBox( box ) {
  20378. // using 4 splitting planes to rule out intersections
  20379. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20380. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20381. }
  20382. clampPoint( point, target ) {
  20383. return target.copy( point ).clamp( this.min, this.max );
  20384. }
  20385. distanceToPoint( point ) {
  20386. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20387. }
  20388. intersect( box ) {
  20389. this.min.max( box.min );
  20390. this.max.min( box.max );
  20391. if ( this.isEmpty() ) this.makeEmpty();
  20392. return this;
  20393. }
  20394. union( box ) {
  20395. this.min.min( box.min );
  20396. this.max.max( box.max );
  20397. return this;
  20398. }
  20399. translate( offset ) {
  20400. this.min.add( offset );
  20401. this.max.add( offset );
  20402. return this;
  20403. }
  20404. equals( box ) {
  20405. return box.min.equals( this.min ) && box.max.equals( this.max );
  20406. }
  20407. }
  20408. const _startP = /*@__PURE__*/ new Vector3();
  20409. const _startEnd = /*@__PURE__*/ new Vector3();
  20410. class Line3 {
  20411. constructor( start = new Vector3(), end = new Vector3() ) {
  20412. this.start = start;
  20413. this.end = end;
  20414. }
  20415. set( start, end ) {
  20416. this.start.copy( start );
  20417. this.end.copy( end );
  20418. return this;
  20419. }
  20420. copy( line ) {
  20421. this.start.copy( line.start );
  20422. this.end.copy( line.end );
  20423. return this;
  20424. }
  20425. getCenter( target ) {
  20426. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20427. }
  20428. delta( target ) {
  20429. return target.subVectors( this.end, this.start );
  20430. }
  20431. distanceSq() {
  20432. return this.start.distanceToSquared( this.end );
  20433. }
  20434. distance() {
  20435. return this.start.distanceTo( this.end );
  20436. }
  20437. at( t, target ) {
  20438. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20439. }
  20440. closestPointToPointParameter( point, clampToLine ) {
  20441. _startP.subVectors( point, this.start );
  20442. _startEnd.subVectors( this.end, this.start );
  20443. const startEnd2 = _startEnd.dot( _startEnd );
  20444. const startEnd_startP = _startEnd.dot( _startP );
  20445. let t = startEnd_startP / startEnd2;
  20446. if ( clampToLine ) {
  20447. t = clamp$1( t, 0, 1 );
  20448. }
  20449. return t;
  20450. }
  20451. closestPointToPoint( point, clampToLine, target ) {
  20452. const t = this.closestPointToPointParameter( point, clampToLine );
  20453. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20454. }
  20455. applyMatrix4( matrix ) {
  20456. this.start.applyMatrix4( matrix );
  20457. this.end.applyMatrix4( matrix );
  20458. return this;
  20459. }
  20460. equals( line ) {
  20461. return line.start.equals( this.start ) && line.end.equals( this.end );
  20462. }
  20463. clone() {
  20464. return new this.constructor().copy( this );
  20465. }
  20466. }
  20467. const _vector$3 = /*@__PURE__*/ new Vector3();
  20468. class SpotLightHelper extends Object3D {
  20469. constructor( light, color ) {
  20470. super();
  20471. this.light = light;
  20472. this.matrixAutoUpdate = false;
  20473. this.color = color;
  20474. this.type = 'SpotLightHelper';
  20475. const geometry = new BufferGeometry();
  20476. const positions = [
  20477. 0, 0, 0, 0, 0, 1,
  20478. 0, 0, 0, 1, 0, 1,
  20479. 0, 0, 0, - 1, 0, 1,
  20480. 0, 0, 0, 0, 1, 1,
  20481. 0, 0, 0, 0, - 1, 1
  20482. ];
  20483. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20484. const p1 = ( i / l ) * Math.PI * 2;
  20485. const p2 = ( j / l ) * Math.PI * 2;
  20486. positions.push(
  20487. Math.cos( p1 ), Math.sin( p1 ), 1,
  20488. Math.cos( p2 ), Math.sin( p2 ), 1
  20489. );
  20490. }
  20491. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20492. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20493. this.cone = new LineSegments( geometry, material );
  20494. this.add( this.cone );
  20495. this.update();
  20496. }
  20497. dispose() {
  20498. this.cone.geometry.dispose();
  20499. this.cone.material.dispose();
  20500. }
  20501. update() {
  20502. this.light.updateWorldMatrix( true, false );
  20503. this.light.target.updateWorldMatrix( true, false );
  20504. // update the local matrix based on the parent and light target transforms
  20505. if ( this.parent ) {
  20506. this.parent.updateWorldMatrix( true );
  20507. this.matrix
  20508. .copy( this.parent.matrixWorld )
  20509. .invert()
  20510. .multiply( this.light.matrixWorld );
  20511. } else {
  20512. this.matrix.copy( this.light.matrixWorld );
  20513. }
  20514. this.matrixWorld.copy( this.light.matrixWorld );
  20515. const coneLength = this.light.distance ? this.light.distance : 1000;
  20516. const coneWidth = coneLength * Math.tan( this.light.angle );
  20517. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20518. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20519. this.cone.lookAt( _vector$3 );
  20520. if ( this.color !== undefined ) {
  20521. this.cone.material.color.set( this.color );
  20522. } else {
  20523. this.cone.material.color.copy( this.light.color );
  20524. }
  20525. }
  20526. }
  20527. const _vector$2 = /*@__PURE__*/ new Vector3();
  20528. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20529. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20530. class SkeletonHelper extends LineSegments {
  20531. constructor( object ) {
  20532. const bones = getBoneList( object );
  20533. const geometry = new BufferGeometry();
  20534. const vertices = [];
  20535. const colors = [];
  20536. const color1 = new Color( 0, 0, 1 );
  20537. const color2 = new Color( 0, 1, 0 );
  20538. for ( let i = 0; i < bones.length; i ++ ) {
  20539. const bone = bones[ i ];
  20540. if ( bone.parent && bone.parent.isBone ) {
  20541. vertices.push( 0, 0, 0 );
  20542. vertices.push( 0, 0, 0 );
  20543. colors.push( color1.r, color1.g, color1.b );
  20544. colors.push( color2.r, color2.g, color2.b );
  20545. }
  20546. }
  20547. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20548. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20549. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20550. super( geometry, material );
  20551. this.isSkeletonHelper = true;
  20552. this.type = 'SkeletonHelper';
  20553. this.root = object;
  20554. this.bones = bones;
  20555. this.matrix = object.matrixWorld;
  20556. this.matrixAutoUpdate = false;
  20557. }
  20558. updateMatrixWorld( force ) {
  20559. const bones = this.bones;
  20560. const geometry = this.geometry;
  20561. const position = geometry.getAttribute( 'position' );
  20562. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20563. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20564. const bone = bones[ i ];
  20565. if ( bone.parent && bone.parent.isBone ) {
  20566. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20567. _vector$2.setFromMatrixPosition( _boneMatrix );
  20568. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20569. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20570. _vector$2.setFromMatrixPosition( _boneMatrix );
  20571. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20572. j += 2;
  20573. }
  20574. }
  20575. geometry.getAttribute( 'position' ).needsUpdate = true;
  20576. super.updateMatrixWorld( force );
  20577. }
  20578. dispose() {
  20579. this.geometry.dispose();
  20580. this.material.dispose();
  20581. }
  20582. }
  20583. function getBoneList( object ) {
  20584. const boneList = [];
  20585. if ( object.isBone === true ) {
  20586. boneList.push( object );
  20587. }
  20588. for ( let i = 0; i < object.children.length; i ++ ) {
  20589. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20590. }
  20591. return boneList;
  20592. }
  20593. class PointLightHelper extends Mesh {
  20594. constructor( light, sphereSize, color ) {
  20595. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20596. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20597. super( geometry, material );
  20598. this.light = light;
  20599. this.color = color;
  20600. this.type = 'PointLightHelper';
  20601. this.matrix = this.light.matrixWorld;
  20602. this.matrixAutoUpdate = false;
  20603. this.update();
  20604. /*
  20605. // TODO: delete this comment?
  20606. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20607. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20608. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20609. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20610. const d = light.distance;
  20611. if ( d === 0.0 ) {
  20612. this.lightDistance.visible = false;
  20613. } else {
  20614. this.lightDistance.scale.set( d, d, d );
  20615. }
  20616. this.add( this.lightDistance );
  20617. */
  20618. }
  20619. dispose() {
  20620. this.geometry.dispose();
  20621. this.material.dispose();
  20622. }
  20623. update() {
  20624. this.light.updateWorldMatrix( true, false );
  20625. if ( this.color !== undefined ) {
  20626. this.material.color.set( this.color );
  20627. } else {
  20628. this.material.color.copy( this.light.color );
  20629. }
  20630. /*
  20631. const d = this.light.distance;
  20632. if ( d === 0.0 ) {
  20633. this.lightDistance.visible = false;
  20634. } else {
  20635. this.lightDistance.visible = true;
  20636. this.lightDistance.scale.set( d, d, d );
  20637. }
  20638. */
  20639. }
  20640. }
  20641. const _vector$1 = /*@__PURE__*/ new Vector3();
  20642. const _color1 = /*@__PURE__*/ new Color();
  20643. const _color2 = /*@__PURE__*/ new Color();
  20644. class HemisphereLightHelper extends Object3D {
  20645. constructor( light, size, color ) {
  20646. super();
  20647. this.light = light;
  20648. this.matrix = light.matrixWorld;
  20649. this.matrixAutoUpdate = false;
  20650. this.color = color;
  20651. this.type = 'HemisphereLightHelper';
  20652. const geometry = new OctahedronGeometry( size );
  20653. geometry.rotateY( Math.PI * 0.5 );
  20654. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20655. if ( this.color === undefined ) this.material.vertexColors = true;
  20656. const position = geometry.getAttribute( 'position' );
  20657. const colors = new Float32Array( position.count * 3 );
  20658. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20659. this.add( new Mesh( geometry, this.material ) );
  20660. this.update();
  20661. }
  20662. dispose() {
  20663. this.children[ 0 ].geometry.dispose();
  20664. this.children[ 0 ].material.dispose();
  20665. }
  20666. update() {
  20667. const mesh = this.children[ 0 ];
  20668. if ( this.color !== undefined ) {
  20669. this.material.color.set( this.color );
  20670. } else {
  20671. const colors = mesh.geometry.getAttribute( 'color' );
  20672. _color1.copy( this.light.color );
  20673. _color2.copy( this.light.groundColor );
  20674. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20675. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20676. colors.setXYZ( i, color.r, color.g, color.b );
  20677. }
  20678. colors.needsUpdate = true;
  20679. }
  20680. this.light.updateWorldMatrix( true, false );
  20681. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20682. }
  20683. }
  20684. class GridHelper extends LineSegments {
  20685. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20686. color1 = new Color( color1 );
  20687. color2 = new Color( color2 );
  20688. const center = divisions / 2;
  20689. const step = size / divisions;
  20690. const halfSize = size / 2;
  20691. const vertices = [], colors = [];
  20692. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20693. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20694. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20695. const color = i === center ? color1 : color2;
  20696. color.toArray( colors, j ); j += 3;
  20697. color.toArray( colors, j ); j += 3;
  20698. color.toArray( colors, j ); j += 3;
  20699. color.toArray( colors, j ); j += 3;
  20700. }
  20701. const geometry = new BufferGeometry();
  20702. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20703. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20704. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20705. super( geometry, material );
  20706. this.type = 'GridHelper';
  20707. }
  20708. dispose() {
  20709. this.geometry.dispose();
  20710. this.material.dispose();
  20711. }
  20712. }
  20713. class PolarGridHelper extends LineSegments {
  20714. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20715. color1 = new Color( color1 );
  20716. color2 = new Color( color2 );
  20717. const vertices = [];
  20718. const colors = [];
  20719. // create the sectors
  20720. if ( sectors > 1 ) {
  20721. for ( let i = 0; i < sectors; i ++ ) {
  20722. const v = ( i / sectors ) * ( Math.PI * 2 );
  20723. const x = Math.sin( v ) * radius;
  20724. const z = Math.cos( v ) * radius;
  20725. vertices.push( 0, 0, 0 );
  20726. vertices.push( x, 0, z );
  20727. const color = ( i & 1 ) ? color1 : color2;
  20728. colors.push( color.r, color.g, color.b );
  20729. colors.push( color.r, color.g, color.b );
  20730. }
  20731. }
  20732. // create the rings
  20733. for ( let i = 0; i < rings; i ++ ) {
  20734. const color = ( i & 1 ) ? color1 : color2;
  20735. const r = radius - ( radius / rings * i );
  20736. for ( let j = 0; j < divisions; j ++ ) {
  20737. // first vertex
  20738. let v = ( j / divisions ) * ( Math.PI * 2 );
  20739. let x = Math.sin( v ) * r;
  20740. let z = Math.cos( v ) * r;
  20741. vertices.push( x, 0, z );
  20742. colors.push( color.r, color.g, color.b );
  20743. // second vertex
  20744. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20745. x = Math.sin( v ) * r;
  20746. z = Math.cos( v ) * r;
  20747. vertices.push( x, 0, z );
  20748. colors.push( color.r, color.g, color.b );
  20749. }
  20750. }
  20751. const geometry = new BufferGeometry();
  20752. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20753. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20754. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20755. super( geometry, material );
  20756. this.type = 'PolarGridHelper';
  20757. }
  20758. dispose() {
  20759. this.geometry.dispose();
  20760. this.material.dispose();
  20761. }
  20762. }
  20763. const _v1 = /*@__PURE__*/ new Vector3();
  20764. const _v2 = /*@__PURE__*/ new Vector3();
  20765. const _v3 = /*@__PURE__*/ new Vector3();
  20766. class DirectionalLightHelper extends Object3D {
  20767. constructor( light, size, color ) {
  20768. super();
  20769. this.light = light;
  20770. this.matrix = light.matrixWorld;
  20771. this.matrixAutoUpdate = false;
  20772. this.color = color;
  20773. this.type = 'DirectionalLightHelper';
  20774. if ( size === undefined ) size = 1;
  20775. let geometry = new BufferGeometry();
  20776. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20777. - size, size, 0,
  20778. size, size, 0,
  20779. size, - size, 0,
  20780. - size, - size, 0,
  20781. - size, size, 0
  20782. ], 3 ) );
  20783. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20784. this.lightPlane = new Line( geometry, material );
  20785. this.add( this.lightPlane );
  20786. geometry = new BufferGeometry();
  20787. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20788. this.targetLine = new Line( geometry, material );
  20789. this.add( this.targetLine );
  20790. this.update();
  20791. }
  20792. dispose() {
  20793. this.lightPlane.geometry.dispose();
  20794. this.lightPlane.material.dispose();
  20795. this.targetLine.geometry.dispose();
  20796. this.targetLine.material.dispose();
  20797. }
  20798. update() {
  20799. this.light.updateWorldMatrix( true, false );
  20800. this.light.target.updateWorldMatrix( true, false );
  20801. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20802. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20803. _v3.subVectors( _v2, _v1 );
  20804. this.lightPlane.lookAt( _v2 );
  20805. if ( this.color !== undefined ) {
  20806. this.lightPlane.material.color.set( this.color );
  20807. this.targetLine.material.color.set( this.color );
  20808. } else {
  20809. this.lightPlane.material.color.copy( this.light.color );
  20810. this.targetLine.material.color.copy( this.light.color );
  20811. }
  20812. this.targetLine.lookAt( _v2 );
  20813. this.targetLine.scale.z = _v3.length();
  20814. }
  20815. }
  20816. const _vector = /*@__PURE__*/ new Vector3();
  20817. const _camera$1 = /*@__PURE__*/ new Camera();
  20818. /**
  20819. * - shows frustum, line of sight and up of the camera
  20820. * - suitable for fast updates
  20821. * - based on frustum visualization in lightgl.js shadowmap example
  20822. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20823. */
  20824. class CameraHelper extends LineSegments {
  20825. constructor( camera ) {
  20826. const geometry = new BufferGeometry();
  20827. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20828. const vertices = [];
  20829. const colors = [];
  20830. const pointMap = {};
  20831. // near
  20832. addLine( 'n1', 'n2' );
  20833. addLine( 'n2', 'n4' );
  20834. addLine( 'n4', 'n3' );
  20835. addLine( 'n3', 'n1' );
  20836. // far
  20837. addLine( 'f1', 'f2' );
  20838. addLine( 'f2', 'f4' );
  20839. addLine( 'f4', 'f3' );
  20840. addLine( 'f3', 'f1' );
  20841. // sides
  20842. addLine( 'n1', 'f1' );
  20843. addLine( 'n2', 'f2' );
  20844. addLine( 'n3', 'f3' );
  20845. addLine( 'n4', 'f4' );
  20846. // cone
  20847. addLine( 'p', 'n1' );
  20848. addLine( 'p', 'n2' );
  20849. addLine( 'p', 'n3' );
  20850. addLine( 'p', 'n4' );
  20851. // up
  20852. addLine( 'u1', 'u2' );
  20853. addLine( 'u2', 'u3' );
  20854. addLine( 'u3', 'u1' );
  20855. // target
  20856. addLine( 'c', 't' );
  20857. addLine( 'p', 'c' );
  20858. // cross
  20859. addLine( 'cn1', 'cn2' );
  20860. addLine( 'cn3', 'cn4' );
  20861. addLine( 'cf1', 'cf2' );
  20862. addLine( 'cf3', 'cf4' );
  20863. function addLine( a, b ) {
  20864. addPoint( a );
  20865. addPoint( b );
  20866. }
  20867. function addPoint( id ) {
  20868. vertices.push( 0, 0, 0 );
  20869. colors.push( 0, 0, 0 );
  20870. if ( pointMap[ id ] === undefined ) {
  20871. pointMap[ id ] = [];
  20872. }
  20873. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20874. }
  20875. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20876. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20877. super( geometry, material );
  20878. this.type = 'CameraHelper';
  20879. this.camera = camera;
  20880. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20881. this.matrix = camera.matrixWorld;
  20882. this.matrixAutoUpdate = false;
  20883. this.pointMap = pointMap;
  20884. this.update();
  20885. // colors
  20886. const colorFrustum = new Color( 0xffaa00 );
  20887. const colorCone = new Color( 0xff0000 );
  20888. const colorUp = new Color( 0x00aaff );
  20889. const colorTarget = new Color( 0xffffff );
  20890. const colorCross = new Color( 0x333333 );
  20891. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20892. }
  20893. setColors( frustum, cone, up, target, cross ) {
  20894. const geometry = this.geometry;
  20895. const colorAttribute = geometry.getAttribute( 'color' );
  20896. // near
  20897. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20898. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20899. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20900. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20901. // far
  20902. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20903. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20904. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20905. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20906. // sides
  20907. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20908. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20909. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20910. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20911. // cone
  20912. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20913. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20914. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20915. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20916. // up
  20917. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20918. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20919. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20920. // target
  20921. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20922. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20923. // cross
  20924. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20925. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20926. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20927. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20928. colorAttribute.needsUpdate = true;
  20929. }
  20930. update() {
  20931. const geometry = this.geometry;
  20932. const pointMap = this.pointMap;
  20933. const w = 1, h = 1;
  20934. // we need just camera projection matrix inverse
  20935. // world matrix must be identity
  20936. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20937. // center / target
  20938. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20939. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20940. // near
  20941. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20942. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20943. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20944. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20945. // far
  20946. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20947. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20948. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20949. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20950. // up
  20951. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20952. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20953. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20954. // cross
  20955. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20956. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20957. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20958. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20959. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20960. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20961. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20962. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20963. geometry.getAttribute( 'position' ).needsUpdate = true;
  20964. }
  20965. dispose() {
  20966. this.geometry.dispose();
  20967. this.material.dispose();
  20968. }
  20969. }
  20970. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20971. _vector.set( x, y, z ).unproject( camera );
  20972. const points = pointMap[ point ];
  20973. if ( points !== undefined ) {
  20974. const position = geometry.getAttribute( 'position' );
  20975. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20976. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20977. }
  20978. }
  20979. }
  20980. const _box = /*@__PURE__*/ new Box3();
  20981. class BoxHelper extends LineSegments {
  20982. constructor( object, color = 0xffff00 ) {
  20983. 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 ] );
  20984. const positions = new Float32Array( 8 * 3 );
  20985. const geometry = new BufferGeometry();
  20986. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20987. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20988. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20989. this.object = object;
  20990. this.type = 'BoxHelper';
  20991. this.matrixAutoUpdate = false;
  20992. this.update();
  20993. }
  20994. update( object ) {
  20995. if ( object !== undefined ) {
  20996. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20997. }
  20998. if ( this.object !== undefined ) {
  20999. _box.setFromObject( this.object );
  21000. }
  21001. if ( _box.isEmpty() ) return;
  21002. const min = _box.min;
  21003. const max = _box.max;
  21004. /*
  21005. 5____4
  21006. 1/___0/|
  21007. | 6__|_7
  21008. 2/___3/
  21009. 0: max.x, max.y, max.z
  21010. 1: min.x, max.y, max.z
  21011. 2: min.x, min.y, max.z
  21012. 3: max.x, min.y, max.z
  21013. 4: max.x, max.y, min.z
  21014. 5: min.x, max.y, min.z
  21015. 6: min.x, min.y, min.z
  21016. 7: max.x, min.y, min.z
  21017. */
  21018. const position = this.geometry.attributes.position;
  21019. const array = position.array;
  21020. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21021. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21022. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21023. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21024. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21025. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21026. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21027. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21028. position.needsUpdate = true;
  21029. this.geometry.computeBoundingSphere();
  21030. }
  21031. setFromObject( object ) {
  21032. this.object = object;
  21033. this.update();
  21034. return this;
  21035. }
  21036. copy( source, recursive ) {
  21037. super.copy( source, recursive );
  21038. this.object = source.object;
  21039. return this;
  21040. }
  21041. dispose() {
  21042. this.geometry.dispose();
  21043. this.material.dispose();
  21044. }
  21045. }
  21046. class Box3Helper extends LineSegments {
  21047. constructor( box, color = 0xffff00 ) {
  21048. 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 ] );
  21049. 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 ];
  21050. const geometry = new BufferGeometry();
  21051. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21052. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21053. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21054. this.box = box;
  21055. this.type = 'Box3Helper';
  21056. this.geometry.computeBoundingSphere();
  21057. }
  21058. updateMatrixWorld( force ) {
  21059. const box = this.box;
  21060. if ( box.isEmpty() ) return;
  21061. box.getCenter( this.position );
  21062. box.getSize( this.scale );
  21063. this.scale.multiplyScalar( 0.5 );
  21064. super.updateMatrixWorld( force );
  21065. }
  21066. dispose() {
  21067. this.geometry.dispose();
  21068. this.material.dispose();
  21069. }
  21070. }
  21071. class PlaneHelper extends Line {
  21072. constructor( plane, size = 1, hex = 0xffff00 ) {
  21073. const color = hex;
  21074. 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 ];
  21075. const geometry = new BufferGeometry();
  21076. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21077. geometry.computeBoundingSphere();
  21078. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21079. this.type = 'PlaneHelper';
  21080. this.plane = plane;
  21081. this.size = size;
  21082. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21083. const geometry2 = new BufferGeometry();
  21084. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21085. geometry2.computeBoundingSphere();
  21086. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21087. }
  21088. updateMatrixWorld( force ) {
  21089. this.position.set( 0, 0, 0 );
  21090. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21091. this.lookAt( this.plane.normal );
  21092. this.translateZ( - this.plane.constant );
  21093. super.updateMatrixWorld( force );
  21094. }
  21095. dispose() {
  21096. this.geometry.dispose();
  21097. this.material.dispose();
  21098. this.children[ 0 ].geometry.dispose();
  21099. this.children[ 0 ].material.dispose();
  21100. }
  21101. }
  21102. const _axis = /*@__PURE__*/ new Vector3();
  21103. let _lineGeometry, _coneGeometry;
  21104. class ArrowHelper extends Object3D {
  21105. // dir is assumed to be normalized
  21106. 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 ) {
  21107. super();
  21108. this.type = 'ArrowHelper';
  21109. if ( _lineGeometry === undefined ) {
  21110. _lineGeometry = new BufferGeometry();
  21111. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21112. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21113. _coneGeometry.translate( 0, - 0.5, 0 );
  21114. }
  21115. this.position.copy( origin );
  21116. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21117. this.line.matrixAutoUpdate = false;
  21118. this.add( this.line );
  21119. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21120. this.cone.matrixAutoUpdate = false;
  21121. this.add( this.cone );
  21122. this.setDirection( dir );
  21123. this.setLength( length, headLength, headWidth );
  21124. }
  21125. setDirection( dir ) {
  21126. // dir is assumed to be normalized
  21127. if ( dir.y > 0.99999 ) {
  21128. this.quaternion.set( 0, 0, 0, 1 );
  21129. } else if ( dir.y < - 0.99999 ) {
  21130. this.quaternion.set( 1, 0, 0, 0 );
  21131. } else {
  21132. _axis.set( dir.z, 0, - dir.x ).normalize();
  21133. const radians = Math.acos( dir.y );
  21134. this.quaternion.setFromAxisAngle( _axis, radians );
  21135. }
  21136. }
  21137. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21138. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21139. this.line.updateMatrix();
  21140. this.cone.scale.set( headWidth, headLength, headWidth );
  21141. this.cone.position.y = length;
  21142. this.cone.updateMatrix();
  21143. }
  21144. setColor( color ) {
  21145. this.line.material.color.set( color );
  21146. this.cone.material.color.set( color );
  21147. }
  21148. copy( source ) {
  21149. super.copy( source, false );
  21150. this.line.copy( source.line );
  21151. this.cone.copy( source.cone );
  21152. return this;
  21153. }
  21154. dispose() {
  21155. this.line.geometry.dispose();
  21156. this.line.material.dispose();
  21157. this.cone.geometry.dispose();
  21158. this.cone.material.dispose();
  21159. }
  21160. }
  21161. class AxesHelper extends LineSegments {
  21162. constructor( size = 1 ) {
  21163. const vertices = [
  21164. 0, 0, 0, size, 0, 0,
  21165. 0, 0, 0, 0, size, 0,
  21166. 0, 0, 0, 0, 0, size
  21167. ];
  21168. const colors = [
  21169. 1, 0, 0, 1, 0.6, 0,
  21170. 0, 1, 0, 0.6, 1, 0,
  21171. 0, 0, 1, 0, 0.6, 1
  21172. ];
  21173. const geometry = new BufferGeometry();
  21174. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21175. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21176. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21177. super( geometry, material );
  21178. this.type = 'AxesHelper';
  21179. }
  21180. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21181. const color = new Color();
  21182. const array = this.geometry.attributes.color.array;
  21183. color.set( xAxisColor );
  21184. color.toArray( array, 0 );
  21185. color.toArray( array, 3 );
  21186. color.set( yAxisColor );
  21187. color.toArray( array, 6 );
  21188. color.toArray( array, 9 );
  21189. color.set( zAxisColor );
  21190. color.toArray( array, 12 );
  21191. color.toArray( array, 15 );
  21192. this.geometry.attributes.color.needsUpdate = true;
  21193. return this;
  21194. }
  21195. dispose() {
  21196. this.geometry.dispose();
  21197. this.material.dispose();
  21198. }
  21199. }
  21200. class ShapePath {
  21201. constructor() {
  21202. this.type = 'ShapePath';
  21203. this.color = new Color();
  21204. this.subPaths = [];
  21205. this.currentPath = null;
  21206. }
  21207. moveTo( x, y ) {
  21208. this.currentPath = new Path();
  21209. this.subPaths.push( this.currentPath );
  21210. this.currentPath.moveTo( x, y );
  21211. return this;
  21212. }
  21213. lineTo( x, y ) {
  21214. this.currentPath.lineTo( x, y );
  21215. return this;
  21216. }
  21217. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21218. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21219. return this;
  21220. }
  21221. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21222. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21223. return this;
  21224. }
  21225. splineThru( pts ) {
  21226. this.currentPath.splineThru( pts );
  21227. return this;
  21228. }
  21229. toShapes( isCCW ) {
  21230. function toShapesNoHoles( inSubpaths ) {
  21231. const shapes = [];
  21232. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21233. const tmpPath = inSubpaths[ i ];
  21234. const tmpShape = new Shape();
  21235. tmpShape.curves = tmpPath.curves;
  21236. shapes.push( tmpShape );
  21237. }
  21238. return shapes;
  21239. }
  21240. function isPointInsidePolygon( inPt, inPolygon ) {
  21241. const polyLen = inPolygon.length;
  21242. // inPt on polygon contour => immediate success or
  21243. // toggling of inside/outside at every single! intersection point of an edge
  21244. // with the horizontal line through inPt, left of inPt
  21245. // not counting lowerY endpoints of edges and whole edges on that line
  21246. let inside = false;
  21247. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21248. let edgeLowPt = inPolygon[ p ];
  21249. let edgeHighPt = inPolygon[ q ];
  21250. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21251. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21252. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21253. // not parallel
  21254. if ( edgeDy < 0 ) {
  21255. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21256. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21257. }
  21258. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21259. if ( inPt.y === edgeLowPt.y ) {
  21260. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21261. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21262. } else {
  21263. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21264. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21265. if ( perpEdge < 0 ) continue;
  21266. inside = ! inside; // true intersection left of inPt
  21267. }
  21268. } else {
  21269. // parallel or collinear
  21270. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21271. // edge lies on the same horizontal line as inPt
  21272. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21273. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21274. // continue;
  21275. }
  21276. }
  21277. return inside;
  21278. }
  21279. const isClockWise = ShapeUtils.isClockWise;
  21280. const subPaths = this.subPaths;
  21281. if ( subPaths.length === 0 ) return [];
  21282. let solid, tmpPath, tmpShape;
  21283. const shapes = [];
  21284. if ( subPaths.length === 1 ) {
  21285. tmpPath = subPaths[ 0 ];
  21286. tmpShape = new Shape();
  21287. tmpShape.curves = tmpPath.curves;
  21288. shapes.push( tmpShape );
  21289. return shapes;
  21290. }
  21291. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21292. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21293. // console.log("Holes first", holesFirst);
  21294. const betterShapeHoles = [];
  21295. const newShapes = [];
  21296. let newShapeHoles = [];
  21297. let mainIdx = 0;
  21298. let tmpPoints;
  21299. newShapes[ mainIdx ] = undefined;
  21300. newShapeHoles[ mainIdx ] = [];
  21301. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21302. tmpPath = subPaths[ i ];
  21303. tmpPoints = tmpPath.getPoints();
  21304. solid = isClockWise( tmpPoints );
  21305. solid = isCCW ? ! solid : solid;
  21306. if ( solid ) {
  21307. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21308. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21309. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21310. if ( holesFirst ) mainIdx ++;
  21311. newShapeHoles[ mainIdx ] = [];
  21312. //console.log('cw', i);
  21313. } else {
  21314. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21315. //console.log('ccw', i);
  21316. }
  21317. }
  21318. // only Holes? -> probably all Shapes with wrong orientation
  21319. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21320. if ( newShapes.length > 1 ) {
  21321. let ambiguous = false;
  21322. let toChange = 0;
  21323. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21324. betterShapeHoles[ sIdx ] = [];
  21325. }
  21326. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21327. const sho = newShapeHoles[ sIdx ];
  21328. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21329. const ho = sho[ hIdx ];
  21330. let hole_unassigned = true;
  21331. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21332. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21333. if ( sIdx !== s2Idx ) toChange ++;
  21334. if ( hole_unassigned ) {
  21335. hole_unassigned = false;
  21336. betterShapeHoles[ s2Idx ].push( ho );
  21337. } else {
  21338. ambiguous = true;
  21339. }
  21340. }
  21341. }
  21342. if ( hole_unassigned ) {
  21343. betterShapeHoles[ sIdx ].push( ho );
  21344. }
  21345. }
  21346. }
  21347. if ( toChange > 0 && ambiguous === false ) {
  21348. newShapeHoles = betterShapeHoles;
  21349. }
  21350. }
  21351. let tmpHoles;
  21352. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21353. tmpShape = newShapes[ i ].s;
  21354. shapes.push( tmpShape );
  21355. tmpHoles = newShapeHoles[ i ];
  21356. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21357. tmpShape.holes.push( tmpHoles[ j ].h );
  21358. }
  21359. }
  21360. //console.log("shape", shapes);
  21361. return shapes;
  21362. }
  21363. }
  21364. class Controls extends EventDispatcher {
  21365. constructor( object, domElement = null ) {
  21366. super();
  21367. this.object = object;
  21368. this.domElement = domElement;
  21369. this.enabled = true;
  21370. this.state = - 1;
  21371. this.keys = {};
  21372. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21373. this.touches = { ONE: null, TWO: null };
  21374. }
  21375. connect() {}
  21376. disconnect() {}
  21377. dispose() {}
  21378. update( /* delta */ ) {}
  21379. }
  21380. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21381. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21382. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21383. super( width, height, { ...options, count } );
  21384. this.isWebGLMultipleRenderTargets = true;
  21385. }
  21386. get texture() {
  21387. return this.textures;
  21388. }
  21389. }
  21390. const refreshUniforms = [
  21391. 'alphaMap',
  21392. 'alphaTest',
  21393. 'anisotropy',
  21394. 'anisotropyMap',
  21395. 'anisotropyRotation',
  21396. 'aoMap',
  21397. 'attenuationColor',
  21398. 'attenuationDistance',
  21399. 'bumpMap',
  21400. 'clearcoat',
  21401. 'clearcoatMap',
  21402. 'clearcoatNormalMap',
  21403. 'clearcoatNormalScale',
  21404. 'clearcoatRoughness',
  21405. 'color',
  21406. 'dispersion',
  21407. 'displacementMap',
  21408. 'emissive',
  21409. 'emissiveMap',
  21410. 'envMap',
  21411. 'gradientMap',
  21412. 'ior',
  21413. 'iridescence',
  21414. 'iridescenceIOR',
  21415. 'iridescenceMap',
  21416. 'iridescenceThicknessMap',
  21417. 'lightMap',
  21418. 'map',
  21419. 'matcap',
  21420. 'metalness',
  21421. 'metalnessMap',
  21422. 'normalMap',
  21423. 'normalScale',
  21424. 'opacity',
  21425. 'roughness',
  21426. 'roughnessMap',
  21427. 'sheen',
  21428. 'sheenColor',
  21429. 'sheenColorMap',
  21430. 'sheenRoughnessMap',
  21431. 'shininess',
  21432. 'specular',
  21433. 'specularColor',
  21434. 'specularColorMap',
  21435. 'specularIntensity',
  21436. 'specularIntensityMap',
  21437. 'specularMap',
  21438. 'thickness',
  21439. 'transmission',
  21440. 'transmissionMap'
  21441. ];
  21442. class NodeMaterialObserver {
  21443. constructor( builder ) {
  21444. this.renderObjects = new WeakMap();
  21445. this.hasNode = this.containsNode( builder );
  21446. this.hasAnimation = builder.object.isSkinnedMesh === true;
  21447. this.refreshUniforms = refreshUniforms;
  21448. this.renderId = 0;
  21449. }
  21450. firstInitialization( renderObject ) {
  21451. const hasInitialized = this.renderObjects.has( renderObject );
  21452. if ( hasInitialized === false ) {
  21453. this.getRenderObjectData( renderObject );
  21454. return true;
  21455. }
  21456. return false;
  21457. }
  21458. getRenderObjectData( renderObject ) {
  21459. let data = this.renderObjects.get( renderObject );
  21460. if ( data === undefined ) {
  21461. data = {
  21462. material: this.getMaterialData( renderObject.material ),
  21463. worldMatrix: renderObject.object.matrixWorld.clone()
  21464. };
  21465. if ( renderObject.object.center ) {
  21466. data.center = renderObject.object.center.clone();
  21467. }
  21468. if ( renderObject.object.morphTargetInfluences ) {
  21469. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  21470. }
  21471. if ( renderObject.bundle !== null ) {
  21472. data.version = renderObject.bundle.version;
  21473. }
  21474. this.renderObjects.set( renderObject, data );
  21475. }
  21476. return data;
  21477. }
  21478. containsNode( builder ) {
  21479. const material = builder.material;
  21480. for ( const property in material ) {
  21481. if ( material[ property ] && material[ property ].isNode )
  21482. return true;
  21483. }
  21484. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  21485. return true;
  21486. return false;
  21487. }
  21488. getMaterialData( material ) {
  21489. const data = {};
  21490. for ( const property of this.refreshUniforms ) {
  21491. const value = material[ property ];
  21492. if ( value === null || value === undefined ) continue;
  21493. if ( typeof value === 'object' && value.clone !== undefined ) {
  21494. if ( value.isTexture === true ) {
  21495. data[ property ] = { id: value.id, version: value.version };
  21496. } else {
  21497. data[ property ] = value.clone();
  21498. }
  21499. } else {
  21500. data[ property ] = value;
  21501. }
  21502. }
  21503. return data;
  21504. }
  21505. equals( renderObject ) {
  21506. const { object, material } = renderObject;
  21507. const renderObjectData = this.getRenderObjectData( renderObject );
  21508. // world matrix
  21509. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  21510. renderObjectData.worldMatrix.copy( object.matrixWorld );
  21511. return false;
  21512. }
  21513. // material
  21514. const materialData = renderObjectData.material;
  21515. for ( const property in materialData ) {
  21516. const value = materialData[ property ];
  21517. const mtlValue = material[ property ];
  21518. if ( value.equals !== undefined ) {
  21519. if ( value.equals( mtlValue ) === false ) {
  21520. value.copy( mtlValue );
  21521. return false;
  21522. }
  21523. } else if ( mtlValue.isTexture === true ) {
  21524. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  21525. value.id = mtlValue.id;
  21526. value.version = mtlValue.version;
  21527. return false;
  21528. }
  21529. } else if ( value !== mtlValue ) {
  21530. materialData[ property ] = mtlValue;
  21531. return false;
  21532. }
  21533. }
  21534. // morph targets
  21535. if ( renderObjectData.morphTargetInfluences ) {
  21536. let morphChanged = false;
  21537. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  21538. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  21539. morphChanged = true;
  21540. }
  21541. }
  21542. if ( morphChanged ) return true;
  21543. }
  21544. // center
  21545. if ( renderObjectData.center ) {
  21546. if ( renderObjectData.center.equals( object.center ) === false ) {
  21547. renderObjectData.center.copy( object.center );
  21548. return true;
  21549. }
  21550. }
  21551. // bundle
  21552. if ( renderObject.bundle !== null ) {
  21553. renderObjectData.version = renderObject.bundle.version;
  21554. }
  21555. return true;
  21556. }
  21557. needsRefresh( renderObject, nodeFrame ) {
  21558. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  21559. return true;
  21560. const { renderId } = nodeFrame;
  21561. if ( this.renderId !== renderId ) {
  21562. this.renderId = renderId;
  21563. return true;
  21564. }
  21565. const isStatic = renderObject.object.static === true;
  21566. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  21567. if ( isStatic || isBundle )
  21568. return false;
  21569. const notEqual = this.equals( renderObject ) !== true;
  21570. return notEqual;
  21571. }
  21572. }
  21573. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  21574. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  21575. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  21576. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  21577. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  21578. function cyrb53( value, seed = 0 ) {
  21579. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  21580. if ( value instanceof Array ) {
  21581. for ( let i = 0, val; i < value.length; i ++ ) {
  21582. val = value[ i ];
  21583. h1 = Math.imul( h1 ^ val, 2654435761 );
  21584. h2 = Math.imul( h2 ^ val, 1597334677 );
  21585. }
  21586. } else {
  21587. for ( let i = 0, ch; i < value.length; i ++ ) {
  21588. ch = value.charCodeAt( i );
  21589. h1 = Math.imul( h1 ^ ch, 2654435761 );
  21590. h2 = Math.imul( h2 ^ ch, 1597334677 );
  21591. }
  21592. }
  21593. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  21594. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  21595. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  21596. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  21597. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  21598. }
  21599. const hashString = ( str ) => cyrb53( str );
  21600. const hashArray = ( array ) => cyrb53( array );
  21601. const hash$1 = ( ...params ) => cyrb53( params );
  21602. function getCacheKey$1( object, force = false ) {
  21603. const values = [];
  21604. if ( object.isNode === true ) {
  21605. values.push( object.id );
  21606. object = object.getSelf();
  21607. }
  21608. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21609. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  21610. }
  21611. return cyrb53( values );
  21612. }
  21613. function* getNodeChildren( node, toJSON = false ) {
  21614. for ( const property in node ) {
  21615. // Ignore private properties.
  21616. if ( property.startsWith( '_' ) === true ) continue;
  21617. const object = node[ property ];
  21618. if ( Array.isArray( object ) === true ) {
  21619. for ( let i = 0; i < object.length; i ++ ) {
  21620. const child = object[ i ];
  21621. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21622. yield { property, index: i, childNode: child };
  21623. }
  21624. }
  21625. } else if ( object && object.isNode === true ) {
  21626. yield { property, childNode: object };
  21627. } else if ( typeof object === 'object' ) {
  21628. for ( const subProperty in object ) {
  21629. const child = object[ subProperty ];
  21630. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21631. yield { property, index: subProperty, childNode: child };
  21632. }
  21633. }
  21634. }
  21635. }
  21636. }
  21637. function getValueType( value ) {
  21638. if ( value === undefined || value === null ) return null;
  21639. const typeOf = typeof value;
  21640. if ( value.isNode === true ) {
  21641. return 'node';
  21642. } else if ( typeOf === 'number' ) {
  21643. return 'float';
  21644. } else if ( typeOf === 'boolean' ) {
  21645. return 'bool';
  21646. } else if ( typeOf === 'string' ) {
  21647. return 'string';
  21648. } else if ( typeOf === 'function' ) {
  21649. return 'shader';
  21650. } else if ( value.isVector2 === true ) {
  21651. return 'vec2';
  21652. } else if ( value.isVector3 === true ) {
  21653. return 'vec3';
  21654. } else if ( value.isVector4 === true ) {
  21655. return 'vec4';
  21656. } else if ( value.isMatrix3 === true ) {
  21657. return 'mat3';
  21658. } else if ( value.isMatrix4 === true ) {
  21659. return 'mat4';
  21660. } else if ( value.isColor === true ) {
  21661. return 'color';
  21662. } else if ( value instanceof ArrayBuffer ) {
  21663. return 'ArrayBuffer';
  21664. }
  21665. return null;
  21666. }
  21667. function getValueFromType( type, ...params ) {
  21668. const last4 = type ? type.slice( - 4 ) : undefined;
  21669. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21670. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21671. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21672. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21673. }
  21674. if ( type === 'color' ) {
  21675. return new Color( ...params );
  21676. } else if ( last4 === 'vec2' ) {
  21677. return new Vector2( ...params );
  21678. } else if ( last4 === 'vec3' ) {
  21679. return new Vector3( ...params );
  21680. } else if ( last4 === 'vec4' ) {
  21681. return new Vector4( ...params );
  21682. } else if ( last4 === 'mat3' ) {
  21683. return new Matrix3( ...params );
  21684. } else if ( last4 === 'mat4' ) {
  21685. return new Matrix4( ...params );
  21686. } else if ( type === 'bool' ) {
  21687. return params[ 0 ] || false;
  21688. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21689. return params[ 0 ] || 0;
  21690. } else if ( type === 'string' ) {
  21691. return params[ 0 ] || '';
  21692. } else if ( type === 'ArrayBuffer' ) {
  21693. return base64ToArrayBuffer( params[ 0 ] );
  21694. }
  21695. return null;
  21696. }
  21697. function arrayBufferToBase64( arrayBuffer ) {
  21698. let chars = '';
  21699. const array = new Uint8Array( arrayBuffer );
  21700. for ( let i = 0; i < array.length; i ++ ) {
  21701. chars += String.fromCharCode( array[ i ] );
  21702. }
  21703. return btoa( chars );
  21704. }
  21705. function base64ToArrayBuffer( base64 ) {
  21706. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21707. }
  21708. var NodeUtils = /*#__PURE__*/Object.freeze({
  21709. __proto__: null,
  21710. arrayBufferToBase64: arrayBufferToBase64,
  21711. base64ToArrayBuffer: base64ToArrayBuffer,
  21712. getCacheKey: getCacheKey$1,
  21713. getNodeChildren: getNodeChildren,
  21714. getValueFromType: getValueFromType,
  21715. getValueType: getValueType,
  21716. hash: hash$1,
  21717. hashArray: hashArray,
  21718. hashString: hashString
  21719. });
  21720. const NodeShaderStage = {
  21721. VERTEX: 'vertex',
  21722. FRAGMENT: 'fragment'
  21723. };
  21724. const NodeUpdateType = {
  21725. NONE: 'none',
  21726. FRAME: 'frame',
  21727. RENDER: 'render',
  21728. OBJECT: 'object'
  21729. };
  21730. const NodeType = {
  21731. BOOLEAN: 'bool',
  21732. INTEGER: 'int',
  21733. FLOAT: 'float',
  21734. VECTOR2: 'vec2',
  21735. VECTOR3: 'vec3',
  21736. VECTOR4: 'vec4',
  21737. MATRIX2: 'mat2',
  21738. MATRIX3: 'mat3',
  21739. MATRIX4: 'mat4'
  21740. };
  21741. const defaultShaderStages = [ 'fragment', 'vertex' ];
  21742. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  21743. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  21744. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  21745. let _nodeId = 0;
  21746. class Node extends EventDispatcher {
  21747. static get type() {
  21748. return 'Node';
  21749. }
  21750. constructor( nodeType = null ) {
  21751. super();
  21752. this.nodeType = nodeType;
  21753. this.updateType = NodeUpdateType.NONE;
  21754. this.updateBeforeType = NodeUpdateType.NONE;
  21755. this.updateAfterType = NodeUpdateType.NONE;
  21756. this.uuid = MathUtils.generateUUID();
  21757. this.version = 0;
  21758. this._cacheKey = null;
  21759. this._cacheKeyVersion = 0;
  21760. this.global = false;
  21761. this.isNode = true;
  21762. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  21763. }
  21764. set needsUpdate( value ) {
  21765. if ( value === true ) {
  21766. this.version ++;
  21767. }
  21768. }
  21769. get type() {
  21770. return this.constructor.type;
  21771. }
  21772. onUpdate( callback, updateType ) {
  21773. this.updateType = updateType;
  21774. this.update = callback.bind( this.getSelf() );
  21775. return this;
  21776. }
  21777. onFrameUpdate( callback ) {
  21778. return this.onUpdate( callback, NodeUpdateType.FRAME );
  21779. }
  21780. onRenderUpdate( callback ) {
  21781. return this.onUpdate( callback, NodeUpdateType.RENDER );
  21782. }
  21783. onObjectUpdate( callback ) {
  21784. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  21785. }
  21786. onReference( callback ) {
  21787. this.updateReference = callback.bind( this.getSelf() );
  21788. return this;
  21789. }
  21790. getSelf() {
  21791. // Returns non-node object.
  21792. return this.self || this;
  21793. }
  21794. updateReference( /*state*/ ) {
  21795. return this;
  21796. }
  21797. isGlobal( /*builder*/ ) {
  21798. return this.global;
  21799. }
  21800. * getChildren() {
  21801. for ( const { childNode } of getNodeChildren( this ) ) {
  21802. yield childNode;
  21803. }
  21804. }
  21805. dispose() {
  21806. this.dispatchEvent( { type: 'dispose' } );
  21807. }
  21808. traverse( callback ) {
  21809. callback( this );
  21810. for ( const childNode of this.getChildren() ) {
  21811. childNode.traverse( callback );
  21812. }
  21813. }
  21814. getCacheKey( force = false ) {
  21815. force = force || this.version !== this._cacheKeyVersion;
  21816. if ( force === true || this._cacheKey === null ) {
  21817. this._cacheKey = getCacheKey$1( this, force );
  21818. this._cacheKeyVersion = this.version;
  21819. }
  21820. return this._cacheKey;
  21821. }
  21822. getScope() {
  21823. return this;
  21824. }
  21825. getHash( /*builder*/ ) {
  21826. return this.uuid;
  21827. }
  21828. getUpdateType() {
  21829. return this.updateType;
  21830. }
  21831. getUpdateBeforeType() {
  21832. return this.updateBeforeType;
  21833. }
  21834. getUpdateAfterType() {
  21835. return this.updateAfterType;
  21836. }
  21837. getElementType( builder ) {
  21838. const type = this.getNodeType( builder );
  21839. const elementType = builder.getElementType( type );
  21840. return elementType;
  21841. }
  21842. getNodeType( builder ) {
  21843. const nodeProperties = builder.getNodeProperties( this );
  21844. if ( nodeProperties.outputNode ) {
  21845. return nodeProperties.outputNode.getNodeType( builder );
  21846. }
  21847. return this.nodeType;
  21848. }
  21849. getShared( builder ) {
  21850. const hash = this.getHash( builder );
  21851. const nodeFromHash = builder.getNodeFromHash( hash );
  21852. return nodeFromHash || this;
  21853. }
  21854. setup( builder ) {
  21855. const nodeProperties = builder.getNodeProperties( this );
  21856. let index = 0;
  21857. for ( const childNode of this.getChildren() ) {
  21858. nodeProperties[ 'node' + index ++ ] = childNode;
  21859. }
  21860. // return a outputNode if exists
  21861. return null;
  21862. }
  21863. analyze( builder ) {
  21864. const usageCount = builder.increaseUsage( this );
  21865. if ( usageCount === 1 ) {
  21866. // node flow children
  21867. const nodeProperties = builder.getNodeProperties( this );
  21868. for ( const childNode of Object.values( nodeProperties ) ) {
  21869. if ( childNode && childNode.isNode === true ) {
  21870. childNode.build( builder );
  21871. }
  21872. }
  21873. }
  21874. }
  21875. generate( builder, output ) {
  21876. const { outputNode } = builder.getNodeProperties( this );
  21877. if ( outputNode && outputNode.isNode === true ) {
  21878. return outputNode.build( builder, output );
  21879. }
  21880. }
  21881. updateBefore( /*frame*/ ) {
  21882. console.warn( 'Abstract function.' );
  21883. }
  21884. updateAfter( /*frame*/ ) {
  21885. console.warn( 'Abstract function.' );
  21886. }
  21887. update( /*frame*/ ) {
  21888. console.warn( 'Abstract function.' );
  21889. }
  21890. build( builder, output = null ) {
  21891. const refNode = this.getShared( builder );
  21892. if ( this !== refNode ) {
  21893. return refNode.build( builder, output );
  21894. }
  21895. builder.addNode( this );
  21896. builder.addChain( this );
  21897. /* Build stages expected results:
  21898. - "setup" -> Node
  21899. - "analyze" -> null
  21900. - "generate" -> String
  21901. */
  21902. let result = null;
  21903. const buildStage = builder.getBuildStage();
  21904. if ( buildStage === 'setup' ) {
  21905. this.updateReference( builder );
  21906. const properties = builder.getNodeProperties( this );
  21907. if ( properties.initialized !== true ) {
  21908. const stackNodesBeforeSetup = builder.stack.nodes.length;
  21909. properties.initialized = true;
  21910. properties.outputNode = this.setup( builder );
  21911. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  21912. for ( const childNode of Object.values( properties ) ) {
  21913. if ( childNode && childNode.isNode === true ) {
  21914. childNode.build( builder );
  21915. }
  21916. }
  21917. }
  21918. } else if ( buildStage === 'analyze' ) {
  21919. this.analyze( builder );
  21920. } else if ( buildStage === 'generate' ) {
  21921. const isGenerateOnce = this.generate.length === 1;
  21922. if ( isGenerateOnce ) {
  21923. const type = this.getNodeType( builder );
  21924. const nodeData = builder.getDataFromNode( this );
  21925. result = nodeData.snippet;
  21926. if ( result === undefined ) {
  21927. result = this.generate( builder ) || '';
  21928. nodeData.snippet = result;
  21929. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  21930. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  21931. }
  21932. result = builder.format( result, type, output );
  21933. } else {
  21934. result = this.generate( builder, output ) || '';
  21935. }
  21936. }
  21937. builder.removeChain( this );
  21938. return result;
  21939. }
  21940. getSerializeChildren() {
  21941. return getNodeChildren( this );
  21942. }
  21943. serialize( json ) {
  21944. const nodeChildren = this.getSerializeChildren();
  21945. const inputNodes = {};
  21946. for ( const { property, index, childNode } of nodeChildren ) {
  21947. if ( index !== undefined ) {
  21948. if ( inputNodes[ property ] === undefined ) {
  21949. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  21950. }
  21951. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  21952. } else {
  21953. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  21954. }
  21955. }
  21956. if ( Object.keys( inputNodes ).length > 0 ) {
  21957. json.inputNodes = inputNodes;
  21958. }
  21959. }
  21960. deserialize( json ) {
  21961. if ( json.inputNodes !== undefined ) {
  21962. const nodes = json.meta.nodes;
  21963. for ( const property in json.inputNodes ) {
  21964. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  21965. const inputArray = [];
  21966. for ( const uuid of json.inputNodes[ property ] ) {
  21967. inputArray.push( nodes[ uuid ] );
  21968. }
  21969. this[ property ] = inputArray;
  21970. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  21971. const inputObject = {};
  21972. for ( const subProperty in json.inputNodes[ property ] ) {
  21973. const uuid = json.inputNodes[ property ][ subProperty ];
  21974. inputObject[ subProperty ] = nodes[ uuid ];
  21975. }
  21976. this[ property ] = inputObject;
  21977. } else {
  21978. const uuid = json.inputNodes[ property ];
  21979. this[ property ] = nodes[ uuid ];
  21980. }
  21981. }
  21982. }
  21983. }
  21984. toJSON( meta ) {
  21985. const { uuid, type } = this;
  21986. const isRoot = ( meta === undefined || typeof meta === 'string' );
  21987. if ( isRoot ) {
  21988. meta = {
  21989. textures: {},
  21990. images: {},
  21991. nodes: {}
  21992. };
  21993. }
  21994. // serialize
  21995. let data = meta.nodes[ uuid ];
  21996. if ( data === undefined ) {
  21997. data = {
  21998. uuid,
  21999. type,
  22000. meta,
  22001. metadata: {
  22002. version: 4.6,
  22003. type: 'Node',
  22004. generator: 'Node.toJSON'
  22005. }
  22006. };
  22007. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22008. this.serialize( data );
  22009. delete data.meta;
  22010. }
  22011. // TODO: Copied from Object3D.toJSON
  22012. function extractFromCache( cache ) {
  22013. const values = [];
  22014. for ( const key in cache ) {
  22015. const data = cache[ key ];
  22016. delete data.metadata;
  22017. values.push( data );
  22018. }
  22019. return values;
  22020. }
  22021. if ( isRoot ) {
  22022. const textures = extractFromCache( meta.textures );
  22023. const images = extractFromCache( meta.images );
  22024. const nodes = extractFromCache( meta.nodes );
  22025. if ( textures.length > 0 ) data.textures = textures;
  22026. if ( images.length > 0 ) data.images = images;
  22027. if ( nodes.length > 0 ) data.nodes = nodes;
  22028. }
  22029. return data;
  22030. }
  22031. }
  22032. class ArrayElementNode extends Node {
  22033. static get type() {
  22034. return 'ArrayElementNode';
  22035. } // @TODO: If extending from TempNode it breaks webgpu_compute
  22036. constructor( node, indexNode ) {
  22037. super();
  22038. this.node = node;
  22039. this.indexNode = indexNode;
  22040. this.isArrayElementNode = true;
  22041. }
  22042. getNodeType( builder ) {
  22043. return this.node.getElementType( builder );
  22044. }
  22045. generate( builder ) {
  22046. const nodeSnippet = this.node.build( builder );
  22047. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22048. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22049. }
  22050. }
  22051. class ConvertNode extends Node {
  22052. static get type() {
  22053. return 'ConvertNode';
  22054. }
  22055. constructor( node, convertTo ) {
  22056. super();
  22057. this.node = node;
  22058. this.convertTo = convertTo;
  22059. }
  22060. getNodeType( builder ) {
  22061. const requestType = this.node.getNodeType( builder );
  22062. let convertTo = null;
  22063. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22064. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22065. convertTo = overloadingType;
  22066. }
  22067. }
  22068. return convertTo;
  22069. }
  22070. serialize( data ) {
  22071. super.serialize( data );
  22072. data.convertTo = this.convertTo;
  22073. }
  22074. deserialize( data ) {
  22075. super.deserialize( data );
  22076. this.convertTo = data.convertTo;
  22077. }
  22078. generate( builder, output ) {
  22079. const node = this.node;
  22080. const type = this.getNodeType( builder );
  22081. const snippet = node.build( builder, type );
  22082. return builder.format( snippet, type, output );
  22083. }
  22084. }
  22085. class TempNode extends Node {
  22086. static get type() {
  22087. return 'TempNode';
  22088. }
  22089. constructor( type ) {
  22090. super( type );
  22091. this.isTempNode = true;
  22092. }
  22093. hasDependencies( builder ) {
  22094. return builder.getDataFromNode( this ).usageCount > 1;
  22095. }
  22096. build( builder, output ) {
  22097. const buildStage = builder.getBuildStage();
  22098. if ( buildStage === 'generate' ) {
  22099. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22100. const nodeData = builder.getDataFromNode( this );
  22101. if ( nodeData.propertyName !== undefined ) {
  22102. return builder.format( nodeData.propertyName, type, output );
  22103. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22104. const snippet = super.build( builder, type );
  22105. const nodeVar = builder.getVarFromNode( this, null, type );
  22106. const propertyName = builder.getPropertyName( nodeVar );
  22107. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  22108. nodeData.snippet = snippet;
  22109. nodeData.propertyName = propertyName;
  22110. return builder.format( nodeData.propertyName, type, output );
  22111. }
  22112. }
  22113. return super.build( builder, output );
  22114. }
  22115. }
  22116. class JoinNode extends TempNode {
  22117. static get type() {
  22118. return 'JoinNode';
  22119. }
  22120. constructor( nodes = [], nodeType = null ) {
  22121. super( nodeType );
  22122. this.nodes = nodes;
  22123. }
  22124. getNodeType( builder ) {
  22125. if ( this.nodeType !== null ) {
  22126. return builder.getVectorType( this.nodeType );
  22127. }
  22128. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22129. }
  22130. generate( builder, output ) {
  22131. const type = this.getNodeType( builder );
  22132. const nodes = this.nodes;
  22133. const primitiveType = builder.getComponentType( type );
  22134. const snippetValues = [];
  22135. for ( const input of nodes ) {
  22136. let inputSnippet = input.build( builder );
  22137. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22138. if ( inputPrimitiveType !== primitiveType ) {
  22139. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22140. }
  22141. snippetValues.push( inputSnippet );
  22142. }
  22143. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22144. return builder.format( snippet, type, output );
  22145. }
  22146. }
  22147. const stringVectorComponents = vectorComponents.join( '' );
  22148. class SplitNode extends Node {
  22149. static get type() {
  22150. return 'SplitNode';
  22151. }
  22152. constructor( node, components = 'x' ) {
  22153. super();
  22154. this.node = node;
  22155. this.components = components;
  22156. this.isSplitNode = true;
  22157. }
  22158. getVectorLength() {
  22159. let vectorLength = this.components.length;
  22160. for ( const c of this.components ) {
  22161. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22162. }
  22163. return vectorLength;
  22164. }
  22165. getComponentType( builder ) {
  22166. return builder.getComponentType( this.node.getNodeType( builder ) );
  22167. }
  22168. getNodeType( builder ) {
  22169. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22170. }
  22171. generate( builder, output ) {
  22172. const node = this.node;
  22173. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22174. let snippet = null;
  22175. if ( nodeTypeLength > 1 ) {
  22176. let type = null;
  22177. const componentsLength = this.getVectorLength();
  22178. if ( componentsLength >= nodeTypeLength ) {
  22179. // needed expand the input node
  22180. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22181. }
  22182. const nodeSnippet = node.build( builder, type );
  22183. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22184. // unnecessary swizzle
  22185. snippet = builder.format( nodeSnippet, type, output );
  22186. } else {
  22187. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22188. }
  22189. } else {
  22190. // ignore .components if .node returns float/integer
  22191. snippet = node.build( builder, output );
  22192. }
  22193. return snippet;
  22194. }
  22195. serialize( data ) {
  22196. super.serialize( data );
  22197. data.components = this.components;
  22198. }
  22199. deserialize( data ) {
  22200. super.deserialize( data );
  22201. this.components = data.components;
  22202. }
  22203. }
  22204. class SetNode extends TempNode {
  22205. static get type() {
  22206. return 'SetNode';
  22207. }
  22208. constructor( sourceNode, components, targetNode ) {
  22209. super();
  22210. this.sourceNode = sourceNode;
  22211. this.components = components;
  22212. this.targetNode = targetNode;
  22213. }
  22214. getNodeType( builder ) {
  22215. return this.sourceNode.getNodeType( builder );
  22216. }
  22217. generate( builder ) {
  22218. const { sourceNode, components, targetNode } = this;
  22219. const sourceType = this.getNodeType( builder );
  22220. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  22221. const targetSnippet = targetNode.build( builder, targetType );
  22222. const sourceSnippet = sourceNode.build( builder, sourceType );
  22223. const length = builder.getTypeLength( sourceType );
  22224. const snippetValues = [];
  22225. for ( let i = 0; i < length; i ++ ) {
  22226. const component = vectorComponents[ i ];
  22227. if ( component === components[ 0 ] ) {
  22228. snippetValues.push( targetSnippet );
  22229. i += components.length - 1;
  22230. } else {
  22231. snippetValues.push( sourceSnippet + '.' + component );
  22232. }
  22233. }
  22234. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22235. }
  22236. }
  22237. class FlipNode extends TempNode {
  22238. static get type() {
  22239. return 'FlipNode';
  22240. }
  22241. constructor( sourceNode, components ) {
  22242. super();
  22243. this.sourceNode = sourceNode;
  22244. this.components = components;
  22245. }
  22246. getNodeType( builder ) {
  22247. return this.sourceNode.getNodeType( builder );
  22248. }
  22249. generate( builder ) {
  22250. const { components, sourceNode } = this;
  22251. const sourceType = this.getNodeType( builder );
  22252. const sourceSnippet = sourceNode.build( builder );
  22253. const sourceCache = builder.getVarFromNode( this );
  22254. const sourceProperty = builder.getPropertyName( sourceCache );
  22255. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  22256. const length = builder.getTypeLength( sourceType );
  22257. const snippetValues = [];
  22258. let componentIndex = 0;
  22259. for ( let i = 0; i < length; i ++ ) {
  22260. const component = vectorComponents[ i ];
  22261. if ( component === components[ componentIndex ] ) {
  22262. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  22263. componentIndex ++;
  22264. } else {
  22265. snippetValues.push( sourceProperty + '.' + component );
  22266. }
  22267. }
  22268. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22269. }
  22270. }
  22271. class InputNode extends Node {
  22272. static get type() {
  22273. return 'InputNode';
  22274. }
  22275. constructor( value, nodeType = null ) {
  22276. super( nodeType );
  22277. this.isInputNode = true;
  22278. this.value = value;
  22279. this.precision = null;
  22280. }
  22281. getNodeType( /*builder*/ ) {
  22282. if ( this.nodeType === null ) {
  22283. return getValueType( this.value );
  22284. }
  22285. return this.nodeType;
  22286. }
  22287. getInputType( builder ) {
  22288. return this.getNodeType( builder );
  22289. }
  22290. setPrecision( precision ) {
  22291. this.precision = precision;
  22292. return this;
  22293. }
  22294. serialize( data ) {
  22295. super.serialize( data );
  22296. data.value = this.value;
  22297. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22298. data.valueType = getValueType( this.value );
  22299. data.nodeType = this.nodeType;
  22300. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22301. data.precision = this.precision;
  22302. }
  22303. deserialize( data ) {
  22304. super.deserialize( data );
  22305. this.nodeType = data.nodeType;
  22306. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22307. this.precision = data.precision || null;
  22308. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22309. }
  22310. generate( /*builder, output*/ ) {
  22311. console.warn( 'Abstract function.' );
  22312. }
  22313. }
  22314. class ConstNode extends InputNode {
  22315. static get type() {
  22316. return 'ConstNode';
  22317. }
  22318. constructor( value, nodeType = null ) {
  22319. super( value, nodeType );
  22320. this.isConstNode = true;
  22321. }
  22322. generateConst( builder ) {
  22323. return builder.generateConst( this.getNodeType( builder ), this.value );
  22324. }
  22325. generate( builder, output ) {
  22326. const type = this.getNodeType( builder );
  22327. return builder.format( this.generateConst( builder ), type, output );
  22328. }
  22329. }
  22330. //
  22331. let currentStack = null;
  22332. const NodeElements = new Map();
  22333. function addMethodChaining( name, nodeElement ) {
  22334. if ( NodeElements.has( name ) ) {
  22335. console.warn( `Redefinition of method chaining ${ name }` );
  22336. return;
  22337. }
  22338. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22339. NodeElements.set( name, nodeElement );
  22340. }
  22341. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22342. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22343. const shaderNodeHandler = {
  22344. setup( NodeClosure, params ) {
  22345. const inputs = params.shift();
  22346. return NodeClosure( nodeObjects( inputs ), ...params );
  22347. },
  22348. get( node, prop, nodeObj ) {
  22349. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22350. if ( node.isStackNode !== true && prop === 'assign' ) {
  22351. return ( ...params ) => {
  22352. currentStack.assign( nodeObj, ...params );
  22353. return nodeObj;
  22354. };
  22355. } else if ( NodeElements.has( prop ) ) {
  22356. const nodeElement = NodeElements.get( prop );
  22357. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22358. } else if ( prop === 'self' ) {
  22359. return node;
  22360. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22361. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22362. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22363. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22364. // accessing properties ( swizzle )
  22365. prop = parseSwizzle( prop );
  22366. return nodeObject( new SplitNode( nodeObj, prop ) );
  22367. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22368. // set properties ( swizzle ) and sort to xyzw sequence
  22369. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22370. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22371. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22372. // set properties ( swizzle ) and sort to xyzw sequence
  22373. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22374. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22375. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22376. // accessing property
  22377. if ( prop === 'width' ) prop = 'x';
  22378. else if ( prop === 'height' ) prop = 'y';
  22379. else if ( prop === 'depth' ) prop = 'z';
  22380. return nodeObject( new SplitNode( node, prop ) );
  22381. } else if ( /^\d+$/.test( prop ) === true ) {
  22382. // accessing array
  22383. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22384. }
  22385. }
  22386. return Reflect.get( node, prop, nodeObj );
  22387. },
  22388. set( node, prop, value, nodeObj ) {
  22389. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22390. // setting properties
  22391. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22392. nodeObj[ prop ].assign( value );
  22393. return true;
  22394. }
  22395. }
  22396. return Reflect.set( node, prop, value, nodeObj );
  22397. }
  22398. };
  22399. const nodeObjectsCacheMap = new WeakMap();
  22400. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22401. const ShaderNodeObject = function ( obj, altType = null ) {
  22402. const type = getValueType( obj );
  22403. if ( type === 'node' ) {
  22404. let nodeObject = nodeObjectsCacheMap.get( obj );
  22405. if ( nodeObject === undefined ) {
  22406. nodeObject = new Proxy( obj, shaderNodeHandler );
  22407. nodeObjectsCacheMap.set( obj, nodeObject );
  22408. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22409. }
  22410. return nodeObject;
  22411. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22412. return nodeObject( getConstNode( obj, altType ) );
  22413. } else if ( type === 'shader' ) {
  22414. return Fn( obj );
  22415. }
  22416. return obj;
  22417. };
  22418. const ShaderNodeObjects = function ( objects, altType = null ) {
  22419. for ( const name in objects ) {
  22420. objects[ name ] = nodeObject( objects[ name ], altType );
  22421. }
  22422. return objects;
  22423. };
  22424. const ShaderNodeArray = function ( array, altType = null ) {
  22425. const len = array.length;
  22426. for ( let i = 0; i < len; i ++ ) {
  22427. array[ i ] = nodeObject( array[ i ], altType );
  22428. }
  22429. return array;
  22430. };
  22431. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22432. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22433. if ( scope === null ) {
  22434. return ( ...params ) => {
  22435. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22436. };
  22437. } else if ( factor !== null ) {
  22438. factor = nodeObject( factor );
  22439. return ( ...params ) => {
  22440. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22441. };
  22442. } else {
  22443. return ( ...params ) => {
  22444. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22445. };
  22446. }
  22447. };
  22448. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22449. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22450. };
  22451. class ShaderCallNodeInternal extends Node {
  22452. constructor( shaderNode, inputNodes ) {
  22453. super();
  22454. this.shaderNode = shaderNode;
  22455. this.inputNodes = inputNodes;
  22456. }
  22457. getNodeType( builder ) {
  22458. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22459. }
  22460. call( builder ) {
  22461. const { shaderNode, inputNodes } = this;
  22462. const properties = builder.getNodeProperties( shaderNode );
  22463. if ( properties.onceOutput ) return properties.onceOutput;
  22464. //
  22465. let result = null;
  22466. if ( shaderNode.layout ) {
  22467. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22468. if ( functionNodesCacheMap === undefined ) {
  22469. functionNodesCacheMap = new WeakMap();
  22470. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22471. }
  22472. let functionNode = functionNodesCacheMap.get( shaderNode );
  22473. if ( functionNode === undefined ) {
  22474. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22475. functionNodesCacheMap.set( shaderNode, functionNode );
  22476. }
  22477. if ( builder.currentFunctionNode !== null ) {
  22478. builder.currentFunctionNode.includes.push( functionNode );
  22479. }
  22480. result = nodeObject( functionNode.call( inputNodes ) );
  22481. } else {
  22482. const jsFunc = shaderNode.jsFunc;
  22483. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22484. result = nodeObject( outputNode );
  22485. }
  22486. if ( shaderNode.once ) {
  22487. properties.onceOutput = result;
  22488. }
  22489. return result;
  22490. }
  22491. getOutputNode( builder ) {
  22492. const properties = builder.getNodeProperties( this );
  22493. if ( properties.outputNode === null ) {
  22494. properties.outputNode = this.setupOutput( builder );
  22495. }
  22496. return properties.outputNode;
  22497. }
  22498. setup( builder ) {
  22499. return this.getOutputNode( builder );
  22500. }
  22501. setupOutput( builder ) {
  22502. builder.addStack();
  22503. builder.stack.outputNode = this.call( builder );
  22504. return builder.removeStack();
  22505. }
  22506. generate( builder, output ) {
  22507. const outputNode = this.getOutputNode( builder );
  22508. return outputNode.build( builder, output );
  22509. }
  22510. }
  22511. class ShaderNodeInternal extends Node {
  22512. constructor( jsFunc, nodeType ) {
  22513. super( nodeType );
  22514. this.jsFunc = jsFunc;
  22515. this.layout = null;
  22516. this.global = true;
  22517. this.once = false;
  22518. }
  22519. setLayout( layout ) {
  22520. this.layout = layout;
  22521. return this;
  22522. }
  22523. call( inputs = null ) {
  22524. nodeObjects( inputs );
  22525. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22526. }
  22527. setup() {
  22528. return this.call();
  22529. }
  22530. }
  22531. const bools = [ false, true ];
  22532. const uints = [ 0, 1, 2, 3 ];
  22533. const ints = [ - 1, - 2 ];
  22534. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  22535. const boolsCacheMap = new Map();
  22536. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22537. const uintsCacheMap = new Map();
  22538. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22539. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22540. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22541. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22542. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22543. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22544. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22545. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22546. const getConstNode = ( value, type ) => {
  22547. if ( constNodesCacheMap.has( value ) ) {
  22548. return constNodesCacheMap.get( value );
  22549. } else if ( value.isNode === true ) {
  22550. return value;
  22551. } else {
  22552. return new ConstNode( value, type );
  22553. }
  22554. };
  22555. const safeGetNodeType = ( node ) => {
  22556. try {
  22557. return node.getNodeType();
  22558. } catch ( _ ) {
  22559. return undefined;
  22560. }
  22561. };
  22562. const ConvertType = function ( type, cacheMap = null ) {
  22563. return ( ...params ) => {
  22564. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22565. params = [ getValueFromType( type, ...params ) ];
  22566. }
  22567. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22568. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22569. }
  22570. if ( params.length === 1 ) {
  22571. const node = getConstNode( params[ 0 ], type );
  22572. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22573. return nodeObject( new ConvertNode( node, type ) );
  22574. }
  22575. const nodes = params.map( param => getConstNode( param ) );
  22576. return nodeObject( new JoinNode( nodes, type ) );
  22577. };
  22578. };
  22579. // exports
  22580. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22581. // utils
  22582. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22583. // shader node base
  22584. function ShaderNode( jsFunc, nodeType ) {
  22585. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22586. }
  22587. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22588. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22589. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22590. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22591. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22592. const Fn = ( jsFunc, nodeType ) => {
  22593. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22594. const fn = ( ...params ) => {
  22595. let inputs;
  22596. nodeObjects( params );
  22597. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22598. inputs = [ ...params ];
  22599. } else {
  22600. inputs = params[ 0 ];
  22601. }
  22602. return shaderNode.call( inputs );
  22603. };
  22604. fn.shaderNode = shaderNode;
  22605. fn.setLayout = ( layout ) => {
  22606. shaderNode.setLayout( layout );
  22607. return fn;
  22608. };
  22609. fn.once = () => {
  22610. shaderNode.once = true;
  22611. return fn;
  22612. };
  22613. return fn;
  22614. };
  22615. const tslFn = ( ...params ) => { // @deprecated, r168
  22616. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22617. return Fn( ...params );
  22618. };
  22619. //
  22620. addMethodChaining( 'toGlobal', ( node ) => {
  22621. node.global = true;
  22622. return node;
  22623. } );
  22624. //
  22625. const setCurrentStack = ( stack ) => {
  22626. currentStack = stack;
  22627. };
  22628. const getCurrentStack = () => currentStack;
  22629. const If = ( ...params ) => currentStack.If( ...params );
  22630. function append( node ) {
  22631. if ( currentStack ) currentStack.add( node );
  22632. return node;
  22633. }
  22634. addMethodChaining( 'append', append );
  22635. // types
  22636. const color = new ConvertType( 'color' );
  22637. const float = new ConvertType( 'float', cacheMaps.float );
  22638. const int = new ConvertType( 'int', cacheMaps.ints );
  22639. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22640. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22641. const vec2 = new ConvertType( 'vec2' );
  22642. const ivec2 = new ConvertType( 'ivec2' );
  22643. const uvec2 = new ConvertType( 'uvec2' );
  22644. const bvec2 = new ConvertType( 'bvec2' );
  22645. const vec3 = new ConvertType( 'vec3' );
  22646. const ivec3 = new ConvertType( 'ivec3' );
  22647. const uvec3 = new ConvertType( 'uvec3' );
  22648. const bvec3 = new ConvertType( 'bvec3' );
  22649. const vec4 = new ConvertType( 'vec4' );
  22650. const ivec4 = new ConvertType( 'ivec4' );
  22651. const uvec4 = new ConvertType( 'uvec4' );
  22652. const bvec4 = new ConvertType( 'bvec4' );
  22653. const mat2 = new ConvertType( 'mat2' );
  22654. const mat3 = new ConvertType( 'mat3' );
  22655. const mat4 = new ConvertType( 'mat4' );
  22656. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22657. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22658. addMethodChaining( 'toColor', color );
  22659. addMethodChaining( 'toFloat', float );
  22660. addMethodChaining( 'toInt', int );
  22661. addMethodChaining( 'toUint', uint );
  22662. addMethodChaining( 'toBool', bool );
  22663. addMethodChaining( 'toVec2', vec2 );
  22664. addMethodChaining( 'toIVec2', ivec2 );
  22665. addMethodChaining( 'toUVec2', uvec2 );
  22666. addMethodChaining( 'toBVec2', bvec2 );
  22667. addMethodChaining( 'toVec3', vec3 );
  22668. addMethodChaining( 'toIVec3', ivec3 );
  22669. addMethodChaining( 'toUVec3', uvec3 );
  22670. addMethodChaining( 'toBVec3', bvec3 );
  22671. addMethodChaining( 'toVec4', vec4 );
  22672. addMethodChaining( 'toIVec4', ivec4 );
  22673. addMethodChaining( 'toUVec4', uvec4 );
  22674. addMethodChaining( 'toBVec4', bvec4 );
  22675. addMethodChaining( 'toMat2', mat2 );
  22676. addMethodChaining( 'toMat3', mat3 );
  22677. addMethodChaining( 'toMat4', mat4 );
  22678. // basic nodes
  22679. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22680. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22681. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22682. addMethodChaining( 'element', element );
  22683. addMethodChaining( 'convert', convert );
  22684. class UniformGroupNode extends Node {
  22685. static get type() {
  22686. return 'UniformGroupNode';
  22687. }
  22688. constructor( name, shared = false, order = 1 ) {
  22689. super( 'string' );
  22690. this.name = name;
  22691. this.version = 0;
  22692. this.shared = shared;
  22693. this.order = order;
  22694. this.isUniformGroup = true;
  22695. }
  22696. set needsUpdate( value ) {
  22697. if ( value === true ) this.version ++;
  22698. }
  22699. serialize( data ) {
  22700. super.serialize( data );
  22701. data.name = this.name;
  22702. data.version = this.version;
  22703. data.shared = this.shared;
  22704. }
  22705. deserialize( data ) {
  22706. super.deserialize( data );
  22707. this.name = data.name;
  22708. this.version = data.version;
  22709. this.shared = data.shared;
  22710. }
  22711. }
  22712. const uniformGroup = ( name ) => new UniformGroupNode( name );
  22713. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  22714. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  22715. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  22716. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  22717. class UniformNode extends InputNode {
  22718. static get type() {
  22719. return 'UniformNode';
  22720. }
  22721. constructor( value, nodeType = null ) {
  22722. super( value, nodeType );
  22723. this.isUniformNode = true;
  22724. this.name = '';
  22725. this.groupNode = objectGroup;
  22726. }
  22727. label( name ) {
  22728. this.name = name;
  22729. return this;
  22730. }
  22731. setGroup( group ) {
  22732. this.groupNode = group;
  22733. return this;
  22734. }
  22735. getGroup() {
  22736. return this.groupNode;
  22737. }
  22738. getUniformHash( builder ) {
  22739. return this.getHash( builder );
  22740. }
  22741. onUpdate( callback, updateType ) {
  22742. const self = this.getSelf();
  22743. callback = callback.bind( self );
  22744. return super.onUpdate( ( frame ) => {
  22745. const value = callback( frame, self );
  22746. if ( value !== undefined ) {
  22747. this.value = value;
  22748. }
  22749. }, updateType );
  22750. }
  22751. generate( builder, output ) {
  22752. const type = this.getNodeType( builder );
  22753. const hash = this.getUniformHash( builder );
  22754. let sharedNode = builder.getNodeFromHash( hash );
  22755. if ( sharedNode === undefined ) {
  22756. builder.setHashNode( this, hash );
  22757. sharedNode = this;
  22758. }
  22759. const sharedNodeType = sharedNode.getInputType( builder );
  22760. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  22761. const propertyName = builder.getPropertyName( nodeUniform );
  22762. if ( builder.context.label !== undefined ) delete builder.context.label;
  22763. return builder.format( propertyName, type, output );
  22764. }
  22765. }
  22766. const uniform = ( arg1, arg2 ) => {
  22767. const nodeType = getConstNodeType( arg2 || arg1 );
  22768. // @TODO: get ConstNode from .traverse() in the future
  22769. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  22770. return nodeObject( new UniformNode( value, nodeType ) );
  22771. };
  22772. class PropertyNode extends Node {
  22773. static get type() {
  22774. return 'PropertyNode';
  22775. }
  22776. constructor( nodeType, name = null, varying = false ) {
  22777. super( nodeType );
  22778. this.name = name;
  22779. this.varying = varying;
  22780. this.isPropertyNode = true;
  22781. }
  22782. getHash( builder ) {
  22783. return this.name || super.getHash( builder );
  22784. }
  22785. isGlobal( /*builder*/ ) {
  22786. return true;
  22787. }
  22788. generate( builder ) {
  22789. let nodeVar;
  22790. if ( this.varying === true ) {
  22791. nodeVar = builder.getVaryingFromNode( this, this.name );
  22792. nodeVar.needsInterpolation = true;
  22793. } else {
  22794. nodeVar = builder.getVarFromNode( this, this.name );
  22795. }
  22796. return builder.getPropertyName( nodeVar );
  22797. }
  22798. }
  22799. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  22800. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  22801. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  22802. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  22803. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  22804. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  22805. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  22806. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  22807. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  22808. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  22809. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  22810. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  22811. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  22812. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  22813. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  22814. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  22815. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  22816. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  22817. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  22818. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  22819. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  22820. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  22821. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  22822. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  22823. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  22824. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  22825. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  22826. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  22827. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  22828. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  22829. class AssignNode extends TempNode {
  22830. static get type() {
  22831. return 'AssignNode';
  22832. }
  22833. constructor( targetNode, sourceNode ) {
  22834. super();
  22835. this.targetNode = targetNode;
  22836. this.sourceNode = sourceNode;
  22837. }
  22838. hasDependencies() {
  22839. return false;
  22840. }
  22841. getNodeType( builder, output ) {
  22842. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  22843. }
  22844. needsSplitAssign( builder ) {
  22845. const { targetNode } = this;
  22846. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  22847. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  22848. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  22849. return assignDiferentVector;
  22850. }
  22851. return false;
  22852. }
  22853. generate( builder, output ) {
  22854. const { targetNode, sourceNode } = this;
  22855. const needsSplitAssign = this.needsSplitAssign( builder );
  22856. const targetType = targetNode.getNodeType( builder );
  22857. const target = targetNode.context( { assign: true } ).build( builder );
  22858. const source = sourceNode.build( builder, targetType );
  22859. const sourceType = sourceNode.getNodeType( builder );
  22860. const nodeData = builder.getDataFromNode( this );
  22861. //
  22862. let snippet;
  22863. if ( nodeData.initialized === true ) {
  22864. if ( output !== 'void' ) {
  22865. snippet = target;
  22866. }
  22867. } else if ( needsSplitAssign ) {
  22868. const sourceVar = builder.getVarFromNode( this, null, targetType );
  22869. const sourceProperty = builder.getPropertyName( sourceVar );
  22870. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  22871. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  22872. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  22873. const component = targetNode.components[ i ];
  22874. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  22875. }
  22876. if ( output !== 'void' ) {
  22877. snippet = target;
  22878. }
  22879. } else {
  22880. snippet = `${ target } = ${ source }`;
  22881. if ( output === 'void' || sourceType === 'void' ) {
  22882. builder.addLineFlowCode( snippet, this );
  22883. if ( output !== 'void' ) {
  22884. snippet = target;
  22885. }
  22886. }
  22887. }
  22888. nodeData.initialized = true;
  22889. return builder.format( snippet, targetType, output );
  22890. }
  22891. }
  22892. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  22893. addMethodChaining( 'assign', assign );
  22894. class FunctionCallNode extends TempNode {
  22895. static get type() {
  22896. return 'FunctionCallNode';
  22897. }
  22898. constructor( functionNode = null, parameters = {} ) {
  22899. super();
  22900. this.functionNode = functionNode;
  22901. this.parameters = parameters;
  22902. }
  22903. setParameters( parameters ) {
  22904. this.parameters = parameters;
  22905. return this;
  22906. }
  22907. getParameters() {
  22908. return this.parameters;
  22909. }
  22910. getNodeType( builder ) {
  22911. return this.functionNode.getNodeType( builder );
  22912. }
  22913. generate( builder ) {
  22914. const params = [];
  22915. const functionNode = this.functionNode;
  22916. const inputs = functionNode.getInputs( builder );
  22917. const parameters = this.parameters;
  22918. if ( Array.isArray( parameters ) ) {
  22919. for ( let i = 0; i < parameters.length; i ++ ) {
  22920. const inputNode = inputs[ i ];
  22921. const node = parameters[ i ];
  22922. params.push( node.build( builder, inputNode.type ) );
  22923. }
  22924. } else {
  22925. for ( const inputNode of inputs ) {
  22926. const node = parameters[ inputNode.name ];
  22927. if ( node !== undefined ) {
  22928. params.push( node.build( builder, inputNode.type ) );
  22929. } else {
  22930. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  22931. }
  22932. }
  22933. }
  22934. const functionName = functionNode.build( builder, 'property' );
  22935. return `${functionName}( ${params.join( ', ' )} )`;
  22936. }
  22937. }
  22938. const call = ( func, ...params ) => {
  22939. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  22940. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  22941. };
  22942. addMethodChaining( 'call', call );
  22943. class OperatorNode extends TempNode {
  22944. static get type() {
  22945. return 'OperatorNode';
  22946. }
  22947. constructor( op, aNode, bNode, ...params ) {
  22948. super();
  22949. if ( params.length > 0 ) {
  22950. let finalOp = new OperatorNode( op, aNode, bNode );
  22951. for ( let i = 0; i < params.length - 1; i ++ ) {
  22952. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  22953. }
  22954. aNode = finalOp;
  22955. bNode = params[ params.length - 1 ];
  22956. }
  22957. this.op = op;
  22958. this.aNode = aNode;
  22959. this.bNode = bNode;
  22960. }
  22961. getNodeType( builder, output ) {
  22962. const op = this.op;
  22963. const aNode = this.aNode;
  22964. const bNode = this.bNode;
  22965. const typeA = aNode.getNodeType( builder );
  22966. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  22967. if ( typeA === 'void' || typeB === 'void' ) {
  22968. return 'void';
  22969. } else if ( op === '%' ) {
  22970. return typeA;
  22971. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  22972. return builder.getIntegerType( typeA );
  22973. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  22974. return 'bool';
  22975. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  22976. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  22977. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  22978. } else {
  22979. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  22980. return typeB;
  22981. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  22982. // matrix x vector
  22983. return builder.getVectorFromMatrix( typeA );
  22984. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  22985. // vector x matrix
  22986. return builder.getVectorFromMatrix( typeB );
  22987. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  22988. // anytype x anytype: use the greater length vector
  22989. return typeB;
  22990. }
  22991. return typeA;
  22992. }
  22993. }
  22994. generate( builder, output ) {
  22995. const op = this.op;
  22996. const aNode = this.aNode;
  22997. const bNode = this.bNode;
  22998. const type = this.getNodeType( builder, output );
  22999. let typeA = null;
  23000. let typeB = null;
  23001. if ( type !== 'void' ) {
  23002. typeA = aNode.getNodeType( builder );
  23003. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23004. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  23005. if ( builder.isVector( typeA ) ) {
  23006. typeB = typeA;
  23007. } else if ( typeA !== typeB ) {
  23008. typeA = typeB = 'float';
  23009. }
  23010. } else if ( op === '>>' || op === '<<' ) {
  23011. typeA = type;
  23012. typeB = builder.changeComponentType( typeB, 'uint' );
  23013. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23014. // matrix x vector
  23015. typeB = builder.getVectorFromMatrix( typeA );
  23016. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23017. // vector x matrix
  23018. typeA = builder.getVectorFromMatrix( typeB );
  23019. } else {
  23020. // anytype x anytype
  23021. typeA = typeB = type;
  23022. }
  23023. } else {
  23024. typeA = typeB = type;
  23025. }
  23026. const a = aNode.build( builder, typeA );
  23027. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  23028. const outputLength = builder.getTypeLength( output );
  23029. const fnOpSnippet = builder.getFunctionOperator( op );
  23030. if ( output !== 'void' ) {
  23031. if ( op === '<' && outputLength > 1 ) {
  23032. if ( builder.useComparisonMethod ) {
  23033. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  23034. } else {
  23035. return builder.format( `( ${ a } < ${ b } )`, type, output );
  23036. }
  23037. } else if ( op === '<=' && outputLength > 1 ) {
  23038. if ( builder.useComparisonMethod ) {
  23039. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23040. } else {
  23041. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  23042. }
  23043. } else if ( op === '>' && outputLength > 1 ) {
  23044. if ( builder.useComparisonMethod ) {
  23045. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  23046. } else {
  23047. return builder.format( `( ${ a } > ${ b } )`, type, output );
  23048. }
  23049. } else if ( op === '>=' && outputLength > 1 ) {
  23050. if ( builder.useComparisonMethod ) {
  23051. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23052. } else {
  23053. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  23054. }
  23055. } else if ( op === '!' || op === '~' ) {
  23056. return builder.format( `(${op}${a})`, typeA, output );
  23057. } else if ( fnOpSnippet ) {
  23058. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23059. } else {
  23060. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  23061. }
  23062. } else if ( typeA !== 'void' ) {
  23063. if ( fnOpSnippet ) {
  23064. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23065. } else {
  23066. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  23067. }
  23068. }
  23069. }
  23070. serialize( data ) {
  23071. super.serialize( data );
  23072. data.op = this.op;
  23073. }
  23074. deserialize( data ) {
  23075. super.deserialize( data );
  23076. this.op = data.op;
  23077. }
  23078. }
  23079. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  23080. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  23081. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  23082. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  23083. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  23084. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  23085. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  23086. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  23087. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  23088. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  23089. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  23090. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  23091. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  23092. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  23093. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  23094. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  23095. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  23096. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  23097. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  23098. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  23099. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  23100. addMethodChaining( 'add', add );
  23101. addMethodChaining( 'sub', sub );
  23102. addMethodChaining( 'mul', mul );
  23103. addMethodChaining( 'div', div );
  23104. addMethodChaining( 'modInt', modInt );
  23105. addMethodChaining( 'equal', equal );
  23106. addMethodChaining( 'notEqual', notEqual );
  23107. addMethodChaining( 'lessThan', lessThan );
  23108. addMethodChaining( 'greaterThan', greaterThan );
  23109. addMethodChaining( 'lessThanEqual', lessThanEqual );
  23110. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  23111. addMethodChaining( 'and', and );
  23112. addMethodChaining( 'or', or );
  23113. addMethodChaining( 'not', not );
  23114. addMethodChaining( 'xor', xor );
  23115. addMethodChaining( 'bitAnd', bitAnd );
  23116. addMethodChaining( 'bitNot', bitNot );
  23117. addMethodChaining( 'bitOr', bitOr );
  23118. addMethodChaining( 'bitXor', bitXor );
  23119. addMethodChaining( 'shiftLeft', shiftLeft );
  23120. addMethodChaining( 'shiftRight', shiftRight );
  23121. const remainder = ( ...params ) => { // @deprecated, r168
  23122. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  23123. return modInt( ...params );
  23124. };
  23125. addMethodChaining( 'remainder', remainder );
  23126. class MathNode extends TempNode {
  23127. static get type() {
  23128. return 'MathNode';
  23129. }
  23130. constructor( method, aNode, bNode = null, cNode = null ) {
  23131. super();
  23132. this.method = method;
  23133. this.aNode = aNode;
  23134. this.bNode = bNode;
  23135. this.cNode = cNode;
  23136. }
  23137. getInputType( builder ) {
  23138. const aType = this.aNode.getNodeType( builder );
  23139. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  23140. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  23141. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  23142. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  23143. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  23144. if ( aLen > bLen && aLen > cLen ) {
  23145. return aType;
  23146. } else if ( bLen > cLen ) {
  23147. return bType;
  23148. } else if ( cLen > aLen ) {
  23149. return cType;
  23150. }
  23151. return aType;
  23152. }
  23153. getNodeType( builder ) {
  23154. const method = this.method;
  23155. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  23156. return 'float';
  23157. } else if ( method === MathNode.CROSS ) {
  23158. return 'vec3';
  23159. } else if ( method === MathNode.ALL ) {
  23160. return 'bool';
  23161. } else if ( method === MathNode.EQUALS ) {
  23162. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  23163. } else if ( method === MathNode.MOD ) {
  23164. return this.aNode.getNodeType( builder );
  23165. } else {
  23166. return this.getInputType( builder );
  23167. }
  23168. }
  23169. generate( builder, output ) {
  23170. const method = this.method;
  23171. const type = this.getNodeType( builder );
  23172. const inputType = this.getInputType( builder );
  23173. const a = this.aNode;
  23174. const b = this.bNode;
  23175. const c = this.cNode;
  23176. const isWebGL = builder.renderer.isWebGLRenderer === true;
  23177. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  23178. // dir can be either a direction vector or a normal vector
  23179. // upper-left 3x3 of matrix is assumed to be orthogonal
  23180. let tA = a;
  23181. let tB = b;
  23182. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  23183. tB = vec4( vec3( tB ), 0.0 );
  23184. } else {
  23185. tA = vec4( vec3( tA ), 0.0 );
  23186. }
  23187. const mulNode = mul( tA, tB ).xyz;
  23188. return normalize( mulNode ).build( builder, output );
  23189. } else if ( method === MathNode.NEGATE ) {
  23190. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  23191. } else if ( method === MathNode.ONE_MINUS ) {
  23192. return sub( 1.0, a ).build( builder, output );
  23193. } else if ( method === MathNode.RECIPROCAL ) {
  23194. return div( 1.0, a ).build( builder, output );
  23195. } else if ( method === MathNode.DIFFERENCE ) {
  23196. return abs( sub( a, b ) ).build( builder, output );
  23197. } else {
  23198. const params = [];
  23199. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  23200. params.push(
  23201. a.build( builder, type ),
  23202. b.build( builder, type )
  23203. );
  23204. } else if ( isWebGL && method === MathNode.STEP ) {
  23205. params.push(
  23206. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  23207. b.build( builder, inputType )
  23208. );
  23209. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  23210. params.push(
  23211. a.build( builder, inputType ),
  23212. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23213. );
  23214. } else if ( method === MathNode.REFRACT ) {
  23215. params.push(
  23216. a.build( builder, inputType ),
  23217. b.build( builder, inputType ),
  23218. c.build( builder, 'float' )
  23219. );
  23220. } else if ( method === MathNode.MIX ) {
  23221. params.push(
  23222. a.build( builder, inputType ),
  23223. b.build( builder, inputType ),
  23224. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23225. );
  23226. } else {
  23227. params.push( a.build( builder, inputType ) );
  23228. if ( b !== null ) params.push( b.build( builder, inputType ) );
  23229. if ( c !== null ) params.push( c.build( builder, inputType ) );
  23230. }
  23231. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  23232. }
  23233. }
  23234. serialize( data ) {
  23235. super.serialize( data );
  23236. data.method = this.method;
  23237. }
  23238. deserialize( data ) {
  23239. super.deserialize( data );
  23240. this.method = data.method;
  23241. }
  23242. }
  23243. // 1 input
  23244. MathNode.ALL = 'all';
  23245. MathNode.ANY = 'any';
  23246. MathNode.EQUALS = 'equals';
  23247. MathNode.RADIANS = 'radians';
  23248. MathNode.DEGREES = 'degrees';
  23249. MathNode.EXP = 'exp';
  23250. MathNode.EXP2 = 'exp2';
  23251. MathNode.LOG = 'log';
  23252. MathNode.LOG2 = 'log2';
  23253. MathNode.SQRT = 'sqrt';
  23254. MathNode.INVERSE_SQRT = 'inversesqrt';
  23255. MathNode.FLOOR = 'floor';
  23256. MathNode.CEIL = 'ceil';
  23257. MathNode.NORMALIZE = 'normalize';
  23258. MathNode.FRACT = 'fract';
  23259. MathNode.SIN = 'sin';
  23260. MathNode.COS = 'cos';
  23261. MathNode.TAN = 'tan';
  23262. MathNode.ASIN = 'asin';
  23263. MathNode.ACOS = 'acos';
  23264. MathNode.ATAN = 'atan';
  23265. MathNode.ABS = 'abs';
  23266. MathNode.SIGN = 'sign';
  23267. MathNode.LENGTH = 'length';
  23268. MathNode.NEGATE = 'negate';
  23269. MathNode.ONE_MINUS = 'oneMinus';
  23270. MathNode.DFDX = 'dFdx';
  23271. MathNode.DFDY = 'dFdy';
  23272. MathNode.ROUND = 'round';
  23273. MathNode.RECIPROCAL = 'reciprocal';
  23274. MathNode.TRUNC = 'trunc';
  23275. MathNode.FWIDTH = 'fwidth';
  23276. MathNode.BITCAST = 'bitcast';
  23277. MathNode.TRANSPOSE = 'transpose';
  23278. // 2 inputs
  23279. MathNode.ATAN2 = 'atan2';
  23280. MathNode.MIN = 'min';
  23281. MathNode.MAX = 'max';
  23282. MathNode.MOD = 'mod';
  23283. MathNode.STEP = 'step';
  23284. MathNode.REFLECT = 'reflect';
  23285. MathNode.DISTANCE = 'distance';
  23286. MathNode.DIFFERENCE = 'difference';
  23287. MathNode.DOT = 'dot';
  23288. MathNode.CROSS = 'cross';
  23289. MathNode.POW = 'pow';
  23290. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23291. // 3 inputs
  23292. MathNode.MIX = 'mix';
  23293. MathNode.CLAMP = 'clamp';
  23294. MathNode.REFRACT = 'refract';
  23295. MathNode.SMOOTHSTEP = 'smoothstep';
  23296. MathNode.FACEFORWARD = 'faceforward';
  23297. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23298. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23299. const PI = /*@__PURE__*/ float( Math.PI );
  23300. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23301. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23302. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23303. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23304. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23305. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23306. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23307. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23308. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23309. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23310. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23311. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23312. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23313. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23314. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23315. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23316. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23317. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23318. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23319. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23320. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23321. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23322. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23323. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23324. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23325. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23326. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23327. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23328. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23329. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23330. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23331. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23332. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23333. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23334. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23335. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23336. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23337. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23338. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23339. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23340. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23341. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23342. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23343. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23344. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23345. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23346. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23347. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23348. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23349. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23350. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23351. const lengthSq = ( a ) => dot( a, a );
  23352. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23353. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23354. const saturate = ( value ) => clamp( value );
  23355. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23356. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23357. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23358. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23359. const a = 12.9898, b = 78.233, c = 43758.5453;
  23360. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23361. return fract( sin( sn ).mul( c ) );
  23362. } );
  23363. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23364. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23365. addMethodChaining( 'all', all );
  23366. addMethodChaining( 'any', any );
  23367. addMethodChaining( 'equals', equals );
  23368. addMethodChaining( 'radians', radians );
  23369. addMethodChaining( 'degrees', degrees );
  23370. addMethodChaining( 'exp', exp );
  23371. addMethodChaining( 'exp2', exp2 );
  23372. addMethodChaining( 'log', log );
  23373. addMethodChaining( 'log2', log2 );
  23374. addMethodChaining( 'sqrt', sqrt );
  23375. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23376. addMethodChaining( 'floor', floor );
  23377. addMethodChaining( 'ceil', ceil );
  23378. addMethodChaining( 'normalize', normalize );
  23379. addMethodChaining( 'fract', fract );
  23380. addMethodChaining( 'sin', sin );
  23381. addMethodChaining( 'cos', cos );
  23382. addMethodChaining( 'tan', tan );
  23383. addMethodChaining( 'asin', asin );
  23384. addMethodChaining( 'acos', acos );
  23385. addMethodChaining( 'atan', atan );
  23386. addMethodChaining( 'abs', abs );
  23387. addMethodChaining( 'sign', sign );
  23388. addMethodChaining( 'length', length );
  23389. addMethodChaining( 'lengthSq', lengthSq );
  23390. addMethodChaining( 'negate', negate );
  23391. addMethodChaining( 'oneMinus', oneMinus );
  23392. addMethodChaining( 'dFdx', dFdx );
  23393. addMethodChaining( 'dFdy', dFdy );
  23394. addMethodChaining( 'round', round );
  23395. addMethodChaining( 'reciprocal', reciprocal );
  23396. addMethodChaining( 'trunc', trunc );
  23397. addMethodChaining( 'fwidth', fwidth );
  23398. addMethodChaining( 'atan2', atan2 );
  23399. addMethodChaining( 'min', min$1 );
  23400. addMethodChaining( 'max', max$1 );
  23401. addMethodChaining( 'mod', mod );
  23402. addMethodChaining( 'step', step );
  23403. addMethodChaining( 'reflect', reflect );
  23404. addMethodChaining( 'distance', distance );
  23405. addMethodChaining( 'dot', dot );
  23406. addMethodChaining( 'cross', cross );
  23407. addMethodChaining( 'pow', pow );
  23408. addMethodChaining( 'pow2', pow2 );
  23409. addMethodChaining( 'pow3', pow3 );
  23410. addMethodChaining( 'pow4', pow4 );
  23411. addMethodChaining( 'transformDirection', transformDirection );
  23412. addMethodChaining( 'mix', mixElement );
  23413. addMethodChaining( 'clamp', clamp );
  23414. addMethodChaining( 'refract', refract );
  23415. addMethodChaining( 'smoothstep', smoothstepElement );
  23416. addMethodChaining( 'faceForward', faceForward );
  23417. addMethodChaining( 'difference', difference );
  23418. addMethodChaining( 'saturate', saturate );
  23419. addMethodChaining( 'cbrt', cbrt );
  23420. addMethodChaining( 'transpose', transpose );
  23421. addMethodChaining( 'rand', rand );
  23422. class ConditionalNode extends Node {
  23423. static get type() {
  23424. return 'ConditionalNode';
  23425. }
  23426. constructor( condNode, ifNode, elseNode = null ) {
  23427. super();
  23428. this.condNode = condNode;
  23429. this.ifNode = ifNode;
  23430. this.elseNode = elseNode;
  23431. }
  23432. getNodeType( builder ) {
  23433. const ifType = this.ifNode.getNodeType( builder );
  23434. if ( this.elseNode !== null ) {
  23435. const elseType = this.elseNode.getNodeType( builder );
  23436. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23437. return elseType;
  23438. }
  23439. }
  23440. return ifType;
  23441. }
  23442. setup( builder ) {
  23443. const condNode = this.condNode.cache();
  23444. const ifNode = this.ifNode.cache();
  23445. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  23446. //
  23447. const currentNodeBlock = builder.context.nodeBlock;
  23448. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  23449. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  23450. //
  23451. const properties = builder.getNodeProperties( this );
  23452. properties.condNode = condNode;
  23453. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  23454. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  23455. }
  23456. generate( builder, output ) {
  23457. const type = this.getNodeType( builder );
  23458. const nodeData = builder.getDataFromNode( this );
  23459. if ( nodeData.nodeProperty !== undefined ) {
  23460. return nodeData.nodeProperty;
  23461. }
  23462. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23463. const needsOutput = output !== 'void';
  23464. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23465. nodeData.nodeProperty = nodeProperty;
  23466. const nodeSnippet = condNode.build( builder, 'bool' );
  23467. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23468. let ifSnippet = ifNode.build( builder, type );
  23469. if ( ifSnippet ) {
  23470. if ( needsOutput ) {
  23471. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23472. } else {
  23473. ifSnippet = 'return ' + ifSnippet + ';';
  23474. }
  23475. }
  23476. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23477. if ( elseNode !== null ) {
  23478. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23479. let elseSnippet = elseNode.build( builder, type );
  23480. if ( elseSnippet ) {
  23481. if ( needsOutput ) {
  23482. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23483. } else {
  23484. elseSnippet = 'return ' + elseSnippet + ';';
  23485. }
  23486. }
  23487. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23488. } else {
  23489. builder.addFlowCode( '\n\n' );
  23490. }
  23491. return builder.format( nodeProperty, type, output );
  23492. }
  23493. }
  23494. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23495. addMethodChaining( 'select', select );
  23496. //
  23497. const cond = ( ...params ) => { // @deprecated, r168
  23498. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23499. return select( ...params );
  23500. };
  23501. addMethodChaining( 'cond', cond );
  23502. class ContextNode extends Node {
  23503. static get type() {
  23504. return 'ContextNode';
  23505. }
  23506. constructor( node, value = {} ) {
  23507. super();
  23508. this.isContextNode = true;
  23509. this.node = node;
  23510. this.value = value;
  23511. }
  23512. getScope() {
  23513. return this.node.getScope();
  23514. }
  23515. getNodeType( builder ) {
  23516. return this.node.getNodeType( builder );
  23517. }
  23518. analyze( builder ) {
  23519. this.node.build( builder );
  23520. }
  23521. setup( builder ) {
  23522. const previousContext = builder.getContext();
  23523. builder.setContext( { ...builder.context, ...this.value } );
  23524. const node = this.node.build( builder );
  23525. builder.setContext( previousContext );
  23526. return node;
  23527. }
  23528. generate( builder, output ) {
  23529. const previousContext = builder.getContext();
  23530. builder.setContext( { ...builder.context, ...this.value } );
  23531. const snippet = this.node.build( builder, output );
  23532. builder.setContext( previousContext );
  23533. return snippet;
  23534. }
  23535. }
  23536. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23537. const label = ( node, name ) => context( node, { label: name } );
  23538. addMethodChaining( 'context', context );
  23539. addMethodChaining( 'label', label );
  23540. class VarNode extends Node {
  23541. static get type() {
  23542. return 'VarNode';
  23543. }
  23544. constructor( node, name = null ) {
  23545. super();
  23546. this.node = node;
  23547. this.name = name;
  23548. this.global = true;
  23549. this.isVarNode = true;
  23550. }
  23551. getHash( builder ) {
  23552. return this.name || super.getHash( builder );
  23553. }
  23554. getNodeType( builder ) {
  23555. return this.node.getNodeType( builder );
  23556. }
  23557. generate( builder ) {
  23558. const { node, name } = this;
  23559. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23560. const propertyName = builder.getPropertyName( nodeVar );
  23561. const snippet = node.build( builder, nodeVar.type );
  23562. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  23563. return propertyName;
  23564. }
  23565. }
  23566. const temp = /*@__PURE__*/ nodeProxy( VarNode );
  23567. addMethodChaining( 'temp', temp ); // @TODO: Will be removed in the future
  23568. addMethodChaining( 'toVar', ( ...params ) => temp( ...params ).append() );
  23569. class VaryingNode extends Node {
  23570. static get type() {
  23571. return 'VaryingNode';
  23572. }
  23573. constructor( node, name = null ) {
  23574. super();
  23575. this.node = node;
  23576. this.name = name;
  23577. this.isVaryingNode = true;
  23578. }
  23579. isGlobal() {
  23580. return true;
  23581. }
  23582. getHash( builder ) {
  23583. return this.name || super.getHash( builder );
  23584. }
  23585. getNodeType( builder ) {
  23586. // VaryingNode is auto type
  23587. return this.node.getNodeType( builder );
  23588. }
  23589. setupVarying( builder ) {
  23590. const properties = builder.getNodeProperties( this );
  23591. let varying = properties.varying;
  23592. if ( varying === undefined ) {
  23593. const name = this.name;
  23594. const type = this.getNodeType( builder );
  23595. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23596. properties.node = this.node;
  23597. }
  23598. // this property can be used to check if the varying can be optimized for a variable
  23599. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23600. return varying;
  23601. }
  23602. setup( builder ) {
  23603. this.setupVarying( builder );
  23604. }
  23605. analyze( builder ) {
  23606. this.setupVarying( builder );
  23607. return this.node.analyze( builder );
  23608. }
  23609. generate( builder ) {
  23610. const properties = builder.getNodeProperties( this );
  23611. const varying = this.setupVarying( builder );
  23612. if ( properties.propertyName === undefined ) {
  23613. const type = this.getNodeType( builder );
  23614. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23615. // force node run in vertex stage
  23616. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23617. properties.propertyName = propertyName;
  23618. }
  23619. return builder.getPropertyName( varying );
  23620. }
  23621. }
  23622. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23623. addMethodChaining( 'varying', varying );
  23624. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  23625. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  23626. function getColorSpaceName( colorSpace ) {
  23627. let method = null;
  23628. if ( colorSpace === LinearSRGBColorSpace ) {
  23629. method = 'Linear';
  23630. } else if ( colorSpace === SRGBColorSpace ) {
  23631. method = 'sRGB';
  23632. }
  23633. return method;
  23634. }
  23635. function getColorSpaceMethod( source, target ) {
  23636. return getColorSpaceName( source ) + 'To' + getColorSpaceName( target );
  23637. }
  23638. class ColorSpaceNode extends TempNode {
  23639. static get type() {
  23640. return 'ColorSpaceNode';
  23641. }
  23642. constructor( colorNode, source, target ) {
  23643. super( 'vec4' );
  23644. this.colorNode = colorNode;
  23645. this.source = source;
  23646. this.target = target;
  23647. }
  23648. getColorSpace( builder, colorSpace ) {
  23649. if ( colorSpace === WORKING_COLOR_SPACE ) {
  23650. return ColorManagement.workingColorSpace;
  23651. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  23652. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  23653. }
  23654. return colorSpace;
  23655. }
  23656. setup( builder ) {
  23657. const { renderer } = builder;
  23658. const { colorNode } = this;
  23659. const source = this.getColorSpace( builder, this.source );
  23660. const target = this.getColorSpace( builder, this.target );
  23661. if ( source === target ) return colorNode;
  23662. const colorSpace = getColorSpaceMethod( source, target );
  23663. let outputNode = null;
  23664. const colorSpaceFn = renderer.nodes.library.getColorSpaceFunction( colorSpace );
  23665. if ( colorSpaceFn !== null ) {
  23666. outputNode = vec4( colorSpaceFn( colorNode.rgb ), colorNode.a );
  23667. } else {
  23668. console.error( 'ColorSpaceNode: Unsupported Color Space configuration.', colorSpace );
  23669. outputNode = colorNode;
  23670. }
  23671. return outputNode;
  23672. }
  23673. }
  23674. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  23675. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  23676. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  23677. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  23678. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23679. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  23680. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  23681. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  23682. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  23683. static get type() {
  23684. return 'ReferenceElementNode';
  23685. }
  23686. constructor( referenceNode, indexNode ) {
  23687. super( referenceNode, indexNode );
  23688. this.referenceNode = referenceNode;
  23689. this.isReferenceElementNode = true;
  23690. }
  23691. getNodeType() {
  23692. return this.referenceNode.uniformType;
  23693. }
  23694. generate( builder ) {
  23695. const snippet = super.generate( builder );
  23696. const arrayType = this.referenceNode.getNodeType();
  23697. const elementType = this.getNodeType();
  23698. return builder.format( snippet, arrayType, elementType );
  23699. }
  23700. };
  23701. class ReferenceBaseNode extends Node {
  23702. static get type() {
  23703. return 'ReferenceBaseNode';
  23704. }
  23705. constructor( property, uniformType, object = null, count = null ) {
  23706. super();
  23707. this.property = property;
  23708. this.uniformType = uniformType;
  23709. this.object = object;
  23710. this.count = count;
  23711. this.properties = property.split( '.' );
  23712. this.reference = object;
  23713. this.node = null;
  23714. this.group = null;
  23715. this.updateType = NodeUpdateType.OBJECT;
  23716. }
  23717. setGroup( group ) {
  23718. this.group = group;
  23719. return this;
  23720. }
  23721. element( indexNode ) {
  23722. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  23723. }
  23724. setNodeType( uniformType ) {
  23725. const node = uniform( null, uniformType ).getSelf();
  23726. if ( this.group !== null ) {
  23727. node.setGroup( this.group );
  23728. }
  23729. this.node = node;
  23730. }
  23731. getNodeType( builder ) {
  23732. if ( this.node === null ) {
  23733. this.updateReference( builder );
  23734. this.updateValue();
  23735. }
  23736. return this.node.getNodeType( builder );
  23737. }
  23738. getValueFromReference( object = this.reference ) {
  23739. const { properties } = this;
  23740. let value = object[ properties[ 0 ] ];
  23741. for ( let i = 1; i < properties.length; i ++ ) {
  23742. value = value[ properties[ i ] ];
  23743. }
  23744. return value;
  23745. }
  23746. updateReference( state ) {
  23747. this.reference = this.object !== null ? this.object : state.object;
  23748. return this.reference;
  23749. }
  23750. setup() {
  23751. this.updateValue();
  23752. return this.node;
  23753. }
  23754. update( /*frame*/ ) {
  23755. this.updateValue();
  23756. }
  23757. updateValue() {
  23758. if ( this.node === null ) this.setNodeType( this.uniformType );
  23759. const value = this.getValueFromReference();
  23760. if ( Array.isArray( value ) ) {
  23761. this.node.array = value;
  23762. } else {
  23763. this.node.value = value;
  23764. }
  23765. }
  23766. }
  23767. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  23768. class RendererReferenceNode extends ReferenceBaseNode {
  23769. static get type() {
  23770. return 'RendererReferenceNode';
  23771. }
  23772. constructor( property, inputType, renderer = null ) {
  23773. super( property, inputType, renderer );
  23774. this.renderer = renderer;
  23775. this.setGroup( renderGroup );
  23776. }
  23777. updateReference( state ) {
  23778. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  23779. return this.reference;
  23780. }
  23781. }
  23782. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  23783. class ToneMappingNode extends TempNode {
  23784. static get type() {
  23785. return 'ToneMappingNode';
  23786. }
  23787. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  23788. super( 'vec3' );
  23789. this.toneMapping = toneMapping;
  23790. this.exposureNode = exposureNode;
  23791. this.colorNode = colorNode;
  23792. }
  23793. getCacheKey() {
  23794. return hash$1( super.getCacheKey(), this.toneMapping );
  23795. }
  23796. setup( builder ) {
  23797. const colorNode = this.colorNode || builder.context.color;
  23798. const toneMapping = this.toneMapping;
  23799. if ( toneMapping === NoToneMapping ) return colorNode;
  23800. let outputNode = null;
  23801. const toneMappingFn = builder.renderer.nodes.library.getToneMappingFunction( toneMapping );
  23802. if ( toneMappingFn !== null ) {
  23803. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  23804. } else {
  23805. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  23806. outputNode = colorNode;
  23807. }
  23808. return outputNode;
  23809. }
  23810. }
  23811. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  23812. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  23813. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  23814. class BufferAttributeNode extends InputNode {
  23815. static get type() {
  23816. return 'BufferAttributeNode';
  23817. }
  23818. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  23819. super( value, bufferType );
  23820. this.isBufferNode = true;
  23821. this.bufferType = bufferType;
  23822. this.bufferStride = bufferStride;
  23823. this.bufferOffset = bufferOffset;
  23824. this.usage = StaticDrawUsage;
  23825. this.instanced = false;
  23826. this.attribute = null;
  23827. this.global = true;
  23828. if ( value && value.isBufferAttribute === true ) {
  23829. this.attribute = value;
  23830. this.usage = value.usage;
  23831. this.instanced = value.isInstancedBufferAttribute;
  23832. }
  23833. }
  23834. getHash( builder ) {
  23835. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  23836. let bufferData = builder.globalCache.getData( this.value );
  23837. if ( bufferData === undefined ) {
  23838. bufferData = {
  23839. node: this
  23840. };
  23841. builder.globalCache.setData( this.value, bufferData );
  23842. }
  23843. return bufferData.node.uuid;
  23844. }
  23845. return this.uuid;
  23846. }
  23847. getNodeType( builder ) {
  23848. if ( this.bufferType === null ) {
  23849. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  23850. }
  23851. return this.bufferType;
  23852. }
  23853. setup( builder ) {
  23854. if ( this.attribute !== null ) return;
  23855. const type = this.getNodeType( builder );
  23856. const array = this.value;
  23857. const itemSize = builder.getTypeLength( type );
  23858. const stride = this.bufferStride || itemSize;
  23859. const offset = this.bufferOffset;
  23860. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  23861. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  23862. buffer.setUsage( this.usage );
  23863. this.attribute = bufferAttribute;
  23864. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  23865. }
  23866. generate( builder ) {
  23867. const nodeType = this.getNodeType( builder );
  23868. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  23869. const propertyName = builder.getPropertyName( nodeAttribute );
  23870. let output = null;
  23871. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23872. this.name = propertyName;
  23873. output = propertyName;
  23874. } else {
  23875. const nodeVarying = varying( this );
  23876. output = nodeVarying.build( builder, nodeType );
  23877. }
  23878. return output;
  23879. }
  23880. getInputType( /*builder*/ ) {
  23881. return 'bufferAttribute';
  23882. }
  23883. setUsage( value ) {
  23884. this.usage = value;
  23885. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  23886. this.attribute.usage = value;
  23887. }
  23888. return this;
  23889. }
  23890. setInstanced( value ) {
  23891. this.instanced = value;
  23892. return this;
  23893. }
  23894. }
  23895. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  23896. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  23897. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  23898. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  23899. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  23900. class ComputeNode extends Node {
  23901. static get type() {
  23902. return 'ComputeNode';
  23903. }
  23904. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  23905. super( 'void' );
  23906. this.isComputeNode = true;
  23907. this.computeNode = computeNode;
  23908. this.count = count;
  23909. this.workgroupSize = workgroupSize;
  23910. this.dispatchCount = 0;
  23911. this.version = 1;
  23912. this.updateBeforeType = NodeUpdateType.OBJECT;
  23913. this.updateDispatchCount();
  23914. }
  23915. dispose() {
  23916. this.dispatchEvent( { type: 'dispose' } );
  23917. }
  23918. set needsUpdate( value ) {
  23919. if ( value === true ) this.version ++;
  23920. }
  23921. updateDispatchCount() {
  23922. const { count, workgroupSize } = this;
  23923. let size = workgroupSize[ 0 ];
  23924. for ( let i = 1; i < workgroupSize.length; i ++ )
  23925. size *= workgroupSize[ i ];
  23926. this.dispatchCount = Math.ceil( count / size );
  23927. }
  23928. onInit() { }
  23929. updateBefore( { renderer } ) {
  23930. renderer.compute( this );
  23931. }
  23932. generate( builder ) {
  23933. const { shaderStage } = builder;
  23934. if ( shaderStage === 'compute' ) {
  23935. const snippet = this.computeNode.build( builder, 'void' );
  23936. if ( snippet !== '' ) {
  23937. builder.addLineFlowCode( snippet, this );
  23938. }
  23939. }
  23940. }
  23941. }
  23942. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  23943. addMethodChaining( 'compute', compute );
  23944. class CacheNode extends Node {
  23945. static get type() {
  23946. return 'CacheNode';
  23947. }
  23948. constructor( node, parent = true ) {
  23949. super();
  23950. this.node = node;
  23951. this.parent = parent;
  23952. this.isCacheNode = true;
  23953. }
  23954. getNodeType( builder ) {
  23955. return this.node.getNodeType( builder );
  23956. }
  23957. build( builder, ...params ) {
  23958. const previousCache = builder.getCache();
  23959. const cache = builder.getCacheFromNode( this, this.parent );
  23960. builder.setCache( cache );
  23961. const data = this.node.build( builder, ...params );
  23962. builder.setCache( previousCache );
  23963. return data;
  23964. }
  23965. }
  23966. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23967. addMethodChaining( 'cache', cache );
  23968. class BypassNode extends Node {
  23969. static get type() {
  23970. return 'BypassNode';
  23971. }
  23972. constructor( returnNode, callNode ) {
  23973. super();
  23974. this.isBypassNode = true;
  23975. this.outputNode = returnNode;
  23976. this.callNode = callNode;
  23977. }
  23978. getNodeType( builder ) {
  23979. return this.outputNode.getNodeType( builder );
  23980. }
  23981. generate( builder ) {
  23982. const snippet = this.callNode.build( builder, 'void' );
  23983. if ( snippet !== '' ) {
  23984. builder.addLineFlowCode( snippet, this );
  23985. }
  23986. return this.outputNode.build( builder );
  23987. }
  23988. }
  23989. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  23990. addMethodChaining( 'bypass', bypass );
  23991. class RemapNode extends Node {
  23992. static get type() {
  23993. return 'RemapNode';
  23994. }
  23995. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  23996. super();
  23997. this.node = node;
  23998. this.inLowNode = inLowNode;
  23999. this.inHighNode = inHighNode;
  24000. this.outLowNode = outLowNode;
  24001. this.outHighNode = outHighNode;
  24002. this.doClamp = true;
  24003. }
  24004. setup() {
  24005. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  24006. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  24007. if ( doClamp === true ) t = t.clamp();
  24008. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  24009. }
  24010. }
  24011. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  24012. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  24013. addMethodChaining( 'remap', remap );
  24014. addMethodChaining( 'remapClamp', remapClamp );
  24015. class ExpressionNode extends Node {
  24016. static get type() {
  24017. return 'ExpressionNode';
  24018. }
  24019. constructor( snippet = '', nodeType = 'void' ) {
  24020. super( nodeType );
  24021. this.snippet = snippet;
  24022. }
  24023. generate( builder, output ) {
  24024. const type = this.getNodeType( builder );
  24025. const snippet = this.snippet;
  24026. if ( type === 'void' ) {
  24027. builder.addLineFlowCode( snippet, this );
  24028. } else {
  24029. return builder.format( `( ${ snippet } )`, type, output );
  24030. }
  24031. }
  24032. }
  24033. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  24034. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  24035. const Return = () => expression( 'return' ).append();
  24036. addMethodChaining( 'discard', Discard );
  24037. class RenderOutputNode extends TempNode {
  24038. static get type() {
  24039. return 'RenderOutputNode';
  24040. }
  24041. constructor( colorNode, toneMapping, outputColorSpace ) {
  24042. super( 'vec4' );
  24043. this.colorNode = colorNode;
  24044. this.toneMapping = toneMapping;
  24045. this.outputColorSpace = outputColorSpace;
  24046. this.isRenderOutput = true;
  24047. }
  24048. setup( { context } ) {
  24049. let outputNode = this.colorNode || context.color;
  24050. // tone mapping
  24051. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  24052. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  24053. if ( toneMapping !== NoToneMapping ) {
  24054. outputNode = outputNode.toneMapping( toneMapping );
  24055. }
  24056. // working to output color space
  24057. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  24058. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  24059. }
  24060. return outputNode;
  24061. }
  24062. }
  24063. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  24064. addMethodChaining( 'renderOutput', renderOutput );
  24065. // Non-PURE exports list, side-effects are required here.
  24066. // TSL Base Syntax
  24067. function addNodeElement( name/*, nodeElement*/ ) {
  24068. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  24069. }
  24070. class AttributeNode extends Node {
  24071. static get type() {
  24072. return 'AttributeNode';
  24073. }
  24074. constructor( attributeName, nodeType = null ) {
  24075. super( nodeType );
  24076. this.global = true;
  24077. this._attributeName = attributeName;
  24078. }
  24079. getHash( builder ) {
  24080. return this.getAttributeName( builder );
  24081. }
  24082. getNodeType( builder ) {
  24083. let nodeType = this.nodeType;
  24084. if ( nodeType === null ) {
  24085. const attributeName = this.getAttributeName( builder );
  24086. if ( builder.hasGeometryAttribute( attributeName ) ) {
  24087. const attribute = builder.geometry.getAttribute( attributeName );
  24088. nodeType = builder.getTypeFromAttribute( attribute );
  24089. } else {
  24090. nodeType = 'float';
  24091. }
  24092. }
  24093. return nodeType;
  24094. }
  24095. setAttributeName( attributeName ) {
  24096. this._attributeName = attributeName;
  24097. return this;
  24098. }
  24099. getAttributeName( /*builder*/ ) {
  24100. return this._attributeName;
  24101. }
  24102. generate( builder ) {
  24103. const attributeName = this.getAttributeName( builder );
  24104. const nodeType = this.getNodeType( builder );
  24105. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  24106. if ( geometryAttribute === true ) {
  24107. const attribute = builder.geometry.getAttribute( attributeName );
  24108. const attributeType = builder.getTypeFromAttribute( attribute );
  24109. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  24110. if ( builder.shaderStage === 'vertex' ) {
  24111. return builder.format( nodeAttribute.name, attributeType, nodeType );
  24112. } else {
  24113. const nodeVarying = varying( this );
  24114. return nodeVarying.build( builder, nodeType );
  24115. }
  24116. } else {
  24117. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  24118. return builder.generateConst( nodeType );
  24119. }
  24120. }
  24121. serialize( data ) {
  24122. super.serialize( data );
  24123. data.global = this.global;
  24124. data._attributeName = this._attributeName;
  24125. }
  24126. deserialize( data ) {
  24127. super.deserialize( data );
  24128. this.global = data.global;
  24129. this._attributeName = data._attributeName;
  24130. }
  24131. }
  24132. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  24133. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24134. class TextureSizeNode extends Node {
  24135. static get type() {
  24136. return 'TextureSizeNode';
  24137. }
  24138. constructor( textureNode, levelNode = null ) {
  24139. super( 'uvec2' );
  24140. this.isTextureSizeNode = true;
  24141. this.textureNode = textureNode;
  24142. this.levelNode = levelNode;
  24143. }
  24144. generate( builder, output ) {
  24145. const textureProperty = this.textureNode.build( builder, 'property' );
  24146. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  24147. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  24148. }
  24149. }
  24150. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  24151. class MaxMipLevelNode extends UniformNode {
  24152. static get type() {
  24153. return 'MaxMipLevelNode';
  24154. }
  24155. constructor( textureNode ) {
  24156. super( 0 );
  24157. this._textureNode = textureNode;
  24158. this.updateType = NodeUpdateType.FRAME;
  24159. }
  24160. get textureNode() {
  24161. return this._textureNode;
  24162. }
  24163. get texture() {
  24164. return this._textureNode.value;
  24165. }
  24166. update() {
  24167. const texture = this.texture;
  24168. const images = texture.images;
  24169. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24170. if ( image && image.width !== undefined ) {
  24171. const { width, height } = image;
  24172. this.value = Math.log2( Math.max( width, height ) );
  24173. }
  24174. }
  24175. }
  24176. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  24177. class TextureNode extends UniformNode {
  24178. static get type() {
  24179. return 'TextureNode';
  24180. }
  24181. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24182. super( value );
  24183. this.isTextureNode = true;
  24184. this.uvNode = uvNode;
  24185. this.levelNode = levelNode;
  24186. this.biasNode = biasNode;
  24187. this.compareNode = null;
  24188. this.depthNode = null;
  24189. this.gradNode = null;
  24190. this.sampler = true;
  24191. this.updateMatrix = false;
  24192. this.updateType = NodeUpdateType.NONE;
  24193. this.referenceNode = null;
  24194. this._value = value;
  24195. this._matrixUniform = null;
  24196. this.setUpdateMatrix( uvNode === null );
  24197. }
  24198. set value( value ) {
  24199. if ( this.referenceNode ) {
  24200. this.referenceNode.value = value;
  24201. } else {
  24202. this._value = value;
  24203. }
  24204. }
  24205. get value() {
  24206. return this.referenceNode ? this.referenceNode.value : this._value;
  24207. }
  24208. getUniformHash( /*builder*/ ) {
  24209. return this.value.uuid;
  24210. }
  24211. getNodeType( /*builder*/ ) {
  24212. if ( this.value.isDepthTexture === true ) return 'float';
  24213. if ( this.value.type === UnsignedIntType ) {
  24214. return 'uvec4';
  24215. } else if ( this.value.type === IntType ) {
  24216. return 'ivec4';
  24217. }
  24218. return 'vec4';
  24219. }
  24220. getInputType( /*builder*/ ) {
  24221. return 'texture';
  24222. }
  24223. getDefaultUV() {
  24224. return uv( this.value.channel );
  24225. }
  24226. updateReference( /*state*/ ) {
  24227. return this.value;
  24228. }
  24229. getTransformedUV( uvNode ) {
  24230. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24231. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24232. }
  24233. setUpdateMatrix( value ) {
  24234. this.updateMatrix = value;
  24235. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24236. return this;
  24237. }
  24238. setupUV( builder, uvNode ) {
  24239. const texture = this.value;
  24240. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24241. if ( this.sampler ) {
  24242. uvNode = uvNode.flipY();
  24243. } else {
  24244. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24245. }
  24246. }
  24247. return uvNode;
  24248. }
  24249. setup( builder ) {
  24250. const properties = builder.getNodeProperties( this );
  24251. properties.referenceNode = this.referenceNode;
  24252. //
  24253. let uvNode = this.uvNode;
  24254. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24255. uvNode = builder.context.getUV( this );
  24256. }
  24257. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24258. if ( this.updateMatrix === true ) {
  24259. uvNode = this.getTransformedUV( uvNode );
  24260. }
  24261. uvNode = this.setupUV( builder, uvNode );
  24262. //
  24263. let levelNode = this.levelNode;
  24264. if ( levelNode === null && builder.context.getTextureLevel ) {
  24265. levelNode = builder.context.getTextureLevel( this );
  24266. }
  24267. //
  24268. properties.uvNode = uvNode;
  24269. properties.levelNode = levelNode;
  24270. properties.biasNode = this.biasNode;
  24271. properties.compareNode = this.compareNode;
  24272. properties.gradNode = this.gradNode;
  24273. properties.depthNode = this.depthNode;
  24274. }
  24275. generateUV( builder, uvNode ) {
  24276. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24277. }
  24278. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24279. const texture = this.value;
  24280. let snippet;
  24281. if ( levelSnippet ) {
  24282. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24283. } else if ( biasSnippet ) {
  24284. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24285. } else if ( gradSnippet ) {
  24286. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24287. } else if ( compareSnippet ) {
  24288. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24289. } else if ( this.sampler === false ) {
  24290. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24291. } else {
  24292. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24293. }
  24294. return snippet;
  24295. }
  24296. generate( builder, output ) {
  24297. const properties = builder.getNodeProperties( this );
  24298. const texture = this.value;
  24299. if ( ! texture || texture.isTexture !== true ) {
  24300. throw new Error( 'TextureNode: Need a three.js texture.' );
  24301. }
  24302. const textureProperty = super.generate( builder, 'property' );
  24303. if ( output === 'sampler' ) {
  24304. return textureProperty + '_sampler';
  24305. } else if ( builder.isReference( output ) ) {
  24306. return textureProperty;
  24307. } else {
  24308. const nodeData = builder.getDataFromNode( this );
  24309. let propertyName = nodeData.propertyName;
  24310. if ( propertyName === undefined ) {
  24311. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24312. const uvSnippet = this.generateUV( builder, uvNode );
  24313. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24314. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24315. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24316. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24317. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24318. const nodeVar = builder.getVarFromNode( this );
  24319. propertyName = builder.getPropertyName( nodeVar );
  24320. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24321. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  24322. nodeData.snippet = snippet;
  24323. nodeData.propertyName = propertyName;
  24324. }
  24325. let snippet = propertyName;
  24326. const nodeType = this.getNodeType( builder );
  24327. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24328. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24329. }
  24330. return builder.format( snippet, nodeType, output );
  24331. }
  24332. }
  24333. setSampler( value ) {
  24334. this.sampler = value;
  24335. return this;
  24336. }
  24337. getSampler() {
  24338. return this.sampler;
  24339. }
  24340. // @TODO: Move to TSL
  24341. uv( uvNode ) {
  24342. const textureNode = this.clone();
  24343. textureNode.uvNode = nodeObject( uvNode );
  24344. textureNode.referenceNode = this.getSelf();
  24345. return nodeObject( textureNode );
  24346. }
  24347. blur( amountNode ) {
  24348. const textureNode = this.clone();
  24349. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24350. textureNode.referenceNode = this.getSelf();
  24351. return nodeObject( textureNode );
  24352. }
  24353. level( levelNode ) {
  24354. const textureNode = this.clone();
  24355. textureNode.levelNode = nodeObject( levelNode );
  24356. textureNode.referenceNode = this.getSelf();
  24357. return nodeObject( textureNode );
  24358. }
  24359. size( levelNode ) {
  24360. return textureSize( this, levelNode );
  24361. }
  24362. bias( biasNode ) {
  24363. const textureNode = this.clone();
  24364. textureNode.biasNode = nodeObject( biasNode );
  24365. textureNode.referenceNode = this.getSelf();
  24366. return nodeObject( textureNode );
  24367. }
  24368. compare( compareNode ) {
  24369. const textureNode = this.clone();
  24370. textureNode.compareNode = nodeObject( compareNode );
  24371. textureNode.referenceNode = this.getSelf();
  24372. return nodeObject( textureNode );
  24373. }
  24374. grad( gradNodeX, gradNodeY ) {
  24375. const textureNode = this.clone();
  24376. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24377. textureNode.referenceNode = this.getSelf();
  24378. return nodeObject( textureNode );
  24379. }
  24380. depth( depthNode ) {
  24381. const textureNode = this.clone();
  24382. textureNode.depthNode = nodeObject( depthNode );
  24383. textureNode.referenceNode = this.getSelf();
  24384. return nodeObject( textureNode );
  24385. }
  24386. // --
  24387. serialize( data ) {
  24388. super.serialize( data );
  24389. data.value = this.value.toJSON( data.meta ).uuid;
  24390. data.sampler = this.sampler;
  24391. data.updateMatrix = this.updateMatrix;
  24392. data.updateType = this.updateType;
  24393. }
  24394. deserialize( data ) {
  24395. super.deserialize( data );
  24396. this.value = data.meta.textures[ data.value ];
  24397. this.sampler = data.sampler;
  24398. this.updateMatrix = data.updateMatrix;
  24399. this.updateType = data.updateType;
  24400. }
  24401. update() {
  24402. const texture = this.value;
  24403. const matrixUniform = this._matrixUniform;
  24404. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24405. if ( texture.matrixAutoUpdate === true ) {
  24406. texture.updateMatrix();
  24407. }
  24408. }
  24409. clone() {
  24410. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24411. newNode.sampler = this.sampler;
  24412. return newNode;
  24413. }
  24414. }
  24415. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24416. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24417. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24418. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24419. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24420. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24421. const cameraLogDepth = /*@__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24422. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24423. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24424. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24425. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24426. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24427. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24428. class Object3DNode extends Node {
  24429. static get type() {
  24430. return 'Object3DNode';
  24431. }
  24432. constructor( scope, object3d = null ) {
  24433. super();
  24434. this.scope = scope;
  24435. this.object3d = object3d;
  24436. this.updateType = NodeUpdateType.OBJECT;
  24437. this._uniformNode = new UniformNode( null );
  24438. }
  24439. getNodeType() {
  24440. const scope = this.scope;
  24441. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24442. return 'mat4';
  24443. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24444. return 'vec3';
  24445. }
  24446. }
  24447. update( frame ) {
  24448. const object = this.object3d;
  24449. const uniformNode = this._uniformNode;
  24450. const scope = this.scope;
  24451. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24452. uniformNode.value = object.matrixWorld;
  24453. } else if ( scope === Object3DNode.POSITION ) {
  24454. uniformNode.value = uniformNode.value || new Vector3();
  24455. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24456. } else if ( scope === Object3DNode.SCALE ) {
  24457. uniformNode.value = uniformNode.value || new Vector3();
  24458. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24459. } else if ( scope === Object3DNode.DIRECTION ) {
  24460. uniformNode.value = uniformNode.value || new Vector3();
  24461. object.getWorldDirection( uniformNode.value );
  24462. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24463. const camera = frame.camera;
  24464. uniformNode.value = uniformNode.value || new Vector3();
  24465. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24466. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24467. }
  24468. }
  24469. generate( builder ) {
  24470. const scope = this.scope;
  24471. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24472. this._uniformNode.nodeType = 'mat4';
  24473. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24474. this._uniformNode.nodeType = 'vec3';
  24475. }
  24476. return this._uniformNode.build( builder );
  24477. }
  24478. serialize( data ) {
  24479. super.serialize( data );
  24480. data.scope = this.scope;
  24481. }
  24482. deserialize( data ) {
  24483. super.deserialize( data );
  24484. this.scope = data.scope;
  24485. }
  24486. }
  24487. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24488. Object3DNode.POSITION = 'position';
  24489. Object3DNode.SCALE = 'scale';
  24490. Object3DNode.VIEW_POSITION = 'viewPosition';
  24491. Object3DNode.DIRECTION = 'direction';
  24492. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24493. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24494. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24495. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24496. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24497. class ModelNode extends Object3DNode {
  24498. static get type() {
  24499. return 'ModelNode';
  24500. }
  24501. constructor( scope ) {
  24502. super( scope );
  24503. }
  24504. update( frame ) {
  24505. this.object3d = frame.object;
  24506. super.update( frame );
  24507. }
  24508. }
  24509. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24510. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24511. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24512. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24513. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24514. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  24515. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24516. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24517. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24518. builder.context.isHighPrecisionModelViewMatrix = true;
  24519. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24520. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24521. } );
  24522. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24523. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24524. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24525. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24526. if ( isHighPrecisionModelViewMatrix !== true ) {
  24527. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24528. }
  24529. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24530. } );
  24531. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24532. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24533. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24534. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24535. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24536. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24537. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24538. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24539. class FrontFacingNode extends Node {
  24540. static get type() {
  24541. return 'FrontFacingNode';
  24542. }
  24543. constructor() {
  24544. super( 'bool' );
  24545. this.isFrontFacingNode = true;
  24546. }
  24547. generate( builder ) {
  24548. const { renderer, material } = builder;
  24549. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24550. if ( material.side === BackSide ) {
  24551. return 'false';
  24552. }
  24553. }
  24554. return builder.getFrontFacing();
  24555. }
  24556. }
  24557. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24558. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24559. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24560. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24561. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24562. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24563. return vec3( 0, 1, 0 );
  24564. }
  24565. return normalGeometry;
  24566. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24567. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24568. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24569. let node;
  24570. if ( builder.material.flatShading === true ) {
  24571. node = normalFlat;
  24572. } else {
  24573. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24574. }
  24575. return node;
  24576. }, 'vec3' ).once() )().toVar( 'normalView' );
  24577. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24578. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24579. return builder.context.setupNormal();
  24580. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24581. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24582. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24583. return builder.context.setupClearcoatNormal();
  24584. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24585. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24586. const m = mat3( matrix );
  24587. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24588. return m.mul( transformedNormal ).xyz;
  24589. } );
  24590. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  24591. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  24592. if ( modelNormalViewMatrix !== null ) {
  24593. return modelNormalViewMatrix.transformDirection( normal );
  24594. }
  24595. //
  24596. const transformedNormal = modelNormalMatrix.mul( normal );
  24597. return cameraViewMatrix.transformDirection( transformedNormal );
  24598. } );
  24599. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24600. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24601. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24602. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24603. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24604. class CubeTextureNode extends TextureNode {
  24605. static get type() {
  24606. return 'CubeTextureNode';
  24607. }
  24608. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24609. super( value, uvNode, levelNode, biasNode );
  24610. this.isCubeTextureNode = true;
  24611. }
  24612. getInputType( /*builder*/ ) {
  24613. return 'cubeTexture';
  24614. }
  24615. getDefaultUV() {
  24616. const texture = this.value;
  24617. if ( texture.mapping === CubeReflectionMapping ) {
  24618. return reflectVector;
  24619. } else if ( texture.mapping === CubeRefractionMapping ) {
  24620. return refractVector;
  24621. } else {
  24622. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24623. return vec3( 0, 0, 0 );
  24624. }
  24625. }
  24626. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24627. setupUV( builder, uvNode ) {
  24628. const texture = this.value;
  24629. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24630. return vec3( uvNode.x.negate(), uvNode.yz );
  24631. } else {
  24632. return uvNode;
  24633. }
  24634. }
  24635. generateUV( builder, cubeUV ) {
  24636. return cubeUV.build( builder, 'vec3' );
  24637. }
  24638. }
  24639. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24640. class BufferNode extends UniformNode {
  24641. static get type() {
  24642. return 'BufferNode';
  24643. }
  24644. constructor( value, bufferType, bufferCount = 0 ) {
  24645. super( value, bufferType );
  24646. this.isBufferNode = true;
  24647. this.bufferType = bufferType;
  24648. this.bufferCount = bufferCount;
  24649. }
  24650. getElementType( builder ) {
  24651. return this.getNodeType( builder );
  24652. }
  24653. getInputType( /*builder*/ ) {
  24654. return 'buffer';
  24655. }
  24656. }
  24657. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24658. class UniformArrayElementNode extends ArrayElementNode {
  24659. static get type() {
  24660. return 'UniformArrayElementNode';
  24661. }
  24662. constructor( arrayBuffer, indexNode ) {
  24663. super( arrayBuffer, indexNode );
  24664. this.isArrayBufferElementNode = true;
  24665. }
  24666. generate( builder ) {
  24667. const snippet = super.generate( builder );
  24668. const type = this.getNodeType();
  24669. return builder.format( snippet, 'vec4', type );
  24670. }
  24671. }
  24672. class UniformArrayNode extends BufferNode {
  24673. static get type() {
  24674. return 'UniformArrayNode';
  24675. }
  24676. constructor( value, elementType = null ) {
  24677. super( null, 'vec4' );
  24678. this.array = value;
  24679. this.elementType = elementType;
  24680. this._elementType = null;
  24681. this._elementLength = 0;
  24682. this.updateType = NodeUpdateType.RENDER;
  24683. this.isArrayBufferNode = true;
  24684. }
  24685. getElementType() {
  24686. return this.elementType || this._elementType;
  24687. }
  24688. getElementLength() {
  24689. return this._elementLength;
  24690. }
  24691. update( /*frame*/ ) {
  24692. const { array, value } = this;
  24693. const elementLength = this.getElementLength();
  24694. const elementType = this.getElementType();
  24695. if ( elementLength === 1 ) {
  24696. for ( let i = 0; i < array.length; i ++ ) {
  24697. const index = i * 4;
  24698. value[ index ] = array[ i ];
  24699. }
  24700. } else if ( elementType === 'color' ) {
  24701. for ( let i = 0; i < array.length; i ++ ) {
  24702. const index = i * 4;
  24703. const vector = array[ i ];
  24704. value[ index ] = vector.r;
  24705. value[ index + 1 ] = vector.g;
  24706. value[ index + 2 ] = vector.b || 0;
  24707. //value[ index + 3 ] = vector.a || 0;
  24708. }
  24709. } else {
  24710. for ( let i = 0; i < array.length; i ++ ) {
  24711. const index = i * 4;
  24712. const vector = array[ i ];
  24713. value[ index ] = vector.x;
  24714. value[ index + 1 ] = vector.y;
  24715. value[ index + 2 ] = vector.z || 0;
  24716. value[ index + 3 ] = vector.w || 0;
  24717. }
  24718. }
  24719. }
  24720. setup( builder ) {
  24721. const length = this.array.length;
  24722. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24723. this._elementLength = builder.getTypeLength( this._elementType );
  24724. let arrayType = Float32Array;
  24725. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24726. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24727. this.value = new arrayType( length * 4 );
  24728. this.bufferCount = length;
  24729. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24730. return super.setup( builder );
  24731. }
  24732. element( indexNode ) {
  24733. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  24734. }
  24735. }
  24736. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  24737. //
  24738. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  24739. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  24740. return nodeObject( new UniformArrayNode( values, nodeType ) );
  24741. };
  24742. class ReferenceElementNode extends ArrayElementNode {
  24743. static get type() {
  24744. return 'ReferenceElementNode';
  24745. }
  24746. constructor( referenceNode, indexNode ) {
  24747. super( referenceNode, indexNode );
  24748. this.referenceNode = referenceNode;
  24749. this.isReferenceElementNode = true;
  24750. }
  24751. getNodeType() {
  24752. return this.referenceNode.uniformType;
  24753. }
  24754. generate( builder ) {
  24755. const snippet = super.generate( builder );
  24756. const arrayType = this.referenceNode.getNodeType();
  24757. const elementType = this.getNodeType();
  24758. return builder.format( snippet, arrayType, elementType );
  24759. }
  24760. }
  24761. // TODO: Extends this from ReferenceBaseNode
  24762. class ReferenceNode extends Node {
  24763. static get type() {
  24764. return 'ReferenceNode';
  24765. }
  24766. constructor( property, uniformType, object = null, count = null ) {
  24767. super();
  24768. this.property = property;
  24769. this.uniformType = uniformType;
  24770. this.object = object;
  24771. this.count = count;
  24772. this.properties = property.split( '.' );
  24773. this.reference = object;
  24774. this.node = null;
  24775. this.group = null;
  24776. this.name = null;
  24777. this.updateType = NodeUpdateType.OBJECT;
  24778. }
  24779. element( indexNode ) {
  24780. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24781. }
  24782. setGroup( group ) {
  24783. this.group = group;
  24784. return this;
  24785. }
  24786. label( name ) {
  24787. this.name = name;
  24788. return this;
  24789. }
  24790. setNodeType( uniformType ) {
  24791. let node = null;
  24792. if ( this.count !== null ) {
  24793. node = buffer( null, uniformType, this.count );
  24794. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24795. node = uniformArray( null, uniformType );
  24796. } else if ( uniformType === 'texture' ) {
  24797. node = texture( null );
  24798. } else if ( uniformType === 'cubeTexture' ) {
  24799. node = cubeTexture( null );
  24800. } else {
  24801. node = uniform( null, uniformType );
  24802. }
  24803. if ( this.group !== null ) {
  24804. node.setGroup( this.group );
  24805. }
  24806. if ( this.name !== null ) node.label( this.name );
  24807. this.node = node.getSelf();
  24808. }
  24809. getNodeType( builder ) {
  24810. if ( this.node === null ) {
  24811. this.updateReference( builder );
  24812. this.updateValue();
  24813. }
  24814. return this.node.getNodeType( builder );
  24815. }
  24816. getValueFromReference( object = this.reference ) {
  24817. const { properties } = this;
  24818. let value = object[ properties[ 0 ] ];
  24819. for ( let i = 1; i < properties.length; i ++ ) {
  24820. value = value[ properties[ i ] ];
  24821. }
  24822. return value;
  24823. }
  24824. updateReference( state ) {
  24825. this.reference = this.object !== null ? this.object : state.object;
  24826. return this.reference;
  24827. }
  24828. setup() {
  24829. this.updateValue();
  24830. return this.node;
  24831. }
  24832. update( /*frame*/ ) {
  24833. this.updateValue();
  24834. }
  24835. updateValue() {
  24836. if ( this.node === null ) this.setNodeType( this.uniformType );
  24837. const value = this.getValueFromReference();
  24838. if ( Array.isArray( value ) ) {
  24839. this.node.array = value;
  24840. } else {
  24841. this.node.value = value;
  24842. }
  24843. }
  24844. }
  24845. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24846. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24847. class MaterialReferenceNode extends ReferenceNode {
  24848. static get type() {
  24849. return 'MaterialReferenceNode';
  24850. }
  24851. constructor( property, inputType, material = null ) {
  24852. super( property, inputType, material );
  24853. this.material = material;
  24854. //this.updateType = NodeUpdateType.RENDER;
  24855. this.isMaterialReferenceNode = true;
  24856. }
  24857. /*setNodeType( node ) {
  24858. super.setNodeType( node );
  24859. this.node.groupNode = renderGroup;
  24860. }*/
  24861. updateReference( state ) {
  24862. this.reference = this.material !== null ? this.material : state.material;
  24863. return this.reference;
  24864. }
  24865. }
  24866. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24867. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  24868. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  24869. builder.geometry.computeTangents();
  24870. }
  24871. return attribute( 'tangent', 'vec4' );
  24872. } )();
  24873. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  24874. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  24875. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  24876. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  24877. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  24878. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  24879. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  24880. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  24881. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  24882. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  24883. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  24884. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  24885. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  24886. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  24887. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  24888. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  24889. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  24890. let bentNormal = anisotropyB.cross( positionViewDirection );
  24891. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  24892. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  24893. return bentNormal;
  24894. } )();
  24895. // Normal Mapping Without Precomputed Tangents
  24896. // http://www.thetenthplanet.de/archives/1180
  24897. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  24898. const { eye_pos, surf_norm, mapN, uv } = inputs;
  24899. const q0 = eye_pos.dFdx();
  24900. const q1 = eye_pos.dFdy();
  24901. const st0 = uv.dFdx();
  24902. const st1 = uv.dFdy();
  24903. const N = surf_norm; // normalized
  24904. const q1perp = q1.cross( N );
  24905. const q0perp = N.cross( q0 );
  24906. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  24907. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  24908. const det = T.dot( T ).max( B.dot( B ) );
  24909. const scale = faceDirection.mul( det.inverseSqrt() );
  24910. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  24911. } );
  24912. class NormalMapNode extends TempNode {
  24913. static get type() {
  24914. return 'NormalMapNode';
  24915. }
  24916. constructor( node, scaleNode = null ) {
  24917. super( 'vec3' );
  24918. this.node = node;
  24919. this.scaleNode = scaleNode;
  24920. this.normalMapType = TangentSpaceNormalMap;
  24921. }
  24922. setup( builder ) {
  24923. const { normalMapType, scaleNode } = this;
  24924. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  24925. if ( scaleNode !== null ) {
  24926. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  24927. }
  24928. let outputNode = null;
  24929. if ( normalMapType === ObjectSpaceNormalMap ) {
  24930. outputNode = transformNormalToView( normalMap );
  24931. } else if ( normalMapType === TangentSpaceNormalMap ) {
  24932. const tangent = builder.hasGeometryAttribute( 'tangent' );
  24933. if ( tangent === true ) {
  24934. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  24935. } else {
  24936. outputNode = perturbNormal2Arb( {
  24937. eye_pos: positionView,
  24938. surf_norm: normalView,
  24939. mapN: normalMap,
  24940. uv: uv()
  24941. } );
  24942. }
  24943. }
  24944. return outputNode;
  24945. }
  24946. }
  24947. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  24948. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  24949. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  24950. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  24951. // It's used to preserve the same TextureNode instance
  24952. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  24953. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  24954. return vec2(
  24955. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  24956. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  24957. ).mul( bumpScale );
  24958. } );
  24959. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  24960. const perturbNormalArb = Fn( ( inputs ) => {
  24961. const { surf_pos, surf_norm, dHdxy } = inputs;
  24962. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  24963. const vSigmaX = surf_pos.dFdx().normalize();
  24964. const vSigmaY = surf_pos.dFdy().normalize();
  24965. const vN = surf_norm; // normalized
  24966. const R1 = vSigmaY.cross( vN );
  24967. const R2 = vN.cross( vSigmaX );
  24968. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  24969. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  24970. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  24971. } );
  24972. class BumpMapNode extends TempNode {
  24973. static get type() {
  24974. return 'BumpMapNode';
  24975. }
  24976. constructor( textureNode, scaleNode = null ) {
  24977. super( 'vec3' );
  24978. this.textureNode = textureNode;
  24979. this.scaleNode = scaleNode;
  24980. }
  24981. setup() {
  24982. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  24983. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  24984. return perturbNormalArb( {
  24985. surf_pos: positionView,
  24986. surf_norm: normalView,
  24987. dHdxy
  24988. } );
  24989. }
  24990. }
  24991. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  24992. const _propertyCache = new Map();
  24993. class MaterialNode extends Node {
  24994. static get type() {
  24995. return 'MaterialNode';
  24996. }
  24997. constructor( scope ) {
  24998. super();
  24999. this.scope = scope;
  25000. }
  25001. getCache( property, type ) {
  25002. let node = _propertyCache.get( property );
  25003. if ( node === undefined ) {
  25004. node = materialReference( property, type );
  25005. _propertyCache.set( property, node );
  25006. }
  25007. return node;
  25008. }
  25009. getFloat( property ) {
  25010. return this.getCache( property, 'float' );
  25011. }
  25012. getColor( property ) {
  25013. return this.getCache( property, 'color' );
  25014. }
  25015. getTexture( property ) {
  25016. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25017. }
  25018. setup( builder ) {
  25019. const material = builder.context.material;
  25020. const scope = this.scope;
  25021. let node = null;
  25022. if ( scope === MaterialNode.COLOR ) {
  25023. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  25024. if ( material.map && material.map.isTexture === true ) {
  25025. node = colorNode.mul( this.getTexture( 'map' ) );
  25026. } else {
  25027. node = colorNode;
  25028. }
  25029. } else if ( scope === MaterialNode.OPACITY ) {
  25030. const opacityNode = this.getFloat( scope );
  25031. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25032. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25033. } else {
  25034. node = opacityNode;
  25035. }
  25036. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25037. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25038. node = this.getTexture( 'specular' ).r;
  25039. } else {
  25040. node = float( 1 );
  25041. }
  25042. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25043. const specularIntensity = this.getFloat( scope );
  25044. if ( material.specularMap ) {
  25045. node = specularIntensity.mul( this.getTexture( scope ).a );
  25046. } else {
  25047. node = specularIntensity;
  25048. }
  25049. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25050. const specularColorNode = this.getColor( scope );
  25051. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25052. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25053. } else {
  25054. node = specularColorNode;
  25055. }
  25056. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25057. const roughnessNode = this.getFloat( scope );
  25058. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25059. node = roughnessNode.mul( this.getTexture( scope ).g );
  25060. } else {
  25061. node = roughnessNode;
  25062. }
  25063. } else if ( scope === MaterialNode.METALNESS ) {
  25064. const metalnessNode = this.getFloat( scope );
  25065. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25066. node = metalnessNode.mul( this.getTexture( scope ).b );
  25067. } else {
  25068. node = metalnessNode;
  25069. }
  25070. } else if ( scope === MaterialNode.EMISSIVE ) {
  25071. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25072. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25073. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25074. node = emissiveNode.mul( this.getTexture( scope ) );
  25075. } else {
  25076. node = emissiveNode;
  25077. }
  25078. } else if ( scope === MaterialNode.NORMAL ) {
  25079. if ( material.normalMap ) {
  25080. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  25081. node.normalMapType = material.normalMapType;
  25082. } else if ( material.bumpMap ) {
  25083. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  25084. } else {
  25085. node = normalView;
  25086. }
  25087. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25088. const clearcoatNode = this.getFloat( scope );
  25089. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25090. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25091. } else {
  25092. node = clearcoatNode;
  25093. }
  25094. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25095. const clearcoatRoughnessNode = this.getFloat( scope );
  25096. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25097. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25098. } else {
  25099. node = clearcoatRoughnessNode;
  25100. }
  25101. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25102. if ( material.clearcoatNormalMap ) {
  25103. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  25104. } else {
  25105. node = normalView;
  25106. }
  25107. } else if ( scope === MaterialNode.SHEEN ) {
  25108. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25109. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25110. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25111. } else {
  25112. node = sheenNode;
  25113. }
  25114. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25115. const sheenRoughnessNode = this.getFloat( scope );
  25116. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25117. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25118. } else {
  25119. node = sheenRoughnessNode;
  25120. }
  25121. node = node.clamp( 0.07, 1.0 );
  25122. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25123. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25124. const anisotropyPolar = this.getTexture( scope );
  25125. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25126. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25127. } else {
  25128. node = materialAnisotropyVector;
  25129. }
  25130. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25131. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25132. if ( material.iridescenceThicknessMap ) {
  25133. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25134. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25135. } else {
  25136. node = iridescenceThicknessMaximum;
  25137. }
  25138. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25139. const transmissionNode = this.getFloat( scope );
  25140. if ( material.transmissionMap ) {
  25141. node = transmissionNode.mul( this.getTexture( scope ).r );
  25142. } else {
  25143. node = transmissionNode;
  25144. }
  25145. } else if ( scope === MaterialNode.THICKNESS ) {
  25146. const thicknessNode = this.getFloat( scope );
  25147. if ( material.thicknessMap ) {
  25148. node = thicknessNode.mul( this.getTexture( scope ).g );
  25149. } else {
  25150. node = thicknessNode;
  25151. }
  25152. } else if ( scope === MaterialNode.IOR ) {
  25153. node = this.getFloat( scope );
  25154. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25155. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25156. } else if ( scope === MaterialNode.AO_MAP ) {
  25157. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25158. } else {
  25159. const outputType = this.getNodeType( builder );
  25160. node = this.getCache( scope, outputType );
  25161. }
  25162. return node;
  25163. }
  25164. }
  25165. MaterialNode.ALPHA_TEST = 'alphaTest';
  25166. MaterialNode.COLOR = 'color';
  25167. MaterialNode.OPACITY = 'opacity';
  25168. MaterialNode.SHININESS = 'shininess';
  25169. MaterialNode.SPECULAR = 'specular';
  25170. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25171. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25172. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25173. MaterialNode.REFLECTIVITY = 'reflectivity';
  25174. MaterialNode.ROUGHNESS = 'roughness';
  25175. MaterialNode.METALNESS = 'metalness';
  25176. MaterialNode.NORMAL = 'normal';
  25177. MaterialNode.CLEARCOAT = 'clearcoat';
  25178. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25179. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25180. MaterialNode.EMISSIVE = 'emissive';
  25181. MaterialNode.ROTATION = 'rotation';
  25182. MaterialNode.SHEEN = 'sheen';
  25183. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25184. MaterialNode.ANISOTROPY = 'anisotropy';
  25185. MaterialNode.IRIDESCENCE = 'iridescence';
  25186. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25187. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25188. MaterialNode.IOR = 'ior';
  25189. MaterialNode.TRANSMISSION = 'transmission';
  25190. MaterialNode.THICKNESS = 'thickness';
  25191. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25192. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25193. MaterialNode.LINE_SCALE = 'scale';
  25194. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25195. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25196. MaterialNode.LINE_WIDTH = 'linewidth';
  25197. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25198. MaterialNode.POINT_WIDTH = 'pointWidth';
  25199. MaterialNode.DISPERSION = 'dispersion';
  25200. MaterialNode.LIGHT_MAP = 'light';
  25201. MaterialNode.AO_MAP = 'ao';
  25202. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25203. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25204. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25205. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25206. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25207. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25208. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25209. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25210. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25211. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25212. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25213. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25214. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  25215. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25216. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25217. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  25218. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25219. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25220. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25221. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25222. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25223. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25224. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25225. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25226. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25227. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  25228. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25229. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25230. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25231. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25232. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25233. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25234. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25235. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25236. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25237. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25238. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25239. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  25240. return frame.material;
  25241. } ).onRenderUpdate( function ( { material } ) {
  25242. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25243. } );
  25244. class ModelViewProjectionNode extends TempNode {
  25245. static get type() {
  25246. return 'ModelViewProjectionNode';
  25247. }
  25248. constructor( positionNode = null ) {
  25249. super( 'vec4' );
  25250. this.positionNode = positionNode;
  25251. }
  25252. setup( builder ) {
  25253. if ( builder.shaderStage === 'fragment' ) {
  25254. return varying( builder.context.mvp );
  25255. }
  25256. const position = this.positionNode || positionLocal;
  25257. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  25258. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  25259. }
  25260. }
  25261. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  25262. class IndexNode extends Node {
  25263. static get type() {
  25264. return 'IndexNode';
  25265. }
  25266. constructor( scope ) {
  25267. super( 'uint' );
  25268. this.scope = scope;
  25269. this.isInstanceIndexNode = true;
  25270. }
  25271. generate( builder ) {
  25272. const nodeType = this.getNodeType( builder );
  25273. const scope = this.scope;
  25274. let propertyName;
  25275. if ( scope === IndexNode.VERTEX ) {
  25276. // The index of a vertex within a mesh.
  25277. propertyName = builder.getVertexIndex();
  25278. } else if ( scope === IndexNode.INSTANCE ) {
  25279. // The index of either a mesh instance or an invocation of a compute shader.
  25280. propertyName = builder.getInstanceIndex();
  25281. } else if ( scope === IndexNode.DRAW ) {
  25282. // The index of a draw call.
  25283. propertyName = builder.getDrawIndex();
  25284. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  25285. // The index of a compute invocation within the scope of a workgroup load.
  25286. propertyName = builder.getInvocationLocalIndex();
  25287. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  25288. // The index of a compute invocation within the scope of a subgroup.
  25289. propertyName = builder.getInvocationSubgroupIndex();
  25290. } else if ( scope === IndexNode.SUBGROUP ) {
  25291. // The index of the subgroup the current compute invocation belongs to.
  25292. propertyName = builder.getSubgroupIndex();
  25293. } else {
  25294. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  25295. }
  25296. let output;
  25297. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25298. output = propertyName;
  25299. } else {
  25300. const nodeVarying = varying( this );
  25301. output = nodeVarying.build( builder, nodeType );
  25302. }
  25303. return output;
  25304. }
  25305. }
  25306. IndexNode.VERTEX = 'vertex';
  25307. IndexNode.INSTANCE = 'instance';
  25308. IndexNode.SUBGROUP = 'subgroup';
  25309. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  25310. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  25311. IndexNode.DRAW = 'draw';
  25312. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  25313. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  25314. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  25315. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  25316. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  25317. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  25318. class InstanceNode extends Node {
  25319. static get type() {
  25320. return 'InstanceNode';
  25321. }
  25322. constructor( instanceMesh ) {
  25323. super( 'void' );
  25324. this.instanceMesh = instanceMesh;
  25325. this.instanceMatrixNode = null;
  25326. this.instanceColorNode = null;
  25327. this.updateType = NodeUpdateType.FRAME;
  25328. this.buffer = null;
  25329. this.bufferColor = null;
  25330. }
  25331. setup( builder ) {
  25332. let instanceMatrixNode = this.instanceMatrixNode;
  25333. let instanceColorNode = this.instanceColorNode;
  25334. const instanceMesh = this.instanceMesh;
  25335. if ( instanceMatrixNode === null ) {
  25336. const instanceAttribute = instanceMesh.instanceMatrix;
  25337. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  25338. if ( instanceMesh.count <= 1000 ) {
  25339. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', Math.max( instanceMesh.count, 1 ) ).element( instanceIndex );
  25340. } else {
  25341. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25342. this.buffer = buffer;
  25343. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25344. const instanceBuffers = [
  25345. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25346. bufferFn( buffer, 'vec4', 16, 0 ),
  25347. bufferFn( buffer, 'vec4', 16, 4 ),
  25348. bufferFn( buffer, 'vec4', 16, 8 ),
  25349. bufferFn( buffer, 'vec4', 16, 12 )
  25350. ];
  25351. instanceMatrixNode = mat4( ...instanceBuffers );
  25352. }
  25353. this.instanceMatrixNode = instanceMatrixNode;
  25354. }
  25355. const instanceColorAttribute = instanceMesh.instanceColor;
  25356. if ( instanceColorAttribute && instanceColorNode === null ) {
  25357. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25358. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25359. this.bufferColor = buffer;
  25360. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25361. this.instanceColorNode = instanceColorNode;
  25362. }
  25363. // POSITION
  25364. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25365. positionLocal.assign( instancePosition );
  25366. // NORMAL
  25367. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25368. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25369. // ASSIGNS
  25370. normalLocal.assign( instanceNormal );
  25371. }
  25372. // COLOR
  25373. if ( this.instanceColorNode !== null ) {
  25374. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25375. }
  25376. }
  25377. update( /*frame*/ ) {
  25378. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25379. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25380. }
  25381. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25382. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25383. }
  25384. }
  25385. }
  25386. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25387. class BatchNode extends Node {
  25388. static get type() {
  25389. return 'BatchNode';
  25390. }
  25391. constructor( batchMesh ) {
  25392. super( 'void' );
  25393. this.batchMesh = batchMesh;
  25394. this.batchingIdNode = null;
  25395. }
  25396. setup( builder ) {
  25397. // POSITION
  25398. if ( this.batchingIdNode === null ) {
  25399. if ( builder.getDrawIndex() === null ) {
  25400. this.batchingIdNode = instanceIndex;
  25401. } else {
  25402. this.batchingIdNode = drawIndex;
  25403. }
  25404. }
  25405. const getIndirectIndex = Fn( ( [ id ] ) => {
  25406. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25407. const x = int( id ).modInt( int( size ) );
  25408. const y = int( id ).div( int( size ) );
  25409. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25410. } ).setLayout( {
  25411. name: 'getIndirectIndex',
  25412. type: 'uint',
  25413. inputs: [
  25414. { name: 'id', type: 'int' }
  25415. ]
  25416. } );
  25417. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25418. const matricesTexture = this.batchMesh._matricesTexture;
  25419. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25420. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25421. const x = j.modInt( size );
  25422. const y = j.div( int( size ) );
  25423. const batchingMatrix = mat4(
  25424. textureLoad( matricesTexture, ivec2( x, y ) ),
  25425. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25426. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25427. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25428. );
  25429. const colorsTexture = this.batchMesh._colorsTexture;
  25430. if ( colorsTexture !== null ) {
  25431. const getBatchingColor = Fn( ( [ id ] ) => {
  25432. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25433. const j = id;
  25434. const x = j.modInt( size );
  25435. const y = j.div( size );
  25436. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25437. } ).setLayout( {
  25438. name: 'getBatchingColor',
  25439. type: 'vec3',
  25440. inputs: [
  25441. { name: 'id', type: 'int' }
  25442. ]
  25443. } );
  25444. const color = getBatchingColor( indirectId );
  25445. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25446. }
  25447. const bm = mat3( batchingMatrix );
  25448. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25449. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25450. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25451. normalLocal.assign( batchingNormal );
  25452. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25453. tangentLocal.mulAssign( bm );
  25454. }
  25455. }
  25456. }
  25457. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25458. const _frameId = new WeakMap();
  25459. class SkinningNode extends Node {
  25460. static get type() {
  25461. return 'SkinningNode';
  25462. }
  25463. constructor( skinnedMesh, useReference = false ) {
  25464. super( 'void' );
  25465. this.skinnedMesh = skinnedMesh;
  25466. this.useReference = useReference;
  25467. this.updateType = NodeUpdateType.OBJECT;
  25468. //
  25469. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25470. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25471. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25472. if ( useReference ) {
  25473. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25474. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25475. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25476. } else {
  25477. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25478. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25479. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25480. }
  25481. this.bindMatrixNode = bindMatrixNode;
  25482. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25483. this.boneMatricesNode = boneMatricesNode;
  25484. this.previousBoneMatricesNode = null;
  25485. }
  25486. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25487. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25488. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25489. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25490. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25491. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25492. // POSITION
  25493. const skinVertex = bindMatrixNode.mul( position );
  25494. const skinned = add(
  25495. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25496. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25497. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25498. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25499. );
  25500. return bindMatrixInverseNode.mul( skinned ).xyz;
  25501. }
  25502. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25503. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25504. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25505. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25506. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25507. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25508. // NORMAL
  25509. let skinMatrix = add(
  25510. skinWeightNode.x.mul( boneMatX ),
  25511. skinWeightNode.y.mul( boneMatY ),
  25512. skinWeightNode.z.mul( boneMatZ ),
  25513. skinWeightNode.w.mul( boneMatW )
  25514. );
  25515. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25516. return skinMatrix.transformDirection( normal ).xyz;
  25517. }
  25518. getPreviousSkinnedPosition( builder ) {
  25519. const skinnedMesh = builder.object;
  25520. if ( this.previousBoneMatricesNode === null ) {
  25521. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25522. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25523. }
  25524. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25525. }
  25526. needsPreviousBoneMatrices( builder ) {
  25527. const mrt = builder.renderer.getMRT();
  25528. return mrt && mrt.has( 'velocity' );
  25529. }
  25530. setup( builder ) {
  25531. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25532. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25533. }
  25534. const skinPosition = this.getSkinnedPosition();
  25535. positionLocal.assign( skinPosition );
  25536. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25537. const skinNormal = this.getSkinnedNormal();
  25538. normalLocal.assign( skinNormal );
  25539. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25540. tangentLocal.assign( skinNormal );
  25541. }
  25542. }
  25543. }
  25544. generate( builder, output ) {
  25545. if ( output !== 'void' ) {
  25546. return positionLocal.build( builder, output );
  25547. }
  25548. }
  25549. update( frame ) {
  25550. const object = this.useReference ? frame.object : this.skinnedMesh;
  25551. const skeleton = object.skeleton;
  25552. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25553. _frameId.set( skeleton, frame.frameId );
  25554. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25555. skeleton.update();
  25556. }
  25557. }
  25558. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25559. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25560. class LoopNode extends Node {
  25561. static get type() {
  25562. return 'LoopNode';
  25563. }
  25564. constructor( params = [] ) {
  25565. super();
  25566. this.params = params;
  25567. }
  25568. getVarName( index ) {
  25569. return String.fromCharCode( 'i'.charCodeAt() + index );
  25570. }
  25571. getProperties( builder ) {
  25572. const properties = builder.getNodeProperties( this );
  25573. if ( properties.stackNode !== undefined ) return properties;
  25574. //
  25575. const inputs = {};
  25576. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25577. const param = this.params[ i ];
  25578. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25579. const type = ( param.isNode !== true && param.type ) || 'int';
  25580. inputs[ name ] = expression( name, type );
  25581. }
  25582. const stack = builder.addStack(); // TODO: cache() it
  25583. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25584. properties.stackNode = stack;
  25585. builder.removeStack();
  25586. return properties;
  25587. }
  25588. getNodeType( builder ) {
  25589. const { returnsNode } = this.getProperties( builder );
  25590. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25591. }
  25592. setup( builder ) {
  25593. // setup properties
  25594. this.getProperties( builder );
  25595. }
  25596. generate( builder ) {
  25597. const properties = this.getProperties( builder );
  25598. const params = this.params;
  25599. const stackNode = properties.stackNode;
  25600. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25601. const param = params[ i ];
  25602. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25603. if ( param.isNode ) {
  25604. type = 'int';
  25605. name = this.getVarName( i );
  25606. start = '0';
  25607. end = param.build( builder, type );
  25608. condition = '<';
  25609. } else {
  25610. type = param.type || 'int';
  25611. name = param.name || this.getVarName( i );
  25612. start = param.start;
  25613. end = param.end;
  25614. condition = param.condition;
  25615. update = param.update;
  25616. if ( typeof start === 'number' ) start = start.toString();
  25617. else if ( start && start.isNode ) start = start.build( builder, type );
  25618. if ( typeof end === 'number' ) end = end.toString();
  25619. else if ( end && end.isNode ) end = end.build( builder, type );
  25620. if ( start !== undefined && end === undefined ) {
  25621. start = start + ' - 1';
  25622. end = '0';
  25623. condition = '>=';
  25624. } else if ( end !== undefined && start === undefined ) {
  25625. start = '0';
  25626. condition = '<';
  25627. }
  25628. if ( condition === undefined ) {
  25629. if ( Number( start ) > Number( end ) ) {
  25630. condition = '>=';
  25631. } else {
  25632. condition = '<';
  25633. }
  25634. }
  25635. }
  25636. const internalParam = { start, end, condition };
  25637. //
  25638. const startSnippet = internalParam.start;
  25639. const endSnippet = internalParam.end;
  25640. let declarationSnippet = '';
  25641. let conditionalSnippet = '';
  25642. let updateSnippet = '';
  25643. if ( ! update ) {
  25644. if ( type === 'int' || type === 'uint' ) {
  25645. if ( condition.includes( '<' ) ) update = '++';
  25646. else update = '--';
  25647. } else {
  25648. if ( condition.includes( '<' ) ) update = '+= 1.';
  25649. else update = '-= 1.';
  25650. }
  25651. }
  25652. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25653. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25654. updateSnippet += name + ' ' + update;
  25655. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25656. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25657. }
  25658. const stackSnippet = stackNode.build( builder, 'void' );
  25659. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25660. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25661. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25662. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25663. }
  25664. builder.addFlowTab();
  25665. return returnsSnippet;
  25666. }
  25667. }
  25668. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25669. const Continue = () => expression( 'continue' ).append();
  25670. const Break = () => expression( 'break' ).append();
  25671. //
  25672. const loop = ( ...params ) => { // @deprecated, r168
  25673. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25674. return Loop( ...params );
  25675. };
  25676. const _morphTextures = /*@__PURE__*/ new WeakMap();
  25677. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25678. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25679. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25680. const y = texelIndex.div( width );
  25681. const x = texelIndex.sub( y.mul( width ) );
  25682. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25683. return bufferAttrib.mul( influence );
  25684. } );
  25685. function getEntry( geometry ) {
  25686. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25687. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25688. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25689. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25690. // into an array of data textures. Each layer represents a single morph target.
  25691. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25692. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25693. let entry = _morphTextures.get( geometry );
  25694. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25695. if ( entry !== undefined ) entry.texture.dispose();
  25696. const morphTargets = geometry.morphAttributes.position || [];
  25697. const morphNormals = geometry.morphAttributes.normal || [];
  25698. const morphColors = geometry.morphAttributes.color || [];
  25699. let vertexDataCount = 0;
  25700. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25701. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25702. if ( hasMorphColors === true ) vertexDataCount = 3;
  25703. let width = geometry.attributes.position.count * vertexDataCount;
  25704. let height = 1;
  25705. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25706. if ( width > maxTextureSize ) {
  25707. height = Math.ceil( width / maxTextureSize );
  25708. width = maxTextureSize;
  25709. }
  25710. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25711. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25712. bufferTexture.type = FloatType;
  25713. bufferTexture.needsUpdate = true;
  25714. // fill buffer
  25715. const vertexDataStride = vertexDataCount * 4;
  25716. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25717. const morphTarget = morphTargets[ i ];
  25718. const morphNormal = morphNormals[ i ];
  25719. const morphColor = morphColors[ i ];
  25720. const offset = width * height * 4 * i;
  25721. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25722. const stride = j * vertexDataStride;
  25723. if ( hasMorphPosition === true ) {
  25724. _morphVec4.fromBufferAttribute( morphTarget, j );
  25725. buffer[ offset + stride + 0 ] = _morphVec4.x;
  25726. buffer[ offset + stride + 1 ] = _morphVec4.y;
  25727. buffer[ offset + stride + 2 ] = _morphVec4.z;
  25728. buffer[ offset + stride + 3 ] = 0;
  25729. }
  25730. if ( hasMorphNormals === true ) {
  25731. _morphVec4.fromBufferAttribute( morphNormal, j );
  25732. buffer[ offset + stride + 4 ] = _morphVec4.x;
  25733. buffer[ offset + stride + 5 ] = _morphVec4.y;
  25734. buffer[ offset + stride + 6 ] = _morphVec4.z;
  25735. buffer[ offset + stride + 7 ] = 0;
  25736. }
  25737. if ( hasMorphColors === true ) {
  25738. _morphVec4.fromBufferAttribute( morphColor, j );
  25739. buffer[ offset + stride + 8 ] = _morphVec4.x;
  25740. buffer[ offset + stride + 9 ] = _morphVec4.y;
  25741. buffer[ offset + stride + 10 ] = _morphVec4.z;
  25742. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  25743. }
  25744. }
  25745. }
  25746. entry = {
  25747. count: morphTargetsCount,
  25748. texture: bufferTexture,
  25749. stride: vertexDataCount,
  25750. size: new Vector2( width, height )
  25751. };
  25752. _morphTextures.set( geometry, entry );
  25753. function disposeTexture() {
  25754. bufferTexture.dispose();
  25755. _morphTextures.delete( geometry );
  25756. geometry.removeEventListener( 'dispose', disposeTexture );
  25757. }
  25758. geometry.addEventListener( 'dispose', disposeTexture );
  25759. }
  25760. return entry;
  25761. }
  25762. class MorphNode extends Node {
  25763. static get type() {
  25764. return 'MorphNode';
  25765. }
  25766. constructor( mesh ) {
  25767. super( 'void' );
  25768. this.mesh = mesh;
  25769. this.morphBaseInfluence = uniform( 1 );
  25770. this.updateType = NodeUpdateType.OBJECT;
  25771. }
  25772. setup( builder ) {
  25773. const { geometry } = builder;
  25774. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25775. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  25776. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25777. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25778. // nodes
  25779. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25780. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25781. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25782. const width = int( size.width );
  25783. Loop( morphTargetsCount, ( { i } ) => {
  25784. const influence = float( 0 ).toVar();
  25785. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25786. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25787. } else {
  25788. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25789. }
  25790. if ( hasMorphPosition === true ) {
  25791. positionLocal.addAssign( getMorph( {
  25792. bufferMap,
  25793. influence,
  25794. stride,
  25795. width,
  25796. depth: i,
  25797. offset: int( 0 )
  25798. } ) );
  25799. }
  25800. if ( hasMorphNormals === true ) {
  25801. normalLocal.addAssign( getMorph( {
  25802. bufferMap,
  25803. influence,
  25804. stride,
  25805. width,
  25806. depth: i,
  25807. offset: int( 1 )
  25808. } ) );
  25809. }
  25810. } );
  25811. }
  25812. update() {
  25813. const morphBaseInfluence = this.morphBaseInfluence;
  25814. if ( this.mesh.geometry.morphTargetsRelative ) {
  25815. morphBaseInfluence.value = 1;
  25816. } else {
  25817. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25818. }
  25819. }
  25820. }
  25821. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  25822. const sortLights = ( lights ) => {
  25823. return lights.sort( ( a, b ) => a.id - b.id );
  25824. };
  25825. const getLightNodeById = ( id, lightNodes ) => {
  25826. for ( const lightNode of lightNodes ) {
  25827. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  25828. return lightNode;
  25829. }
  25830. }
  25831. return null;
  25832. };
  25833. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  25834. class LightsNode extends Node {
  25835. static get type() {
  25836. return 'LightsNode';
  25837. }
  25838. constructor( lights = [] ) {
  25839. super( 'vec3' );
  25840. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  25841. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  25842. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  25843. this._lights = lights;
  25844. this._lightNodes = null;
  25845. this._lightNodesHash = null;
  25846. this.global = true;
  25847. }
  25848. getHash( builder ) {
  25849. if ( this._lightNodesHash === null ) {
  25850. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25851. const hash = [];
  25852. for ( const lightNode of this._lightNodes ) {
  25853. hash.push( lightNode.getHash() );
  25854. }
  25855. this._lightNodesHash = 'lights-' + hash.join( ',' );
  25856. }
  25857. return this._lightNodesHash;
  25858. }
  25859. analyze( builder ) {
  25860. const properties = builder.getDataFromNode( this );
  25861. for ( const node of properties.nodes ) {
  25862. node.build( builder );
  25863. }
  25864. }
  25865. setupLightsNode( builder ) {
  25866. const lightNodes = [];
  25867. const previousLightNodes = this._lightNodes;
  25868. const lights = sortLights( this._lights );
  25869. const nodeLibrary = builder.renderer.nodes.library;
  25870. for ( const light of lights ) {
  25871. if ( light.isNode ) {
  25872. lightNodes.push( nodeObject( light ) );
  25873. } else {
  25874. let lightNode = null;
  25875. if ( previousLightNodes !== null ) {
  25876. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  25877. }
  25878. if ( lightNode === null ) {
  25879. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  25880. if ( lightNodeClass === null ) {
  25881. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  25882. continue;
  25883. }
  25884. let lightNode = null;
  25885. if ( ! _lightsNodeRef.has( light ) ) {
  25886. lightNode = new lightNodeClass( light );
  25887. _lightsNodeRef.set( light, lightNode );
  25888. } else {
  25889. lightNode = _lightsNodeRef.get( light );
  25890. }
  25891. lightNodes.push( lightNode );
  25892. }
  25893. }
  25894. }
  25895. this._lightNodes = lightNodes;
  25896. }
  25897. setup( builder ) {
  25898. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25899. const context = builder.context;
  25900. const lightingModel = context.lightingModel;
  25901. let outgoingLightNode = this.outgoingLightNode;
  25902. if ( lightingModel ) {
  25903. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  25904. context.outgoingLight = outgoingLightNode;
  25905. const stack = builder.addStack();
  25906. //
  25907. const properties = builder.getDataFromNode( this );
  25908. properties.nodes = stack.nodes;
  25909. //
  25910. lightingModel.start( context, stack, builder );
  25911. // lights
  25912. for ( const lightNode of _lightNodes ) {
  25913. lightNode.build( builder );
  25914. }
  25915. //
  25916. lightingModel.indirect( context, stack, builder );
  25917. //
  25918. const { backdrop, backdropAlpha } = context;
  25919. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  25920. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  25921. if ( backdrop !== null ) {
  25922. if ( backdropAlpha !== null ) {
  25923. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  25924. } else {
  25925. totalDiffuse = vec3( backdrop );
  25926. }
  25927. context.material.transparent = true;
  25928. }
  25929. totalDiffuseNode.assign( totalDiffuse );
  25930. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  25931. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  25932. //
  25933. lightingModel.finish( context, stack, builder );
  25934. //
  25935. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  25936. }
  25937. return outgoingLightNode;
  25938. }
  25939. setLights( lights ) {
  25940. this._lights = lights;
  25941. this._lightNodes = null;
  25942. this._lightNodesHash = null;
  25943. return this;
  25944. }
  25945. getLights() {
  25946. return this._lights;
  25947. }
  25948. }
  25949. const lights = /*@__PURE__*/ nodeProxy( LightsNode );
  25950. class LightingNode extends Node {
  25951. static get type() {
  25952. return 'LightingNode';
  25953. }
  25954. constructor() {
  25955. super( 'vec3' );
  25956. this.isLightingNode = true;
  25957. }
  25958. generate( /*builder*/ ) {
  25959. console.warn( 'Abstract function.' );
  25960. }
  25961. }
  25962. class AONode extends LightingNode {
  25963. static get type() {
  25964. return 'AONode';
  25965. }
  25966. constructor( aoNode = null ) {
  25967. super();
  25968. this.aoNode = aoNode;
  25969. }
  25970. setup( builder ) {
  25971. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  25972. }
  25973. }
  25974. class LightingContextNode extends ContextNode {
  25975. static get type() {
  25976. return 'LightingContextNode';
  25977. }
  25978. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  25979. super( node );
  25980. this.lightingModel = lightingModel;
  25981. this.backdropNode = backdropNode;
  25982. this.backdropAlphaNode = backdropAlphaNode;
  25983. this._value = null;
  25984. }
  25985. getContext() {
  25986. const { backdropNode, backdropAlphaNode } = this;
  25987. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  25988. directSpecular = vec3().toVar( 'directSpecular' ),
  25989. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  25990. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  25991. const reflectedLight = {
  25992. directDiffuse,
  25993. directSpecular,
  25994. indirectDiffuse,
  25995. indirectSpecular
  25996. };
  25997. const context = {
  25998. radiance: vec3().toVar( 'radiance' ),
  25999. irradiance: vec3().toVar( 'irradiance' ),
  26000. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  26001. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  26002. reflectedLight,
  26003. backdrop: backdropNode,
  26004. backdropAlpha: backdropAlphaNode
  26005. };
  26006. return context;
  26007. }
  26008. setup( builder ) {
  26009. this.value = this._value || ( this._value = this.getContext() );
  26010. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  26011. return super.setup( builder );
  26012. }
  26013. }
  26014. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  26015. class IrradianceNode extends LightingNode {
  26016. static get type() {
  26017. return 'IrradianceNode';
  26018. }
  26019. constructor( node ) {
  26020. super();
  26021. this.node = node;
  26022. }
  26023. setup( builder ) {
  26024. builder.context.irradiance.addAssign( this.node );
  26025. }
  26026. }
  26027. let screenSizeVec, viewportVec;
  26028. class ScreenNode extends Node {
  26029. static get type() {
  26030. return 'ScreenNode';
  26031. }
  26032. constructor( scope ) {
  26033. super();
  26034. this.scope = scope;
  26035. this.isViewportNode = true;
  26036. }
  26037. getNodeType() {
  26038. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  26039. else return 'vec2';
  26040. }
  26041. getUpdateType() {
  26042. let updateType = NodeUpdateType.NONE;
  26043. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  26044. updateType = NodeUpdateType.RENDER;
  26045. }
  26046. this.updateType = updateType;
  26047. return updateType;
  26048. }
  26049. update( { renderer } ) {
  26050. const renderTarget = renderer.getRenderTarget();
  26051. if ( this.scope === ScreenNode.VIEWPORT ) {
  26052. if ( renderTarget !== null ) {
  26053. viewportVec.copy( renderTarget.viewport );
  26054. } else {
  26055. renderer.getViewport( viewportVec );
  26056. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  26057. }
  26058. } else {
  26059. if ( renderTarget !== null ) {
  26060. screenSizeVec.width = renderTarget.width;
  26061. screenSizeVec.height = renderTarget.height;
  26062. } else {
  26063. renderer.getDrawingBufferSize( screenSizeVec );
  26064. }
  26065. }
  26066. }
  26067. setup( /*builder*/ ) {
  26068. const scope = this.scope;
  26069. let output = null;
  26070. if ( scope === ScreenNode.SIZE ) {
  26071. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  26072. } else if ( scope === ScreenNode.VIEWPORT ) {
  26073. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  26074. } else {
  26075. output = vec2( screenCoordinate.div( screenSize ) );
  26076. }
  26077. return output;
  26078. }
  26079. generate( builder ) {
  26080. if ( this.scope === ScreenNode.COORDINATE ) {
  26081. let coord = builder.getFragCoord();
  26082. if ( builder.isFlipY() ) {
  26083. // follow webgpu standards
  26084. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26085. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26086. }
  26087. return coord;
  26088. }
  26089. return super.generate( builder );
  26090. }
  26091. }
  26092. ScreenNode.COORDINATE = 'coordinate';
  26093. ScreenNode.VIEWPORT = 'viewport';
  26094. ScreenNode.SIZE = 'size';
  26095. ScreenNode.UV = 'uv';
  26096. // Screen
  26097. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26098. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26099. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26100. // Viewport
  26101. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26102. const viewportSize = viewport.zw;
  26103. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26104. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26105. // Deprecated
  26106. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26107. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26108. return screenSize;
  26109. }, 'vec2' ).once() )();
  26110. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26111. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26112. return screenUV;
  26113. }, 'vec2' ).once() )();
  26114. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26115. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26116. return screenUV.flipY();
  26117. }, 'vec2' ).once() )();
  26118. const _size$a = /*@__PURE__*/ new Vector2();
  26119. class ViewportTextureNode extends TextureNode {
  26120. static get type() {
  26121. return 'ViewportTextureNode';
  26122. }
  26123. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26124. if ( framebufferTexture === null ) {
  26125. framebufferTexture = new FramebufferTexture();
  26126. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26127. }
  26128. super( framebufferTexture, uvNode, levelNode );
  26129. this.generateMipmaps = false;
  26130. this.isOutputTextureNode = true;
  26131. this.updateBeforeType = NodeUpdateType.FRAME;
  26132. }
  26133. updateBefore( frame ) {
  26134. const renderer = frame.renderer;
  26135. renderer.getDrawingBufferSize( _size$a );
  26136. //
  26137. const framebufferTexture = this.value;
  26138. if ( framebufferTexture.image.width !== _size$a.width || framebufferTexture.image.height !== _size$a.height ) {
  26139. framebufferTexture.image.width = _size$a.width;
  26140. framebufferTexture.image.height = _size$a.height;
  26141. framebufferTexture.needsUpdate = true;
  26142. }
  26143. //
  26144. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26145. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26146. renderer.copyFramebufferToTexture( framebufferTexture );
  26147. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26148. }
  26149. clone() {
  26150. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26151. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26152. return viewportTextureNode;
  26153. }
  26154. }
  26155. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26156. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26157. let sharedDepthbuffer = null;
  26158. class ViewportDepthTextureNode extends ViewportTextureNode {
  26159. static get type() {
  26160. return 'ViewportDepthTextureNode';
  26161. }
  26162. constructor( uvNode = screenUV, levelNode = null ) {
  26163. if ( sharedDepthbuffer === null ) {
  26164. sharedDepthbuffer = new DepthTexture();
  26165. }
  26166. super( uvNode, levelNode, sharedDepthbuffer );
  26167. }
  26168. }
  26169. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26170. class ViewportDepthNode extends Node {
  26171. static get type() {
  26172. return 'ViewportDepthNode';
  26173. }
  26174. constructor( scope, valueNode = null ) {
  26175. super( 'float' );
  26176. this.scope = scope;
  26177. this.valueNode = valueNode;
  26178. this.isViewportDepthNode = true;
  26179. }
  26180. generate( builder ) {
  26181. const { scope } = this;
  26182. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26183. return builder.getFragDepth();
  26184. }
  26185. return super.generate( builder );
  26186. }
  26187. setup( { camera } ) {
  26188. const { scope } = this;
  26189. const value = this.valueNode;
  26190. let node = null;
  26191. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26192. if ( value !== null ) {
  26193. node = depthBase().assign( value );
  26194. }
  26195. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26196. if ( camera.isPerspectiveCamera ) {
  26197. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26198. } else {
  26199. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26200. }
  26201. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26202. if ( value !== null ) {
  26203. if ( camera.isPerspectiveCamera ) {
  26204. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26205. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26206. } else {
  26207. node = value;
  26208. }
  26209. } else {
  26210. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26211. }
  26212. }
  26213. return node;
  26214. }
  26215. }
  26216. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26217. ViewportDepthNode.DEPTH = 'depth';
  26218. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26219. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26220. // -near maps to 0; -far maps to 1
  26221. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26222. // maps orthographic depth in [ 0, 1 ] to viewZ
  26223. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26224. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26225. // -near maps to 0; -far maps to 1
  26226. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26227. // maps perspective depth in [ 0, 1 ] to viewZ
  26228. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26229. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26230. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26231. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26232. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26233. depth.assign = ( value ) => depthBase( value );
  26234. class ClippingNode extends Node {
  26235. static get type() {
  26236. return 'ClippingNode';
  26237. }
  26238. constructor( scope = ClippingNode.DEFAULT ) {
  26239. super();
  26240. this.scope = scope;
  26241. }
  26242. setup( builder ) {
  26243. super.setup( builder );
  26244. const clippingContext = builder.clippingContext;
  26245. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26246. const numClippingPlanes = globalClippingCount + localClippingCount;
  26247. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26248. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26249. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26250. } else {
  26251. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26252. }
  26253. }
  26254. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26255. return Fn( () => {
  26256. const clippingPlanes = uniformArray( planes );
  26257. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26258. const distanceGradient = property( 'float', 'distanceToGradient' );
  26259. const clipOpacity = property( 'float', 'clipOpacity' );
  26260. clipOpacity.assign( 1 );
  26261. let plane;
  26262. Loop( numUnionClippingPlanes, ( { i } ) => {
  26263. plane = clippingPlanes.element( i );
  26264. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26265. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26266. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26267. clipOpacity.equal( 0.0 ).discard();
  26268. } );
  26269. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26270. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26271. unionClipOpacity.assign( 1 );
  26272. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26273. plane = clippingPlanes.element( i );
  26274. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26275. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26276. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26277. } );
  26278. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26279. }
  26280. diffuseColor.a.mulAssign( clipOpacity );
  26281. diffuseColor.a.equal( 0.0 ).discard();
  26282. } )();
  26283. }
  26284. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26285. return Fn( () => {
  26286. const clippingPlanes = uniformArray( planes );
  26287. let plane;
  26288. Loop( numUnionClippingPlanes, ( { i } ) => {
  26289. plane = clippingPlanes.element( i );
  26290. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26291. } );
  26292. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26293. const clipped = property( 'bool', 'clipped' );
  26294. clipped.assign( true );
  26295. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26296. plane = clippingPlanes.element( i );
  26297. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26298. } );
  26299. clipped.discard();
  26300. }
  26301. } )();
  26302. }
  26303. }
  26304. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26305. ClippingNode.DEFAULT = 'default';
  26306. const clipping = () => nodeObject( new ClippingNode() );
  26307. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26308. class NodeMaterial extends Material {
  26309. static get type() {
  26310. return 'NodeMaterial';
  26311. }
  26312. constructor() {
  26313. super();
  26314. this.isNodeMaterial = true;
  26315. this.type = this.constructor.type;
  26316. this.forceSinglePass = false;
  26317. this.fog = true;
  26318. this.lights = false;
  26319. this.lightsNode = null;
  26320. this.envNode = null;
  26321. this.aoNode = null;
  26322. this.colorNode = null;
  26323. this.normalNode = null;
  26324. this.opacityNode = null;
  26325. this.backdropNode = null;
  26326. this.backdropAlphaNode = null;
  26327. this.alphaTestNode = null;
  26328. this.positionNode = null;
  26329. this.depthNode = null;
  26330. this.shadowNode = null;
  26331. this.shadowPositionNode = null;
  26332. this.outputNode = null;
  26333. this.mrtNode = null;
  26334. this.fragmentNode = null;
  26335. this.vertexNode = null;
  26336. }
  26337. customProgramCacheKey() {
  26338. return this.type + getCacheKey$1( this );
  26339. }
  26340. build( builder ) {
  26341. this.setup( builder );
  26342. }
  26343. setupObserver( builder ) {
  26344. return new NodeMaterialObserver( builder );
  26345. }
  26346. setup( builder ) {
  26347. builder.context.setupNormal = () => this.setupNormal( builder );
  26348. // < VERTEX STAGE >
  26349. builder.addStack();
  26350. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26351. builder.addFlow( 'vertex', builder.removeStack() );
  26352. // < FRAGMENT STAGE >
  26353. builder.addStack();
  26354. let resultNode;
  26355. const clippingNode = this.setupClipping( builder );
  26356. if ( this.depthWrite === true ) this.setupDepth( builder );
  26357. if ( this.fragmentNode === null ) {
  26358. this.setupDiffuseColor( builder );
  26359. this.setupVariants( builder );
  26360. const outgoingLightNode = this.setupLighting( builder );
  26361. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26362. // force unsigned floats - useful for RenderTargets
  26363. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26364. resultNode = this.setupOutput( builder, basicOutput );
  26365. // OUTPUT NODE
  26366. output.assign( resultNode );
  26367. //
  26368. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26369. // MRT
  26370. const renderTarget = builder.renderer.getRenderTarget();
  26371. if ( renderTarget !== null ) {
  26372. const mrt = builder.renderer.getMRT();
  26373. const materialMRT = this.mrtNode;
  26374. if ( mrt !== null ) {
  26375. resultNode = mrt;
  26376. if ( materialMRT !== null ) {
  26377. resultNode = mrt.merge( materialMRT );
  26378. }
  26379. } else if ( materialMRT !== null ) {
  26380. resultNode = materialMRT;
  26381. }
  26382. }
  26383. } else {
  26384. let fragmentNode = this.fragmentNode;
  26385. if ( fragmentNode.isOutputStructNode !== true ) {
  26386. fragmentNode = vec4( fragmentNode );
  26387. }
  26388. resultNode = this.setupOutput( builder, fragmentNode );
  26389. }
  26390. builder.stack.outputNode = resultNode;
  26391. builder.addFlow( 'fragment', builder.removeStack() );
  26392. // < MONITOR >
  26393. builder.monitor = this.setupObserver( builder );
  26394. }
  26395. setupClipping( builder ) {
  26396. if ( builder.clippingContext === null ) return null;
  26397. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26398. let result = null;
  26399. if ( globalClippingCount || localClippingCount ) {
  26400. const samples = builder.renderer.samples;
  26401. if ( this.alphaToCoverage && samples > 1 ) {
  26402. // to be added to flow when the color/alpha value has been determined
  26403. result = clippingAlpha();
  26404. } else {
  26405. builder.stack.add( clipping() );
  26406. }
  26407. }
  26408. return result;
  26409. }
  26410. setupDepth( builder ) {
  26411. const { renderer } = builder;
  26412. // Depth
  26413. let depthNode = this.depthNode;
  26414. if ( depthNode === null ) {
  26415. const mrt = renderer.getMRT();
  26416. if ( mrt && mrt.has( 'depth' ) ) {
  26417. depthNode = mrt.get( 'depth' );
  26418. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26419. const fragDepth = modelViewProjection().w.add( 1 );
  26420. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26421. }
  26422. }
  26423. if ( depthNode !== null ) {
  26424. depth.assign( depthNode ).append();
  26425. }
  26426. }
  26427. setupPosition( builder ) {
  26428. const { object } = builder;
  26429. const geometry = object.geometry;
  26430. builder.addStack();
  26431. // Vertex
  26432. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26433. morphReference( object ).append();
  26434. }
  26435. if ( object.isSkinnedMesh === true ) {
  26436. skinningReference( object ).append();
  26437. }
  26438. if ( this.displacementMap ) {
  26439. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26440. const displacementScale = materialReference( 'displacementScale', 'float' );
  26441. const displacementBias = materialReference( 'displacementBias', 'float' );
  26442. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26443. }
  26444. if ( object.isBatchedMesh ) {
  26445. batch( object ).append();
  26446. }
  26447. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26448. instance( object ).append();
  26449. }
  26450. if ( this.positionNode !== null ) {
  26451. positionLocal.assign( this.positionNode );
  26452. }
  26453. const mvp = modelViewProjection();
  26454. builder.context.vertex = builder.removeStack();
  26455. builder.context.mvp = mvp;
  26456. return mvp;
  26457. }
  26458. setupDiffuseColor( { object, geometry } ) {
  26459. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26460. // VERTEX COLORS
  26461. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26462. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26463. }
  26464. // Instanced colors
  26465. if ( object.instanceColor ) {
  26466. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26467. colorNode = instanceColor.mul( colorNode );
  26468. }
  26469. if ( object.isBatchedMesh && object._colorsTexture ) {
  26470. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26471. colorNode = batchColor.mul( colorNode );
  26472. }
  26473. // COLOR
  26474. diffuseColor.assign( colorNode );
  26475. // OPACITY
  26476. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26477. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26478. // ALPHA TEST
  26479. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26480. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26481. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26482. }
  26483. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26484. diffuseColor.a.assign( 1.0 );
  26485. }
  26486. }
  26487. setupVariants( /*builder*/ ) {
  26488. // Interface function.
  26489. }
  26490. setupOutgoingLight() {
  26491. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26492. }
  26493. setupNormal() {
  26494. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26495. }
  26496. setupEnvironment( /*builder*/ ) {
  26497. let node = null;
  26498. if ( this.envNode ) {
  26499. node = this.envNode;
  26500. } else if ( this.envMap ) {
  26501. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26502. }
  26503. return node;
  26504. }
  26505. setupLightMap( builder ) {
  26506. let node = null;
  26507. if ( builder.material.lightMap ) {
  26508. node = new IrradianceNode( materialLightMap );
  26509. }
  26510. return node;
  26511. }
  26512. setupLights( builder ) {
  26513. const materialLightsNode = [];
  26514. //
  26515. const envNode = this.setupEnvironment( builder );
  26516. if ( envNode && envNode.isLightingNode ) {
  26517. materialLightsNode.push( envNode );
  26518. }
  26519. const lightMapNode = this.setupLightMap( builder );
  26520. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26521. materialLightsNode.push( lightMapNode );
  26522. }
  26523. if ( this.aoNode !== null || builder.material.aoMap ) {
  26524. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26525. materialLightsNode.push( new AONode( aoNode ) );
  26526. }
  26527. let lightsN = this.lightsNode || builder.lightsNode;
  26528. if ( materialLightsNode.length > 0 ) {
  26529. lightsN = lights( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26530. }
  26531. return lightsN;
  26532. }
  26533. setupLightingModel( /*builder*/ ) {
  26534. // Interface function.
  26535. }
  26536. setupLighting( builder ) {
  26537. const { material } = builder;
  26538. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26539. // OUTGOING LIGHT
  26540. const lights = this.lights === true || this.lightsNode !== null;
  26541. const lightsNode = lights ? this.setupLights( builder ) : null;
  26542. let outgoingLightNode = this.setupOutgoingLight( builder );
  26543. if ( lightsNode && lightsNode.getScope().getLights().length > 0 ) {
  26544. const lightingModel = this.setupLightingModel( builder );
  26545. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26546. } else if ( backdropNode !== null ) {
  26547. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26548. }
  26549. // EMISSIVE
  26550. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26551. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26552. outgoingLightNode = outgoingLightNode.add( emissive );
  26553. }
  26554. return outgoingLightNode;
  26555. }
  26556. setupOutput( builder, outputNode ) {
  26557. // FOG
  26558. if ( this.fog === true ) {
  26559. const fogNode = builder.fogNode;
  26560. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26561. }
  26562. return outputNode;
  26563. }
  26564. setDefaultValues( material ) {
  26565. // This approach is to reuse the native refreshUniforms*
  26566. // and turn available the use of features like transmission and environment in core
  26567. for ( const property in material ) {
  26568. const value = material[ property ];
  26569. if ( this[ property ] === undefined ) {
  26570. this[ property ] = value;
  26571. if ( value && value.clone ) this[ property ] = value.clone();
  26572. }
  26573. }
  26574. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26575. for ( const key in descriptors ) {
  26576. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26577. descriptors[ key ].get !== undefined ) {
  26578. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26579. }
  26580. }
  26581. }
  26582. toJSON( meta ) {
  26583. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26584. if ( isRoot ) {
  26585. meta = {
  26586. textures: {},
  26587. images: {},
  26588. nodes: {}
  26589. };
  26590. }
  26591. const data = Material.prototype.toJSON.call( this, meta );
  26592. const nodeChildren = getNodeChildren( this );
  26593. data.inputNodes = {};
  26594. for ( const { property, childNode } of nodeChildren ) {
  26595. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26596. }
  26597. // TODO: Copied from Object3D.toJSON
  26598. function extractFromCache( cache ) {
  26599. const values = [];
  26600. for ( const key in cache ) {
  26601. const data = cache[ key ];
  26602. delete data.metadata;
  26603. values.push( data );
  26604. }
  26605. return values;
  26606. }
  26607. if ( isRoot ) {
  26608. const textures = extractFromCache( meta.textures );
  26609. const images = extractFromCache( meta.images );
  26610. const nodes = extractFromCache( meta.nodes );
  26611. if ( textures.length > 0 ) data.textures = textures;
  26612. if ( images.length > 0 ) data.images = images;
  26613. if ( nodes.length > 0 ) data.nodes = nodes;
  26614. }
  26615. return data;
  26616. }
  26617. copy( source ) {
  26618. this.lightsNode = source.lightsNode;
  26619. this.envNode = source.envNode;
  26620. this.colorNode = source.colorNode;
  26621. this.normalNode = source.normalNode;
  26622. this.opacityNode = source.opacityNode;
  26623. this.backdropNode = source.backdropNode;
  26624. this.backdropAlphaNode = source.backdropAlphaNode;
  26625. this.alphaTestNode = source.alphaTestNode;
  26626. this.positionNode = source.positionNode;
  26627. this.depthNode = source.depthNode;
  26628. this.shadowNode = source.shadowNode;
  26629. this.shadowPositionNode = source.shadowPositionNode;
  26630. this.outputNode = source.outputNode;
  26631. this.mrtNode = source.mrtNode;
  26632. this.fragmentNode = source.fragmentNode;
  26633. this.vertexNode = source.vertexNode;
  26634. return super.copy( source );
  26635. }
  26636. }
  26637. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26638. class InstancedPointsNodeMaterial extends NodeMaterial {
  26639. static get type() {
  26640. return 'InstancedPointsNodeMaterial';
  26641. }
  26642. constructor( params = {} ) {
  26643. super();
  26644. this.lights = false;
  26645. this.useAlphaToCoverage = true;
  26646. this.useColor = params.vertexColors;
  26647. this.pointWidth = 1;
  26648. this.pointColorNode = null;
  26649. this.pointWidthNode = null;
  26650. this.setDefaultValues( _defaultValues$e );
  26651. this.setValues( params );
  26652. }
  26653. setup( builder ) {
  26654. this.setupShaders( builder );
  26655. super.setup( builder );
  26656. }
  26657. setupShaders( { renderer } ) {
  26658. const useAlphaToCoverage = this.alphaToCoverage;
  26659. const useColor = this.useColor;
  26660. this.vertexNode = Fn( () => {
  26661. const instancePosition = attribute( 'instancePosition' ).xyz;
  26662. // camera space
  26663. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26664. const aspect = viewport.z.div( viewport.w );
  26665. // clip space
  26666. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26667. // offset in ndc space
  26668. const offset = positionGeometry.xy.toVar();
  26669. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26670. offset.assign( offset.div( viewport.z ) );
  26671. offset.y.assign( offset.y.mul( aspect ) );
  26672. // back to clip space
  26673. offset.assign( offset.mul( clipPos.w ) );
  26674. //clipPos.xy += offset;
  26675. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26676. return clipPos;
  26677. } )();
  26678. this.fragmentNode = Fn( () => {
  26679. const alpha = float( 1 ).toVar();
  26680. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26681. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26682. const dlen = float( len2.fwidth() ).toVar();
  26683. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26684. } else {
  26685. len2.greaterThan( 1.0 ).discard();
  26686. }
  26687. let pointColorNode;
  26688. if ( this.pointColorNode ) {
  26689. pointColorNode = this.pointColorNode;
  26690. } else {
  26691. if ( useColor ) {
  26692. const instanceColor = attribute( 'instanceColor' );
  26693. pointColorNode = instanceColor.mul( materialColor );
  26694. } else {
  26695. pointColorNode = materialColor;
  26696. }
  26697. }
  26698. alpha.mulAssign( materialOpacity );
  26699. return vec4( pointColorNode, alpha );
  26700. } )();
  26701. }
  26702. get alphaToCoverage() {
  26703. return this.useAlphaToCoverage;
  26704. }
  26705. set alphaToCoverage( value ) {
  26706. if ( this.useAlphaToCoverage !== value ) {
  26707. this.useAlphaToCoverage = value;
  26708. this.needsUpdate = true;
  26709. }
  26710. }
  26711. }
  26712. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  26713. class LineBasicNodeMaterial extends NodeMaterial {
  26714. static get type() {
  26715. return 'LineBasicNodeMaterial';
  26716. }
  26717. constructor( parameters ) {
  26718. super();
  26719. this.isLineBasicNodeMaterial = true;
  26720. this.lights = false;
  26721. this.setDefaultValues( _defaultValues$d );
  26722. this.setValues( parameters );
  26723. }
  26724. }
  26725. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  26726. class LineDashedNodeMaterial extends NodeMaterial {
  26727. static get type() {
  26728. return 'LineDashedNodeMaterial';
  26729. }
  26730. constructor( parameters ) {
  26731. super();
  26732. this.isLineDashedNodeMaterial = true;
  26733. this.lights = false;
  26734. this.setDefaultValues( _defaultValues$c );
  26735. this.offsetNode = null;
  26736. this.dashScaleNode = null;
  26737. this.dashSizeNode = null;
  26738. this.gapSizeNode = null;
  26739. this.setValues( parameters );
  26740. }
  26741. setupVariants() {
  26742. const offsetNode = this.offsetNode;
  26743. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26744. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26745. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26746. dashSize.assign( dashSizeNode );
  26747. gapSize.assign( gapSizeNode );
  26748. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  26749. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26750. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  26751. }
  26752. }
  26753. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  26754. class Line2NodeMaterial extends NodeMaterial {
  26755. static get type() {
  26756. return 'Line2NodeMaterial';
  26757. }
  26758. constructor( params = {} ) {
  26759. super();
  26760. this.lights = false;
  26761. this.setDefaultValues( _defaultValues$b );
  26762. this.useAlphaToCoverage = true;
  26763. this.useColor = params.vertexColors;
  26764. this.useDash = params.dashed;
  26765. this.useWorldUnits = false;
  26766. this.dashOffset = 0;
  26767. this.lineWidth = 1;
  26768. this.lineColorNode = null;
  26769. this.offsetNode = null;
  26770. this.dashScaleNode = null;
  26771. this.dashSizeNode = null;
  26772. this.gapSizeNode = null;
  26773. this.setValues( params );
  26774. }
  26775. setup( builder ) {
  26776. this.setupShaders( builder );
  26777. super.setup( builder );
  26778. }
  26779. setupShaders( { renderer } ) {
  26780. const useAlphaToCoverage = this.alphaToCoverage;
  26781. const useColor = this.useColor;
  26782. const useDash = this.dashed;
  26783. const useWorldUnits = this.worldUnits;
  26784. const trimSegment = Fn( ( { start, end } ) => {
  26785. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  26786. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  26787. const nearEstimate = b.mul( - 0.5 ).div( a );
  26788. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  26789. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  26790. } ).setLayout( {
  26791. name: 'trimSegment',
  26792. type: 'vec4',
  26793. inputs: [
  26794. { name: 'start', type: 'vec4' },
  26795. { name: 'end', type: 'vec4' }
  26796. ]
  26797. } );
  26798. this.vertexNode = Fn( () => {
  26799. const instanceStart = attribute( 'instanceStart' );
  26800. const instanceEnd = attribute( 'instanceEnd' );
  26801. // camera space
  26802. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  26803. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  26804. if ( useWorldUnits ) {
  26805. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  26806. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  26807. }
  26808. const aspect = viewport.z.div( viewport.w );
  26809. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  26810. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  26811. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  26812. // perhaps there is a more elegant solution -- WestLangley
  26813. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  26814. If( perspective, () => {
  26815. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  26816. end.assign( trimSegment( { start: start, end: end } ) );
  26817. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  26818. start.assign( trimSegment( { start: end, end: start } ) );
  26819. } );
  26820. } );
  26821. // clip space
  26822. const clipStart = cameraProjectionMatrix.mul( start );
  26823. const clipEnd = cameraProjectionMatrix.mul( end );
  26824. // ndc space
  26825. const ndcStart = clipStart.xyz.div( clipStart.w );
  26826. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  26827. // direction
  26828. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  26829. // account for clip-space aspect ratio
  26830. dir.x.assign( dir.x.mul( aspect ) );
  26831. dir.assign( dir.normalize() );
  26832. const clip = vec4().toVar();
  26833. if ( useWorldUnits ) {
  26834. // get the offset direction as perpendicular to the view vector
  26835. const worldDir = end.xyz.sub( start.xyz ).normalize();
  26836. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  26837. const worldUp = worldDir.cross( tmpFwd ).normalize();
  26838. const worldFwd = worldDir.cross( worldUp );
  26839. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  26840. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  26841. // height offset
  26842. const hw = materialLineWidth.mul( 0.5 );
  26843. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  26844. // don't extend the line if we're rendering dashes because we
  26845. // won't be rendering the endcaps
  26846. if ( ! useDash ) {
  26847. // cap extension
  26848. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  26849. // add width to the box
  26850. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  26851. // endcaps
  26852. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  26853. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  26854. } );
  26855. }
  26856. // project the worldpos
  26857. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  26858. // shift the depth of the projected points so the line
  26859. // segments overlap neatly
  26860. const clipPose = vec3().toVar();
  26861. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  26862. clip.z.assign( clipPose.z.mul( clip.w ) );
  26863. } else {
  26864. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  26865. // undo aspect ratio adjustment
  26866. dir.x.assign( dir.x.div( aspect ) );
  26867. offset.x.assign( offset.x.div( aspect ) );
  26868. // sign flip
  26869. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  26870. // endcaps
  26871. If( positionGeometry.y.lessThan( 0.0 ), () => {
  26872. offset.assign( offset.sub( dir ) );
  26873. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  26874. offset.assign( offset.add( dir ) );
  26875. } );
  26876. // adjust for linewidth
  26877. offset.assign( offset.mul( materialLineWidth ) );
  26878. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  26879. offset.assign( offset.div( viewport.w ) );
  26880. // select end
  26881. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  26882. // back to clip space
  26883. offset.assign( offset.mul( clip.w ) );
  26884. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  26885. }
  26886. return clip;
  26887. } )();
  26888. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  26889. const p13 = p1.sub( p3 );
  26890. const p43 = p4.sub( p3 );
  26891. const p21 = p2.sub( p1 );
  26892. const d1343 = p13.dot( p43 );
  26893. const d4321 = p43.dot( p21 );
  26894. const d1321 = p13.dot( p21 );
  26895. const d4343 = p43.dot( p43 );
  26896. const d2121 = p21.dot( p21 );
  26897. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  26898. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  26899. const mua = numer.div( denom ).clamp();
  26900. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  26901. return vec2( mua, mub );
  26902. } );
  26903. this.fragmentNode = Fn( () => {
  26904. const vUv = uv();
  26905. if ( useDash ) {
  26906. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  26907. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26908. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26909. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26910. dashSize.assign( dashSizeNode );
  26911. gapSize.assign( gapSizeNode );
  26912. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  26913. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  26914. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  26915. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  26916. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26917. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  26918. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  26919. }
  26920. const alpha = float( 1 ).toVar( 'alpha' );
  26921. if ( useWorldUnits ) {
  26922. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  26923. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  26924. // Find the closest points on the view ray and the line segment
  26925. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  26926. const lineDir = worldEnd.sub( worldStart );
  26927. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  26928. const p1 = worldStart.add( lineDir.mul( params.x ) );
  26929. const p2 = rayEnd.mul( params.y );
  26930. const delta = p1.sub( p2 );
  26931. const len = delta.length();
  26932. const norm = len.div( materialLineWidth );
  26933. if ( ! useDash ) {
  26934. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26935. const dnorm = norm.fwidth();
  26936. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  26937. } else {
  26938. norm.greaterThan( 0.5 ).discard();
  26939. }
  26940. }
  26941. } else {
  26942. // round endcaps
  26943. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26944. const a = vUv.x;
  26945. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  26946. const len2 = a.mul( a ).add( b.mul( b ) );
  26947. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  26948. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  26949. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26950. } );
  26951. } else {
  26952. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  26953. const a = vUv.x;
  26954. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  26955. const len2 = a.mul( a ).add( b.mul( b ) );
  26956. len2.greaterThan( 1.0 ).discard();
  26957. } );
  26958. }
  26959. }
  26960. let lineColorNode;
  26961. if ( this.lineColorNode ) {
  26962. lineColorNode = this.lineColorNode;
  26963. } else {
  26964. if ( useColor ) {
  26965. const instanceColorStart = attribute( 'instanceColorStart' );
  26966. const instanceColorEnd = attribute( 'instanceColorEnd' );
  26967. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  26968. lineColorNode = instanceColor.mul( materialColor );
  26969. } else {
  26970. lineColorNode = materialColor;
  26971. }
  26972. }
  26973. return vec4( lineColorNode, alpha );
  26974. } )();
  26975. }
  26976. get worldUnits() {
  26977. return this.useWorldUnits;
  26978. }
  26979. set worldUnits( value ) {
  26980. if ( this.useWorldUnits !== value ) {
  26981. this.useWorldUnits = value;
  26982. this.needsUpdate = true;
  26983. }
  26984. }
  26985. get dashed() {
  26986. return this.useDash;
  26987. }
  26988. set dashed( value ) {
  26989. if ( this.useDash !== value ) {
  26990. this.useDash = value;
  26991. this.needsUpdate = true;
  26992. }
  26993. }
  26994. get alphaToCoverage() {
  26995. return this.useAlphaToCoverage;
  26996. }
  26997. set alphaToCoverage( value ) {
  26998. if ( this.useAlphaToCoverage !== value ) {
  26999. this.useAlphaToCoverage = value;
  27000. this.needsUpdate = true;
  27001. }
  27002. }
  27003. }
  27004. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  27005. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  27006. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  27007. class MeshNormalNodeMaterial extends NodeMaterial {
  27008. static get type() {
  27009. return 'MeshNormalNodeMaterial';
  27010. }
  27011. constructor( parameters ) {
  27012. super();
  27013. this.lights = false;
  27014. this.isMeshNormalNodeMaterial = true;
  27015. this.setDefaultValues( _defaultValues$a );
  27016. this.setValues( parameters );
  27017. }
  27018. setupDiffuseColor() {
  27019. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27020. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  27021. }
  27022. }
  27023. class EquirectUVNode extends TempNode {
  27024. static get type() {
  27025. return 'EquirectUVNode';
  27026. }
  27027. constructor( dirNode = positionWorldDirection ) {
  27028. super( 'vec2' );
  27029. this.dirNode = dirNode;
  27030. }
  27031. setup() {
  27032. const dir = this.dirNode;
  27033. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27034. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27035. return vec2( u, v );
  27036. }
  27037. }
  27038. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  27039. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27040. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27041. constructor( size = 1, options = {} ) {
  27042. super( size, options );
  27043. this.isCubeRenderTarget = true;
  27044. }
  27045. fromEquirectangularTexture( renderer, texture$1 ) {
  27046. const currentMinFilter = texture$1.minFilter;
  27047. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27048. texture$1.generateMipmaps = true;
  27049. this.texture.type = texture$1.type;
  27050. this.texture.colorSpace = texture$1.colorSpace;
  27051. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27052. this.texture.minFilter = texture$1.minFilter;
  27053. this.texture.magFilter = texture$1.magFilter;
  27054. const geometry = new BoxGeometry( 5, 5, 5 );
  27055. const uvNode = equirectUV( positionWorldDirection );
  27056. const material = new NodeMaterial();
  27057. material.colorNode = texture( texture$1, uvNode, 0 );
  27058. material.side = BackSide;
  27059. material.blending = NoBlending;
  27060. const mesh = new Mesh( geometry, material );
  27061. const scene = new Scene();
  27062. scene.add( mesh );
  27063. // Avoid blurred poles
  27064. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27065. const camera = new CubeCamera( 1, 10, this );
  27066. const currentMRT = renderer.getMRT();
  27067. renderer.setMRT( null );
  27068. camera.update( renderer, scene );
  27069. renderer.setMRT( currentMRT );
  27070. texture$1.minFilter = currentMinFilter;
  27071. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27072. mesh.geometry.dispose();
  27073. mesh.material.dispose();
  27074. return this;
  27075. }
  27076. }
  27077. const _cache$1 = new WeakMap();
  27078. class CubeMapNode extends TempNode {
  27079. static get type() {
  27080. return 'CubeMapNode';
  27081. }
  27082. constructor( envNode ) {
  27083. super( 'vec3' );
  27084. this.envNode = envNode;
  27085. this._cubeTexture = null;
  27086. this._cubeTextureNode = cubeTexture();
  27087. const defaultTexture = new CubeTexture();
  27088. defaultTexture.isRenderTargetTexture = true;
  27089. this._defaultTexture = defaultTexture;
  27090. this.updateBeforeType = NodeUpdateType.RENDER;
  27091. }
  27092. updateBefore( frame ) {
  27093. const { renderer, material } = frame;
  27094. const envNode = this.envNode;
  27095. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27096. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27097. if ( texture && texture.isTexture ) {
  27098. const mapping = texture.mapping;
  27099. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27100. // check for converted cubemap map
  27101. if ( _cache$1.has( texture ) ) {
  27102. const cubeMap = _cache$1.get( texture );
  27103. mapTextureMapping( cubeMap, texture.mapping );
  27104. this._cubeTexture = cubeMap;
  27105. } else {
  27106. // create cube map from equirectangular map
  27107. const image = texture.image;
  27108. if ( isEquirectangularMapReady$1( image ) ) {
  27109. const renderTarget = new CubeRenderTarget( image.height );
  27110. renderTarget.fromEquirectangularTexture( renderer, texture );
  27111. mapTextureMapping( renderTarget.texture, texture.mapping );
  27112. this._cubeTexture = renderTarget.texture;
  27113. _cache$1.set( texture, renderTarget.texture );
  27114. texture.addEventListener( 'dispose', onTextureDispose );
  27115. } else {
  27116. // default cube texture as fallback when equirectangular texture is not yet loaded
  27117. this._cubeTexture = this._defaultTexture;
  27118. }
  27119. }
  27120. //
  27121. this._cubeTextureNode.value = this._cubeTexture;
  27122. } else {
  27123. // envNode already refers to a cube map
  27124. this._cubeTextureNode = this.envNode;
  27125. }
  27126. }
  27127. }
  27128. }
  27129. setup( builder ) {
  27130. this.updateBefore( builder );
  27131. return this._cubeTextureNode;
  27132. }
  27133. }
  27134. function isEquirectangularMapReady$1( image ) {
  27135. if ( image === null || image === undefined ) return false;
  27136. return image.height > 0;
  27137. }
  27138. function onTextureDispose( event ) {
  27139. const texture = event.target;
  27140. texture.removeEventListener( 'dispose', onTextureDispose );
  27141. const renderTarget = _cache$1.get( texture );
  27142. if ( renderTarget !== undefined ) {
  27143. _cache$1.delete( texture );
  27144. renderTarget.dispose();
  27145. }
  27146. }
  27147. function mapTextureMapping( texture, mapping ) {
  27148. if ( mapping === EquirectangularReflectionMapping ) {
  27149. texture.mapping = CubeReflectionMapping;
  27150. } else if ( mapping === EquirectangularRefractionMapping ) {
  27151. texture.mapping = CubeRefractionMapping;
  27152. }
  27153. }
  27154. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27155. class BasicEnvironmentNode extends LightingNode {
  27156. static get type() {
  27157. return 'BasicEnvironmentNode';
  27158. }
  27159. constructor( envNode = null ) {
  27160. super();
  27161. this.envNode = envNode;
  27162. }
  27163. setup( builder ) {
  27164. // environment property is used in the finish() method of BasicLightingModel
  27165. builder.context.environment = cubeMapNode( this.envNode );
  27166. }
  27167. }
  27168. class BasicLightMapNode extends LightingNode {
  27169. static get type() {
  27170. return 'BasicLightMapNode';
  27171. }
  27172. constructor( lightMapNode = null ) {
  27173. super();
  27174. this.lightMapNode = lightMapNode;
  27175. }
  27176. setup( builder ) {
  27177. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27178. const RECIPROCAL_PI = float( 1 / Math.PI );
  27179. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27180. }
  27181. }
  27182. class LightingModel {
  27183. start( /*input, stack, builder*/ ) { }
  27184. finish( /*input, stack, builder*/ ) { }
  27185. direct( /*input, stack, builder*/ ) { }
  27186. directRectArea( /*input, stack, builder*/ ) {}
  27187. indirect( /*input, stack, builder*/ ) { }
  27188. ambientOcclusion( /*input, stack, builder*/ ) { }
  27189. }
  27190. class BasicLightingModel extends LightingModel {
  27191. constructor() {
  27192. super();
  27193. }
  27194. indirect( context, stack, builder ) {
  27195. const ambientOcclusion = context.ambientOcclusion;
  27196. const reflectedLight = context.reflectedLight;
  27197. const irradianceLightMap = builder.context.irradianceLightMap;
  27198. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27199. // accumulation (baked indirect lighting only)
  27200. if ( irradianceLightMap ) {
  27201. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27202. } else {
  27203. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27204. }
  27205. // modulation
  27206. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27207. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27208. }
  27209. finish( context, stack, builder ) {
  27210. const material = builder.material;
  27211. const outgoingLight = context.outgoingLight;
  27212. const envNode = builder.context.environment;
  27213. if ( envNode ) {
  27214. switch ( material.combine ) {
  27215. case MultiplyOperation:
  27216. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27217. break;
  27218. case MixOperation:
  27219. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27220. break;
  27221. case AddOperation:
  27222. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27223. break;
  27224. default:
  27225. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27226. break;
  27227. }
  27228. }
  27229. }
  27230. }
  27231. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27232. class MeshBasicNodeMaterial extends NodeMaterial {
  27233. static get type() {
  27234. return 'MeshBasicNodeMaterial';
  27235. }
  27236. constructor( parameters ) {
  27237. super();
  27238. this.isMeshBasicNodeMaterial = true;
  27239. this.lights = true;
  27240. this.setDefaultValues( _defaultValues$9 );
  27241. this.setValues( parameters );
  27242. }
  27243. setupNormal() {
  27244. return normalView; // see #28839
  27245. }
  27246. setupEnvironment( builder ) {
  27247. const envNode = super.setupEnvironment( builder );
  27248. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27249. }
  27250. setupLightMap( builder ) {
  27251. let node = null;
  27252. if ( builder.material.lightMap ) {
  27253. node = new BasicLightMapNode( materialLightMap );
  27254. }
  27255. return node;
  27256. }
  27257. setupOutgoingLight() {
  27258. return diffuseColor.rgb;
  27259. }
  27260. setupLightingModel() {
  27261. return new BasicLightingModel();
  27262. }
  27263. }
  27264. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27265. // Original approximation by Christophe Schlick '94
  27266. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27267. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27268. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27269. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27270. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27271. } ); // validated
  27272. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27273. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27274. } ); // validated
  27275. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27276. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27277. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27278. } );
  27279. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27280. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27281. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27282. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27283. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27284. const G = G_BlinnPhong_Implicit();
  27285. const D = D_BlinnPhong( { dotNH } );
  27286. return F.mul( G ).mul( D );
  27287. } );
  27288. class PhongLightingModel extends BasicLightingModel {
  27289. constructor( specular = true ) {
  27290. super();
  27291. this.specular = specular;
  27292. }
  27293. direct( { lightDirection, lightColor, reflectedLight } ) {
  27294. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27295. const irradiance = dotNL.mul( lightColor );
  27296. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27297. if ( this.specular === true ) {
  27298. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27299. }
  27300. }
  27301. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27302. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27303. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27304. }
  27305. }
  27306. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27307. class MeshLambertNodeMaterial extends NodeMaterial {
  27308. static get type() {
  27309. return 'MeshLambertNodeMaterial';
  27310. }
  27311. constructor( parameters ) {
  27312. super();
  27313. this.isMeshLambertNodeMaterial = true;
  27314. this.lights = true;
  27315. this.setDefaultValues( _defaultValues$8 );
  27316. this.setValues( parameters );
  27317. }
  27318. setupEnvironment( builder ) {
  27319. const envNode = super.setupEnvironment( builder );
  27320. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27321. }
  27322. setupLightingModel( /*builder*/ ) {
  27323. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27324. }
  27325. }
  27326. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27327. class MeshPhongNodeMaterial extends NodeMaterial {
  27328. static get type() {
  27329. return 'MeshPhongNodeMaterial';
  27330. }
  27331. constructor( parameters ) {
  27332. super();
  27333. this.isMeshPhongNodeMaterial = true;
  27334. this.lights = true;
  27335. this.shininessNode = null;
  27336. this.specularNode = null;
  27337. this.setDefaultValues( _defaultValues$7 );
  27338. this.setValues( parameters );
  27339. }
  27340. setupEnvironment( builder ) {
  27341. const envNode = super.setupEnvironment( builder );
  27342. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27343. }
  27344. setupLightingModel( /*builder*/ ) {
  27345. return new PhongLightingModel();
  27346. }
  27347. setupVariants() {
  27348. // SHININESS
  27349. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27350. shininess.assign( shininessNode );
  27351. // SPECULAR COLOR
  27352. const specularNode = this.specularNode || materialSpecular;
  27353. specularColor.assign( specularNode );
  27354. }
  27355. copy( source ) {
  27356. this.shininessNode = source.shininessNode;
  27357. this.specularNode = source.specularNode;
  27358. return super.copy( source );
  27359. }
  27360. }
  27361. const getGeometryRoughness = /*@__PURE__*/ Fn( () => {
  27362. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27363. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27364. return geometryRoughness;
  27365. } );
  27366. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27367. const { roughness } = inputs;
  27368. const geometryRoughness = getGeometryRoughness();
  27369. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27370. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27371. roughnessFactor = roughnessFactor.min( 1.0 );
  27372. return roughnessFactor;
  27373. } );
  27374. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27375. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27376. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27377. const a2 = alpha.pow2();
  27378. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27379. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27380. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27381. } ).setLayout( {
  27382. name: 'V_GGX_SmithCorrelated',
  27383. type: 'float',
  27384. inputs: [
  27385. { name: 'alpha', type: 'float' },
  27386. { name: 'dotNL', type: 'float' },
  27387. { name: 'dotNV', type: 'float' }
  27388. ]
  27389. } ); // validated
  27390. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27391. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27392. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27393. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27394. const v = div( 0.5, gv.add( gl ) );
  27395. return v.saturate();
  27396. } ).setLayout( {
  27397. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27398. type: 'float',
  27399. inputs: [
  27400. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27401. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27402. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27403. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27404. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27405. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27406. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27407. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27408. ]
  27409. } );
  27410. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27411. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27412. // alpha is "roughness squared" in Disney’s reparameterization
  27413. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27414. const a2 = alpha.pow2();
  27415. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27416. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27417. } ).setLayout( {
  27418. name: 'D_GGX',
  27419. type: 'float',
  27420. inputs: [
  27421. { name: 'alpha', type: 'float' },
  27422. { name: 'dotNH', type: 'float' }
  27423. ]
  27424. } ); // validated
  27425. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27426. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27427. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27428. const a2 = alphaT.mul( alphaB );
  27429. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27430. const v2 = v.dot( v );
  27431. const w2 = a2.div( v2 );
  27432. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27433. } ).setLayout( {
  27434. name: 'D_GGX_Anisotropic',
  27435. type: 'float',
  27436. inputs: [
  27437. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27438. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27439. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27440. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27441. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27442. ]
  27443. } );
  27444. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27445. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27446. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27447. const normalView = inputs.normalView || transformedNormalView;
  27448. const alpha = roughness.pow2(); // UE4's roughness
  27449. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27450. const dotNL = normalView.dot( lightDirection ).clamp();
  27451. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27452. const dotNH = normalView.dot( halfDir ).clamp();
  27453. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27454. let F = F_Schlick( { f0, f90, dotVH } );
  27455. let V, D;
  27456. if ( defined( USE_IRIDESCENCE ) ) {
  27457. F = iridescence.mix( F, f );
  27458. }
  27459. if ( defined( USE_ANISOTROPY ) ) {
  27460. const dotTL = anisotropyT.dot( lightDirection );
  27461. const dotTV = anisotropyT.dot( positionViewDirection );
  27462. const dotTH = anisotropyT.dot( halfDir );
  27463. const dotBL = anisotropyB.dot( lightDirection );
  27464. const dotBV = anisotropyB.dot( positionViewDirection );
  27465. const dotBH = anisotropyB.dot( halfDir );
  27466. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27467. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27468. } else {
  27469. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27470. D = D_GGX( { alpha, dotNH } );
  27471. }
  27472. return F.mul( V ).mul( D );
  27473. } ); // validated
  27474. // Analytical approximation of the DFG LUT, one half of the
  27475. // split-sum approximation used in indirect specular lighting.
  27476. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27477. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27478. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27479. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27480. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27481. const r = roughness.mul( c0 ).add( c1 );
  27482. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27483. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27484. return fab;
  27485. } ).setLayout( {
  27486. name: 'DFGApprox',
  27487. type: 'vec2',
  27488. inputs: [
  27489. { name: 'roughness', type: 'float' },
  27490. { name: 'dotNV', type: 'vec3' }
  27491. ]
  27492. } );
  27493. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27494. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27495. const fab = DFGApprox( { dotNV, roughness } );
  27496. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27497. } );
  27498. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27499. const x = dotVH.oneMinus().saturate();
  27500. const x2 = x.mul( x );
  27501. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27502. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27503. } ).setLayout( {
  27504. name: 'Schlick_to_F0',
  27505. type: 'vec3',
  27506. inputs: [
  27507. { name: 'f', type: 'vec3' },
  27508. { name: 'f90', type: 'float' },
  27509. { name: 'dotVH', type: 'float' }
  27510. ]
  27511. } );
  27512. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27513. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27514. const alpha = roughness.pow2();
  27515. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27516. const invAlpha = float( 1.0 ).div( alpha );
  27517. const cos2h = dotNH.pow2();
  27518. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27519. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27520. } ).setLayout( {
  27521. name: 'D_Charlie',
  27522. type: 'float',
  27523. inputs: [
  27524. { name: 'roughness', type: 'float' },
  27525. { name: 'dotNH', type: 'float' }
  27526. ]
  27527. } );
  27528. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27529. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27530. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27531. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27532. } ).setLayout( {
  27533. name: 'V_Neubelt',
  27534. type: 'float',
  27535. inputs: [
  27536. { name: 'dotNV', type: 'float' },
  27537. { name: 'dotNL', type: 'float' }
  27538. ]
  27539. } );
  27540. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27541. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27542. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27543. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27544. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27545. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27546. const V = V_Neubelt( { dotNV, dotNL } );
  27547. return sheen.mul( D ).mul( V );
  27548. } );
  27549. // Rect Area Light
  27550. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27551. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27552. // code: https://github.com/selfshadow/ltc_code/
  27553. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27554. const LUT_SIZE = 64.0;
  27555. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27556. const LUT_BIAS = 0.5 / LUT_SIZE;
  27557. const dotNV = N.dot( V ).saturate();
  27558. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27559. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27560. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27561. return uv;
  27562. } ).setLayout( {
  27563. name: 'LTC_Uv',
  27564. type: 'vec2',
  27565. inputs: [
  27566. { name: 'N', type: 'vec3' },
  27567. { name: 'V', type: 'vec3' },
  27568. { name: 'roughness', type: 'float' }
  27569. ]
  27570. } );
  27571. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27572. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27573. // An approximation of the form factor of a horizon-clipped rectangle.
  27574. const l = f.length();
  27575. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27576. } ).setLayout( {
  27577. name: 'LTC_ClippedSphereFormFactor',
  27578. type: 'float',
  27579. inputs: [
  27580. { name: 'f', type: 'vec3' }
  27581. ]
  27582. } );
  27583. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27584. const x = v1.dot( v2 );
  27585. const y = x.abs().toVar();
  27586. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27587. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27588. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27589. const v = a.div( b );
  27590. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27591. return v1.cross( v2 ).mul( theta_sintheta );
  27592. } ).setLayout( {
  27593. name: 'LTC_EdgeVectorFormFactor',
  27594. type: 'vec3',
  27595. inputs: [
  27596. { name: 'v1', type: 'vec3' },
  27597. { name: 'v2', type: 'vec3' }
  27598. ]
  27599. } );
  27600. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27601. // bail if point is on back side of plane of light
  27602. // assumes ccw winding order of light vertices
  27603. const v1 = p1.sub( p0 ).toVar();
  27604. const v2 = p3.sub( p0 ).toVar();
  27605. const lightNormal = v1.cross( v2 );
  27606. const result = vec3().toVar();
  27607. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27608. // construct orthonormal basis around N
  27609. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27610. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27611. // compute transform
  27612. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27613. // transform rect
  27614. // & project rect onto sphere
  27615. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27616. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27617. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27618. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27619. // calculate vector form factor
  27620. const vectorFormFactor = vec3( 0 ).toVar();
  27621. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27622. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27623. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27624. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27625. // adjust for horizon clipping
  27626. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27627. } );
  27628. return result;
  27629. } ).setLayout( {
  27630. name: 'LTC_Evaluate',
  27631. type: 'vec3',
  27632. inputs: [
  27633. { name: 'N', type: 'vec3' },
  27634. { name: 'V', type: 'vec3' },
  27635. { name: 'P', type: 'vec3' },
  27636. { name: 'mInv', type: 'mat3' },
  27637. { name: 'p0', type: 'vec3' },
  27638. { name: 'p1', type: 'vec3' },
  27639. { name: 'p2', type: 'vec3' },
  27640. { name: 'p3', type: 'vec3' }
  27641. ]
  27642. } );
  27643. // Mipped Bicubic Texture Filtering by N8
  27644. // https://www.shadertoy.com/view/Dl2SDW
  27645. const bC = 1.0 / 6.0;
  27646. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27647. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27648. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27649. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27650. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27651. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27652. // h0 and h1 are the two offset functions
  27653. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27654. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27655. const bicubic = ( textureNode, texelSize, lod ) => {
  27656. const uv = textureNode.uvNode;
  27657. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27658. const iuv = floor( uvScaled );
  27659. const fuv = fract( uvScaled );
  27660. const g0x = g0( fuv.x );
  27661. const g1x = g1( fuv.x );
  27662. const h0x = h0( fuv.x );
  27663. const h1x = h1( fuv.x );
  27664. const h0y = h0( fuv.y );
  27665. const h1y = h1( fuv.y );
  27666. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27667. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27668. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27669. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27670. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27671. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27672. return a.add( b );
  27673. };
  27674. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27675. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27676. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27677. const fLodSizeInv = div( 1.0, fLodSize );
  27678. const cLodSizeInv = div( 1.0, cLodSize );
  27679. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27680. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27681. return fract( lodNode ).mix( fSample, cSample );
  27682. } );
  27683. //
  27684. // Transmission
  27685. //
  27686. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  27687. // Direction of refracted light.
  27688. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  27689. // Compute rotation-independant scaling of the model matrix.
  27690. const modelScale = vec3(
  27691. length( modelMatrix[ 0 ].xyz ),
  27692. length( modelMatrix[ 1 ].xyz ),
  27693. length( modelMatrix[ 2 ].xyz )
  27694. );
  27695. // The thickness is specified in local space.
  27696. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  27697. } ).setLayout( {
  27698. name: 'getVolumeTransmissionRay',
  27699. type: 'vec3',
  27700. inputs: [
  27701. { name: 'n', type: 'vec3' },
  27702. { name: 'v', type: 'vec3' },
  27703. { name: 'thickness', type: 'float' },
  27704. { name: 'ior', type: 'float' },
  27705. { name: 'modelMatrix', type: 'mat4' }
  27706. ]
  27707. } );
  27708. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  27709. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  27710. // an IOR of 1.5 results in the default amount of microfacet refraction.
  27711. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  27712. } ).setLayout( {
  27713. name: 'applyIorToRoughness',
  27714. type: 'float',
  27715. inputs: [
  27716. { name: 'roughness', type: 'float' },
  27717. { name: 'ior', type: 'float' }
  27718. ]
  27719. } );
  27720. const singleViewportMipTexture = /*@__PURE__*/ viewportMipTexture();
  27721. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ] ) => {
  27722. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  27723. //const transmissionSample = viewportMipTexture( fragCoord );
  27724. const lod = log2( float( screenSize.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  27725. return textureBicubic( transmissionSample, lod );
  27726. } );
  27727. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  27728. If( attenuationDistance.notEqual( 0 ), () => {
  27729. // Compute light attenuation using Beer's law.
  27730. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  27731. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  27732. return transmittance;
  27733. } );
  27734. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  27735. return vec3( 1.0 );
  27736. } ).setLayout( {
  27737. name: 'volumeAttenuation',
  27738. type: 'vec3',
  27739. inputs: [
  27740. { name: 'transmissionDistance', type: 'float' },
  27741. { name: 'attenuationColor', type: 'vec3' },
  27742. { name: 'attenuationDistance', type: 'float' }
  27743. ]
  27744. } );
  27745. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  27746. let transmittedLight, transmittance;
  27747. if ( dispersion ) {
  27748. transmittedLight = vec4().toVar();
  27749. transmittance = vec3().toVar();
  27750. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  27751. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  27752. Loop( { start: 0, end: 3 }, ( { i } ) => {
  27753. const ior = iors.element( i );
  27754. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27755. const refractedRayExit = position.add( transmissionRay );
  27756. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27757. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27758. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27759. refractionCoords.addAssign( 1.0 );
  27760. refractionCoords.divAssign( 2.0 );
  27761. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27762. // Sample framebuffer to get pixel the refracted ray hits.
  27763. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  27764. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  27765. transmittedLight.a.addAssign( transmissionSample.a );
  27766. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  27767. } );
  27768. transmittedLight.a.divAssign( 3.0 );
  27769. } else {
  27770. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27771. const refractedRayExit = position.add( transmissionRay );
  27772. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27773. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27774. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27775. refractionCoords.addAssign( 1.0 );
  27776. refractionCoords.divAssign( 2.0 );
  27777. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27778. // Sample framebuffer to get pixel the refracted ray hits.
  27779. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  27780. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  27781. }
  27782. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  27783. const dotNV = n.dot( v ).clamp();
  27784. // Get the specular component.
  27785. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  27786. dotNV,
  27787. specularColor,
  27788. specularF90,
  27789. roughness
  27790. } ) );
  27791. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  27792. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  27793. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  27794. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  27795. } );
  27796. //
  27797. // Iridescence
  27798. //
  27799. // XYZ to linear-sRGB color space
  27800. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  27801. 3.2404542, - 0.9692660, 0.0556434,
  27802. - 1.5371385, 1.8760108, - 0.2040259,
  27803. - 0.4985314, 0.0415560, 1.0572252
  27804. );
  27805. // Assume air interface for top
  27806. // Note: We don't handle the case fresnel0 == 1
  27807. const Fresnel0ToIor = ( fresnel0 ) => {
  27808. const sqrtF0 = fresnel0.sqrt();
  27809. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  27810. };
  27811. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  27812. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  27813. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  27814. };
  27815. // Fresnel equations for dielectric/dielectric interfaces.
  27816. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  27817. // Evaluation XYZ sensitivity curves in Fourier space
  27818. const evalSensitivity = ( OPD, shift ) => {
  27819. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  27820. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  27821. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  27822. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  27823. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  27824. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  27825. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  27826. const rgb = XYZ_TO_REC709.mul( xyz );
  27827. return rgb;
  27828. };
  27829. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  27830. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  27831. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  27832. // Evaluate the cosTheta on the base layer (Snell law)
  27833. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  27834. // Handle TIR:
  27835. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  27836. /*if ( cosTheta2Sq < 0.0 ) {
  27837. return vec3( 1.0 );
  27838. }*/
  27839. const cosTheta2 = cosTheta2Sq.sqrt();
  27840. // First interface
  27841. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  27842. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  27843. //const R21 = R12;
  27844. const T121 = R12.oneMinus();
  27845. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  27846. const phi21 = float( Math.PI ).sub( phi12 );
  27847. // Second interface
  27848. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  27849. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  27850. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  27851. const phi23 = vec3(
  27852. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  27853. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  27854. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  27855. );
  27856. // Phase shift
  27857. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  27858. const phi = vec3( phi21 ).add( phi23 );
  27859. // Compound terms
  27860. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  27861. const r123 = R123.sqrt();
  27862. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  27863. // Reflectance term for m = 0 (DC term amplitude)
  27864. const C0 = R12.add( Rs );
  27865. let I = C0;
  27866. // Reflectance term for m > 0 (pairs of diracs)
  27867. let Cm = Rs.sub( T121 );
  27868. for ( let m = 1; m <= 2; ++ m ) {
  27869. Cm = Cm.mul( r123 );
  27870. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  27871. I = I.add( Cm.mul( Sm ) );
  27872. }
  27873. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  27874. return I.max( vec3( 0.0 ) );
  27875. } ).setLayout( {
  27876. name: 'evalIridescence',
  27877. type: 'vec3',
  27878. inputs: [
  27879. { name: 'outsideIOR', type: 'float' },
  27880. { name: 'eta2', type: 'float' },
  27881. { name: 'cosTheta1', type: 'float' },
  27882. { name: 'thinFilmThickness', type: 'float' },
  27883. { name: 'baseF0', type: 'vec3' }
  27884. ]
  27885. } );
  27886. //
  27887. // Sheen
  27888. //
  27889. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  27890. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  27891. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  27892. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  27893. const dotNV = normal.dot( viewDir ).saturate();
  27894. const r2 = roughness.pow2();
  27895. const a = select(
  27896. roughness.lessThan( 0.25 ),
  27897. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  27898. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  27899. );
  27900. const b = select(
  27901. roughness.lessThan( 0.25 ),
  27902. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  27903. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  27904. );
  27905. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  27906. return DG.mul( 1.0 / Math.PI ).saturate();
  27907. } );
  27908. const clearcoatF0 = vec3( 0.04 );
  27909. const clearcoatF90 = float( 1 );
  27910. //
  27911. class PhysicalLightingModel extends LightingModel {
  27912. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  27913. super();
  27914. this.clearcoat = clearcoat;
  27915. this.sheen = sheen;
  27916. this.iridescence = iridescence;
  27917. this.anisotropy = anisotropy;
  27918. this.transmission = transmission;
  27919. this.dispersion = dispersion;
  27920. this.clearcoatRadiance = null;
  27921. this.clearcoatSpecularDirect = null;
  27922. this.clearcoatSpecularIndirect = null;
  27923. this.sheenSpecularDirect = null;
  27924. this.sheenSpecularIndirect = null;
  27925. this.iridescenceFresnel = null;
  27926. this.iridescenceF0 = null;
  27927. }
  27928. start( context ) {
  27929. if ( this.clearcoat === true ) {
  27930. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  27931. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  27932. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  27933. }
  27934. if ( this.sheen === true ) {
  27935. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  27936. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  27937. }
  27938. if ( this.iridescence === true ) {
  27939. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  27940. this.iridescenceFresnel = evalIridescence( {
  27941. outsideIOR: float( 1.0 ),
  27942. eta2: iridescenceIOR,
  27943. cosTheta1: dotNVi,
  27944. thinFilmThickness: iridescenceThickness,
  27945. baseF0: specularColor
  27946. } );
  27947. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  27948. }
  27949. if ( this.transmission === true ) {
  27950. const position = positionWorld;
  27951. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  27952. const n = transformedNormalWorld;
  27953. context.backdrop = getIBLVolumeRefraction(
  27954. n,
  27955. v,
  27956. roughness,
  27957. diffuseColor,
  27958. specularColor,
  27959. specularF90, // specularF90
  27960. position, // positionWorld
  27961. modelWorldMatrix, // modelMatrix
  27962. cameraViewMatrix, // viewMatrix
  27963. cameraProjectionMatrix, // projMatrix
  27964. ior,
  27965. thickness,
  27966. attenuationColor,
  27967. attenuationDistance,
  27968. this.dispersion ? dispersion : null
  27969. );
  27970. context.backdropAlpha = transmission;
  27971. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  27972. }
  27973. }
  27974. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  27975. // Approximates multiscattering in order to preserve energy.
  27976. // http://www.jcgt.org/published/0008/01/03/
  27977. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  27978. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27979. const fab = DFGApprox( { roughness, dotNV } );
  27980. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  27981. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27982. const Ess = fab.x.add( fab.y );
  27983. const Ems = Ess.oneMinus();
  27984. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  27985. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  27986. singleScatter.addAssign( FssEss );
  27987. multiScatter.addAssign( Fms.mul( Ems ) );
  27988. }
  27989. direct( { lightDirection, lightColor, reflectedLight } ) {
  27990. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27991. const irradiance = dotNL.mul( lightColor );
  27992. if ( this.sheen === true ) {
  27993. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  27994. }
  27995. if ( this.clearcoat === true ) {
  27996. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  27997. const ccIrradiance = dotNLcc.mul( lightColor );
  27998. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  27999. }
  28000. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28001. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  28002. }
  28003. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  28004. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  28005. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  28006. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  28007. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  28008. const N = transformedNormalView;
  28009. const V = positionViewDirection;
  28010. const P = positionView.toVar();
  28011. const uv = LTC_Uv( { N, V, roughness } );
  28012. const t1 = ltc_1.uv( uv ).toVar();
  28013. const t2 = ltc_2.uv( uv ).toVar();
  28014. const mInv = mat3(
  28015. vec3( t1.x, 0, t1.y ),
  28016. vec3( 0, 1, 0 ),
  28017. vec3( t1.z, 0, t1.w )
  28018. ).toVar();
  28019. // LTC Fresnel Approximation by Stephen Hill
  28020. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  28021. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  28022. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  28023. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  28024. }
  28025. indirect( context, stack, builder ) {
  28026. this.indirectDiffuse( context, stack, builder );
  28027. this.indirectSpecular( context, stack, builder );
  28028. this.ambientOcclusion( context, stack, builder );
  28029. }
  28030. indirectDiffuse( { irradiance, reflectedLight } ) {
  28031. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28032. }
  28033. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  28034. if ( this.sheen === true ) {
  28035. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  28036. sheen,
  28037. IBLSheenBRDF( {
  28038. normal: transformedNormalView,
  28039. viewDir: positionViewDirection,
  28040. roughness: sheenRoughness
  28041. } )
  28042. ) );
  28043. }
  28044. if ( this.clearcoat === true ) {
  28045. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28046. const clearcoatEnv = EnvironmentBRDF( {
  28047. dotNV: dotNVcc,
  28048. specularColor: clearcoatF0,
  28049. specularF90: clearcoatF90,
  28050. roughness: clearcoatRoughness
  28051. } );
  28052. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  28053. }
  28054. // Both indirect specular and indirect diffuse light accumulate here
  28055. const singleScattering = vec3().toVar( 'singleScattering' );
  28056. const multiScattering = vec3().toVar( 'multiScattering' );
  28057. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  28058. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  28059. const totalScattering = singleScattering.add( multiScattering );
  28060. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  28061. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  28062. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  28063. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  28064. }
  28065. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  28066. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28067. const aoNV = dotNV.add( ambientOcclusion );
  28068. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  28069. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  28070. if ( this.clearcoat === true ) {
  28071. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  28072. }
  28073. if ( this.sheen === true ) {
  28074. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  28075. }
  28076. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28077. reflectedLight.indirectSpecular.mulAssign( aoNode );
  28078. }
  28079. finish( context ) {
  28080. const { outgoingLight } = context;
  28081. if ( this.clearcoat === true ) {
  28082. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28083. const Fcc = F_Schlick( {
  28084. dotVH: dotNVcc,
  28085. f0: clearcoatF0,
  28086. f90: clearcoatF90
  28087. } );
  28088. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28089. outgoingLight.assign( clearcoatLight );
  28090. }
  28091. if ( this.sheen === true ) {
  28092. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28093. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28094. outgoingLight.assign( sheenLight );
  28095. }
  28096. }
  28097. }
  28098. // These defines must match with PMREMGenerator
  28099. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28100. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28101. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28102. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28103. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28104. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28105. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28106. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28107. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28108. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28109. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28110. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28111. // These shader functions convert between the UV coordinates of a single face of
  28112. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28113. // sampling a textureCube (not generally normalized ).
  28114. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28115. const absDirection = vec3( abs( direction ) ).toVar();
  28116. const face = float( - 1.0 ).toVar();
  28117. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28118. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28119. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28120. } ).Else( () => {
  28121. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28122. } );
  28123. } ).Else( () => {
  28124. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28125. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28126. } ).Else( () => {
  28127. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28128. } );
  28129. } );
  28130. return face;
  28131. } ).setLayout( {
  28132. name: 'getFace',
  28133. type: 'float',
  28134. inputs: [
  28135. { name: 'direction', type: 'vec3' }
  28136. ]
  28137. } );
  28138. // RH coordinate system; PMREM face-indexing convention
  28139. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28140. const uv = vec2().toVar();
  28141. If( face.equal( 0.0 ), () => {
  28142. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28143. } ).ElseIf( face.equal( 1.0 ), () => {
  28144. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28145. } ).ElseIf( face.equal( 2.0 ), () => {
  28146. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28147. } ).ElseIf( face.equal( 3.0 ), () => {
  28148. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28149. } ).ElseIf( face.equal( 4.0 ), () => {
  28150. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28151. } ).Else( () => {
  28152. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28153. } );
  28154. return mul( 0.5, uv.add( 1.0 ) );
  28155. } ).setLayout( {
  28156. name: 'getUV',
  28157. type: 'vec2',
  28158. inputs: [
  28159. { name: 'direction', type: 'vec3' },
  28160. { name: 'face', type: 'float' }
  28161. ]
  28162. } );
  28163. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28164. const mip = float( 0.0 ).toVar();
  28165. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28166. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28167. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28168. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28169. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28170. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28171. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28172. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28173. } ).Else( () => {
  28174. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28175. } );
  28176. return mip;
  28177. } ).setLayout( {
  28178. name: 'roughnessToMip',
  28179. type: 'float',
  28180. inputs: [
  28181. { name: 'roughness', type: 'float' }
  28182. ]
  28183. } );
  28184. // RH coordinate system; PMREM face-indexing convention
  28185. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28186. const uv = uv_immutable.toVar();
  28187. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28188. const direction = vec3( uv, 1.0 ).toVar();
  28189. If( face.equal( 0.0 ), () => {
  28190. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28191. } ).ElseIf( face.equal( 1.0 ), () => {
  28192. direction.assign( direction.xzy );
  28193. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28194. } ).ElseIf( face.equal( 2.0 ), () => {
  28195. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28196. } ).ElseIf( face.equal( 3.0 ), () => {
  28197. direction.assign( direction.zyx );
  28198. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28199. } ).ElseIf( face.equal( 4.0 ), () => {
  28200. direction.assign( direction.xzy );
  28201. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28202. } ).ElseIf( face.equal( 5.0 ), () => {
  28203. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28204. } );
  28205. return direction;
  28206. } ).setLayout( {
  28207. name: 'getDirection',
  28208. type: 'vec3',
  28209. inputs: [
  28210. { name: 'uv', type: 'vec2' },
  28211. { name: 'face', type: 'float' }
  28212. ]
  28213. } );
  28214. //
  28215. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28216. const roughness = float( roughness_immutable );
  28217. const sampleDir = vec3( sampleDir_immutable );
  28218. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28219. const mipF = fract( mip );
  28220. const mipInt = floor( mip );
  28221. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28222. If( mipF.notEqual( 0.0 ), () => {
  28223. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28224. color0.assign( mix( color0, color1, mipF ) );
  28225. } );
  28226. return color0;
  28227. } );
  28228. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28229. const mipInt = float( mipInt_immutable ).toVar();
  28230. const direction = vec3( direction_immutable );
  28231. const face = float( getFace( direction ) ).toVar();
  28232. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28233. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28234. const faceSize = float( exp2( mipInt ) ).toVar();
  28235. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28236. If( face.greaterThan( 2.0 ), () => {
  28237. uv.y.addAssign( faceSize );
  28238. face.subAssign( 3.0 );
  28239. } );
  28240. uv.x.addAssign( face.mul( faceSize ) );
  28241. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28242. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28243. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28244. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28245. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28246. } );
  28247. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28248. const cosTheta = cos( theta );
  28249. // Rodrigues' axis-angle rotation
  28250. const sampleDirection = outputDirection.mul( cosTheta )
  28251. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28252. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28253. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28254. } );
  28255. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28256. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28257. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28258. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28259. } );
  28260. axis.assign( normalize( axis ) );
  28261. const gl_FragColor = vec3().toVar();
  28262. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28263. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28264. If( i.greaterThanEqual( samples ), () => {
  28265. Break();
  28266. } );
  28267. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28268. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28269. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28270. } );
  28271. return vec4( gl_FragColor, 1 );
  28272. } );
  28273. let _generator = null;
  28274. const _cache = new WeakMap();
  28275. function _generateCubeUVSize( imageHeight ) {
  28276. const maxMip = Math.log2( imageHeight ) - 2;
  28277. const texelHeight = 1.0 / imageHeight;
  28278. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28279. return { texelWidth, texelHeight, maxMip };
  28280. }
  28281. function _getPMREMFromTexture( texture ) {
  28282. let cacheTexture = _cache.get( texture );
  28283. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28284. if ( pmremVersion !== texture.pmremVersion ) {
  28285. const image = texture.image;
  28286. if ( texture.isCubeTexture ) {
  28287. if ( isCubeMapReady( image ) ) {
  28288. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28289. } else {
  28290. return null;
  28291. }
  28292. } else {
  28293. if ( isEquirectangularMapReady( image ) ) {
  28294. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28295. } else {
  28296. return null;
  28297. }
  28298. }
  28299. cacheTexture.pmremVersion = texture.pmremVersion;
  28300. _cache.set( texture, cacheTexture );
  28301. }
  28302. return cacheTexture.texture;
  28303. }
  28304. class PMREMNode extends TempNode {
  28305. static get type() {
  28306. return 'PMREMNode';
  28307. }
  28308. constructor( value, uvNode = null, levelNode = null ) {
  28309. super( 'vec3' );
  28310. this._value = value;
  28311. this._pmrem = null;
  28312. this.uvNode = uvNode;
  28313. this.levelNode = levelNode;
  28314. this._generator = null;
  28315. const defaultTexture = new Texture();
  28316. defaultTexture.isRenderTargetTexture = true;
  28317. this._texture = texture( defaultTexture );
  28318. this._width = uniform( 0 );
  28319. this._height = uniform( 0 );
  28320. this._maxMip = uniform( 0 );
  28321. this.updateBeforeType = NodeUpdateType.RENDER;
  28322. }
  28323. set value( value ) {
  28324. this._value = value;
  28325. this._pmrem = null;
  28326. }
  28327. get value() {
  28328. return this._value;
  28329. }
  28330. updateFromTexture( texture ) {
  28331. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28332. this._texture.value = texture;
  28333. this._width.value = cubeUVSize.texelWidth;
  28334. this._height.value = cubeUVSize.texelHeight;
  28335. this._maxMip.value = cubeUVSize.maxMip;
  28336. }
  28337. updateBefore() {
  28338. let pmrem = this._pmrem;
  28339. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28340. const texture = this._value;
  28341. if ( pmremVersion !== texture.pmremVersion ) {
  28342. if ( texture.isPMREMTexture === true ) {
  28343. pmrem = texture;
  28344. } else {
  28345. pmrem = _getPMREMFromTexture( texture );
  28346. }
  28347. if ( pmrem !== null ) {
  28348. this._pmrem = pmrem;
  28349. this.updateFromTexture( pmrem );
  28350. }
  28351. }
  28352. }
  28353. setup( builder ) {
  28354. if ( _generator === null ) {
  28355. _generator = builder.createPMREMGenerator();
  28356. }
  28357. //
  28358. this.updateBefore( builder );
  28359. //
  28360. let uvNode = this.uvNode;
  28361. if ( uvNode === null && builder.context.getUV ) {
  28362. uvNode = builder.context.getUV( this );
  28363. }
  28364. //
  28365. const texture = this.value;
  28366. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28367. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28368. }
  28369. //
  28370. let levelNode = this.levelNode;
  28371. if ( levelNode === null && builder.context.getTextureLevel ) {
  28372. levelNode = builder.context.getTextureLevel( this );
  28373. }
  28374. //
  28375. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28376. }
  28377. }
  28378. function isCubeMapReady( image ) {
  28379. if ( image === null || image === undefined ) return false;
  28380. let count = 0;
  28381. const length = 6;
  28382. for ( let i = 0; i < length; i ++ ) {
  28383. if ( image[ i ] !== undefined ) count ++;
  28384. }
  28385. return count === length;
  28386. }
  28387. function isEquirectangularMapReady( image ) {
  28388. if ( image === null || image === undefined ) return false;
  28389. return image.height > 0;
  28390. }
  28391. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28392. const _envNodeCache = new WeakMap();
  28393. class EnvironmentNode extends LightingNode {
  28394. static get type() {
  28395. return 'EnvironmentNode';
  28396. }
  28397. constructor( envNode = null ) {
  28398. super();
  28399. this.envNode = envNode;
  28400. }
  28401. setup( builder ) {
  28402. const { material } = builder;
  28403. let envNode = this.envNode;
  28404. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28405. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28406. let cacheEnvNode = _envNodeCache.get( value );
  28407. if ( cacheEnvNode === undefined ) {
  28408. cacheEnvNode = pmremTexture( value );
  28409. _envNodeCache.set( value, cacheEnvNode );
  28410. }
  28411. envNode = cacheEnvNode;
  28412. }
  28413. //
  28414. const envMap = material.envMap;
  28415. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28416. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28417. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28418. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28419. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28420. const isolateRadiance = cache( radiance );
  28421. const isolateIrradiance = cache( irradiance );
  28422. //
  28423. builder.context.radiance.addAssign( isolateRadiance );
  28424. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28425. //
  28426. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28427. if ( clearcoatRadiance ) {
  28428. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28429. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28430. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28431. }
  28432. }
  28433. }
  28434. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28435. let reflectVec = null;
  28436. return {
  28437. getUV: () => {
  28438. if ( reflectVec === null ) {
  28439. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28440. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28441. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28442. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28443. }
  28444. return reflectVec;
  28445. },
  28446. getTextureLevel: () => {
  28447. return roughnessNode;
  28448. }
  28449. };
  28450. };
  28451. const createIrradianceContext = ( normalWorldNode ) => {
  28452. return {
  28453. getUV: () => {
  28454. return normalWorldNode;
  28455. },
  28456. getTextureLevel: () => {
  28457. return float( 1.0 );
  28458. }
  28459. };
  28460. };
  28461. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28462. class MeshStandardNodeMaterial extends NodeMaterial {
  28463. static get type() {
  28464. return 'MeshStandardNodeMaterial';
  28465. }
  28466. constructor( parameters ) {
  28467. super();
  28468. this.isMeshStandardNodeMaterial = true;
  28469. this.lights = true;
  28470. this.emissiveNode = null;
  28471. this.metalnessNode = null;
  28472. this.roughnessNode = null;
  28473. this.setDefaultValues( _defaultValues$6 );
  28474. this.setValues( parameters );
  28475. }
  28476. setupEnvironment( builder ) {
  28477. let envNode = super.setupEnvironment( builder );
  28478. if ( envNode === null && builder.environmentNode ) {
  28479. envNode = builder.environmentNode;
  28480. }
  28481. return envNode ? new EnvironmentNode( envNode ) : null;
  28482. }
  28483. setupLightingModel( /*builder*/ ) {
  28484. return new PhysicalLightingModel();
  28485. }
  28486. setupSpecular() {
  28487. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28488. specularColor.assign( specularColorNode );
  28489. specularF90.assign( 1.0 );
  28490. }
  28491. setupVariants() {
  28492. // METALNESS
  28493. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28494. metalness.assign( metalnessNode );
  28495. // ROUGHNESS
  28496. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28497. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28498. roughness.assign( roughnessNode );
  28499. // SPECULAR COLOR
  28500. this.setupSpecular();
  28501. // DIFFUSE COLOR
  28502. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28503. }
  28504. copy( source ) {
  28505. this.emissiveNode = source.emissiveNode;
  28506. this.metalnessNode = source.metalnessNode;
  28507. this.roughnessNode = source.roughnessNode;
  28508. return super.copy( source );
  28509. }
  28510. }
  28511. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28512. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28513. static get type() {
  28514. return 'MeshPhysicalNodeMaterial';
  28515. }
  28516. constructor( parameters ) {
  28517. super();
  28518. this.isMeshPhysicalNodeMaterial = true;
  28519. this.clearcoatNode = null;
  28520. this.clearcoatRoughnessNode = null;
  28521. this.clearcoatNormalNode = null;
  28522. this.sheenNode = null;
  28523. this.sheenRoughnessNode = null;
  28524. this.iridescenceNode = null;
  28525. this.iridescenceIORNode = null;
  28526. this.iridescenceThicknessNode = null;
  28527. this.specularIntensityNode = null;
  28528. this.specularColorNode = null;
  28529. this.iorNode = null;
  28530. this.transmissionNode = null;
  28531. this.thicknessNode = null;
  28532. this.attenuationDistanceNode = null;
  28533. this.attenuationColorNode = null;
  28534. this.dispersionNode = null;
  28535. this.anisotropyNode = null;
  28536. this.setDefaultValues( _defaultValues$5 );
  28537. this.setValues( parameters );
  28538. }
  28539. get useClearcoat() {
  28540. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28541. }
  28542. get useIridescence() {
  28543. return this.iridescence > 0 || this.iridescenceNode !== null;
  28544. }
  28545. get useSheen() {
  28546. return this.sheen > 0 || this.sheenNode !== null;
  28547. }
  28548. get useAnisotropy() {
  28549. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28550. }
  28551. get useTransmission() {
  28552. return this.transmission > 0 || this.transmissionNode !== null;
  28553. }
  28554. get useDispersion() {
  28555. return this.dispersion > 0 || this.dispersionNode !== null;
  28556. }
  28557. setupSpecular() {
  28558. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28559. ior.assign( iorNode );
  28560. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  28561. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28562. }
  28563. setupLightingModel( /*builder*/ ) {
  28564. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28565. }
  28566. setupVariants( builder ) {
  28567. super.setupVariants( builder );
  28568. // CLEARCOAT
  28569. if ( this.useClearcoat ) {
  28570. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28571. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28572. clearcoat.assign( clearcoatNode );
  28573. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28574. }
  28575. // SHEEN
  28576. if ( this.useSheen ) {
  28577. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28578. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28579. sheen.assign( sheenNode );
  28580. sheenRoughness.assign( sheenRoughnessNode );
  28581. }
  28582. // IRIDESCENCE
  28583. if ( this.useIridescence ) {
  28584. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28585. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28586. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28587. iridescence.assign( iridescenceNode );
  28588. iridescenceIOR.assign( iridescenceIORNode );
  28589. iridescenceThickness.assign( iridescenceThicknessNode );
  28590. }
  28591. // ANISOTROPY
  28592. if ( this.useAnisotropy ) {
  28593. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28594. anisotropy.assign( anisotropyV.length() );
  28595. If( anisotropy.equal( 0.0 ), () => {
  28596. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28597. } ).Else( () => {
  28598. anisotropyV.divAssign( vec2( anisotropy ) );
  28599. anisotropy.assign( anisotropy.saturate() );
  28600. } );
  28601. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28602. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28603. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28604. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28605. }
  28606. // TRANSMISSION
  28607. if ( this.useTransmission ) {
  28608. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28609. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28610. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28611. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28612. transmission.assign( transmissionNode );
  28613. thickness.assign( thicknessNode );
  28614. attenuationDistance.assign( attenuationDistanceNode );
  28615. attenuationColor.assign( attenuationColorNode );
  28616. if ( this.useDispersion ) {
  28617. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28618. dispersion.assign( dispersionNode );
  28619. }
  28620. }
  28621. }
  28622. setupClearcoatNormal() {
  28623. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28624. }
  28625. setup( builder ) {
  28626. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28627. super.setup( builder );
  28628. }
  28629. copy( source ) {
  28630. this.clearcoatNode = source.clearcoatNode;
  28631. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28632. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28633. this.sheenNode = source.sheenNode;
  28634. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28635. this.iridescenceNode = source.iridescenceNode;
  28636. this.iridescenceIORNode = source.iridescenceIORNode;
  28637. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28638. this.specularIntensityNode = source.specularIntensityNode;
  28639. this.specularColorNode = source.specularColorNode;
  28640. this.transmissionNode = source.transmissionNode;
  28641. this.thicknessNode = source.thicknessNode;
  28642. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28643. this.attenuationColorNode = source.attenuationColorNode;
  28644. this.dispersionNode = source.dispersionNode;
  28645. this.anisotropyNode = source.anisotropyNode;
  28646. return super.copy( source );
  28647. }
  28648. }
  28649. class SSSLightingModel extends PhysicalLightingModel {
  28650. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28651. super( useClearcoat, useSheen, useIridescence );
  28652. this.useSSS = useSSS;
  28653. }
  28654. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28655. if ( this.useSSS === true ) {
  28656. const material = builder.material;
  28657. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28658. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28659. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28660. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28661. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28662. }
  28663. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28664. }
  28665. }
  28666. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28667. static get type() {
  28668. return 'MeshSSSNodeMaterial';
  28669. }
  28670. constructor( parameters ) {
  28671. super( parameters );
  28672. this.thicknessColorNode = null;
  28673. this.thicknessDistortionNode = float( 0.1 );
  28674. this.thicknessAmbientNode = float( 0.0 );
  28675. this.thicknessAttenuationNode = float( .1 );
  28676. this.thicknessPowerNode = float( 2.0 );
  28677. this.thicknessScaleNode = float( 10.0 );
  28678. }
  28679. get useSSS() {
  28680. return this.thicknessColorNode !== null;
  28681. }
  28682. setupLightingModel( /*builder*/ ) {
  28683. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28684. }
  28685. copy( source ) {
  28686. this.thicknessColorNode = source.thicknessColorNode;
  28687. this.thicknessDistortionNode = source.thicknessDistortionNode;
  28688. this.thicknessAmbientNode = source.thicknessAmbientNode;
  28689. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  28690. this.thicknessPowerNode = source.thicknessPowerNode;
  28691. this.thicknessScaleNode = source.thicknessScaleNode;
  28692. return super.copy( source );
  28693. }
  28694. }
  28695. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  28696. // dotNL will be from -1.0 to 1.0
  28697. const dotNL = normal.dot( lightDirection );
  28698. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  28699. if ( builder.material.gradientMap ) {
  28700. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  28701. return vec3( gradientMap.r );
  28702. } else {
  28703. const fw = coord.fwidth().mul( 0.5 );
  28704. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  28705. }
  28706. } );
  28707. class ToonLightingModel extends LightingModel {
  28708. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28709. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  28710. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28711. }
  28712. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  28713. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28714. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28715. }
  28716. }
  28717. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  28718. class MeshToonNodeMaterial extends NodeMaterial {
  28719. static get type() {
  28720. return 'MeshToonNodeMaterial';
  28721. }
  28722. constructor( parameters ) {
  28723. super();
  28724. this.isMeshToonNodeMaterial = true;
  28725. this.lights = true;
  28726. this.setDefaultValues( _defaultValues$4 );
  28727. this.setValues( parameters );
  28728. }
  28729. setupLightingModel( /*builder*/ ) {
  28730. return new ToonLightingModel();
  28731. }
  28732. }
  28733. class MatcapUVNode extends TempNode {
  28734. static get type() {
  28735. return 'MatcapUVNode';
  28736. }
  28737. constructor() {
  28738. super( 'vec2' );
  28739. }
  28740. setup() {
  28741. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28742. const y = positionViewDirection.cross( x );
  28743. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28744. }
  28745. }
  28746. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  28747. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  28748. class MeshMatcapNodeMaterial extends NodeMaterial {
  28749. static get type() {
  28750. return 'MeshMatcapNodeMaterial';
  28751. }
  28752. constructor( parameters ) {
  28753. super();
  28754. this.lights = false;
  28755. this.isMeshMatcapNodeMaterial = true;
  28756. this.setDefaultValues( _defaultValues$3 );
  28757. this.setValues( parameters );
  28758. }
  28759. setupVariants( builder ) {
  28760. const uv = matcapUV;
  28761. let matcapColor;
  28762. if ( builder.material.matcap ) {
  28763. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  28764. } else {
  28765. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  28766. }
  28767. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  28768. }
  28769. }
  28770. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  28771. class PointsNodeMaterial extends NodeMaterial {
  28772. static get type() {
  28773. return 'PointsNodeMaterial';
  28774. }
  28775. constructor( parameters ) {
  28776. super();
  28777. this.isPointsNodeMaterial = true;
  28778. this.lights = false;
  28779. this.transparent = true;
  28780. this.sizeNode = null;
  28781. this.setDefaultValues( _defaultValues$2 );
  28782. this.setValues( parameters );
  28783. }
  28784. copy( source ) {
  28785. this.sizeNode = source.sizeNode;
  28786. return super.copy( source );
  28787. }
  28788. }
  28789. class RotateNode extends TempNode {
  28790. static get type() {
  28791. return 'RotateNode';
  28792. }
  28793. constructor( positionNode, rotationNode ) {
  28794. super();
  28795. this.positionNode = positionNode;
  28796. this.rotationNode = rotationNode;
  28797. }
  28798. getNodeType( builder ) {
  28799. return this.positionNode.getNodeType( builder );
  28800. }
  28801. setup( builder ) {
  28802. const { rotationNode, positionNode } = this;
  28803. const nodeType = this.getNodeType( builder );
  28804. if ( nodeType === 'vec2' ) {
  28805. const cosAngle = rotationNode.cos();
  28806. const sinAngle = rotationNode.sin();
  28807. const rotationMatrix = mat2(
  28808. cosAngle, sinAngle,
  28809. sinAngle.negate(), cosAngle
  28810. );
  28811. return rotationMatrix.mul( positionNode );
  28812. } else {
  28813. const rotation = rotationNode;
  28814. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  28815. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  28816. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  28817. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  28818. }
  28819. }
  28820. }
  28821. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  28822. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  28823. class SpriteNodeMaterial extends NodeMaterial {
  28824. static get type() {
  28825. return 'SpriteNodeMaterial';
  28826. }
  28827. constructor( parameters ) {
  28828. super();
  28829. this.isSpriteNodeMaterial = true;
  28830. this.lights = false;
  28831. this._useSizeAttenuation = true;
  28832. this.positionNode = null;
  28833. this.rotationNode = null;
  28834. this.scaleNode = null;
  28835. this.setDefaultValues( _defaultValues$1 );
  28836. this.setValues( parameters );
  28837. }
  28838. setupPosition( { object, camera, context } ) {
  28839. const sizeAttenuation = this.sizeAttenuation;
  28840. // < VERTEX STAGE >
  28841. const { positionNode, rotationNode, scaleNode } = this;
  28842. const vertex = positionLocal;
  28843. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  28844. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  28845. if ( scaleNode !== null ) {
  28846. scale = scale.mul( scaleNode );
  28847. }
  28848. if ( ! sizeAttenuation && camera.isPerspectiveCamera ) {
  28849. scale = scale.mul( mvPosition.z.negate() );
  28850. }
  28851. let alignedPosition = vertex.xy;
  28852. if ( object.center && object.center.isVector2 === true ) {
  28853. const center = reference$1( 'center', 'vec2' );
  28854. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  28855. }
  28856. alignedPosition = alignedPosition.mul( scale );
  28857. const rotation = float( rotationNode || materialRotation );
  28858. const rotatedPosition = rotate( alignedPosition, rotation );
  28859. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  28860. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  28861. context.vertex = vertex;
  28862. return modelViewProjection;
  28863. }
  28864. copy( source ) {
  28865. this.positionNode = source.positionNode;
  28866. this.rotationNode = source.rotationNode;
  28867. this.scaleNode = source.scaleNode;
  28868. return super.copy( source );
  28869. }
  28870. get sizeAttenuation() {
  28871. return this._useSizeAttenuation;
  28872. }
  28873. set sizeAttenuation( value ) {
  28874. if ( this._useSizeAttenuation !== value ) {
  28875. this._useSizeAttenuation = value;
  28876. this.needsUpdate = true;
  28877. }
  28878. }
  28879. }
  28880. class ShadowMaskModel extends LightingModel {
  28881. constructor() {
  28882. super();
  28883. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  28884. }
  28885. direct( { shadowMask } ) {
  28886. this.shadowNode.mulAssign( shadowMask );
  28887. }
  28888. finish( context ) {
  28889. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  28890. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  28891. }
  28892. }
  28893. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  28894. class ShadowNodeMaterial extends NodeMaterial {
  28895. static get type() {
  28896. return 'ShadowNodeMaterial';
  28897. }
  28898. constructor( parameters ) {
  28899. super();
  28900. this.isShadowNodeMaterial = true;
  28901. this.lights = true;
  28902. this.setDefaultValues( _defaultValues );
  28903. this.setValues( parameters );
  28904. }
  28905. setupLightingModel( /*builder*/ ) {
  28906. return new ShadowMaskModel();
  28907. }
  28908. }
  28909. const normal = Fn( ( { texture, uv } ) => {
  28910. const epsilon = 0.0001;
  28911. const ret = vec3().toVar();
  28912. If( uv.x.lessThan( epsilon ), () => {
  28913. ret.assign( vec3( 1, 0, 0 ) );
  28914. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  28915. ret.assign( vec3( 0, 1, 0 ) );
  28916. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  28917. ret.assign( vec3( 0, 0, 1 ) );
  28918. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  28919. ret.assign( vec3( - 1, 0, 0 ) );
  28920. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  28921. ret.assign( vec3( 0, - 1, 0 ) );
  28922. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  28923. ret.assign( vec3( 0, 0, - 1 ) );
  28924. } ).Else( () => {
  28925. const step = 0.01;
  28926. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  28927. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  28928. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  28929. ret.assign( vec3( x, y, z ) );
  28930. } );
  28931. return ret.normalize();
  28932. } );
  28933. class Texture3DNode extends TextureNode {
  28934. static get type() {
  28935. return 'Texture3DNode';
  28936. }
  28937. constructor( value, uvNode = null, levelNode = null ) {
  28938. super( value, uvNode, levelNode );
  28939. this.isTexture3DNode = true;
  28940. }
  28941. getInputType( /*builder*/ ) {
  28942. return 'texture3D';
  28943. }
  28944. getDefaultUV() {
  28945. return vec3( 0.5, 0.5, 0.5 );
  28946. }
  28947. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  28948. setupUV( builder, uvNode ) {
  28949. return uvNode;
  28950. }
  28951. generateUV( builder, uvNode ) {
  28952. return uvNode.build( builder, 'vec3' );
  28953. }
  28954. normal( uvNode ) {
  28955. return normal( { texture: this, uv: uvNode } );
  28956. }
  28957. }
  28958. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  28959. class VolumeNodeMaterial extends NodeMaterial {
  28960. static get type() {
  28961. return 'VolumeNodeMaterial';
  28962. }
  28963. constructor( params = {} ) {
  28964. super();
  28965. this.lights = false;
  28966. this.isVolumeNodeMaterial = true;
  28967. this.testNode = null;
  28968. this.setValues( params );
  28969. }
  28970. setup( builder ) {
  28971. const map = texture3D( this.map, null, 0 );
  28972. const hitBox = Fn( ( { orig, dir } ) => {
  28973. const box_min = vec3( - 0.5 );
  28974. const box_max = vec3( 0.5 );
  28975. const inv_dir = dir.reciprocal();
  28976. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  28977. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  28978. const tmin = min$1( tmin_tmp, tmax_tmp );
  28979. const tmax = max$1( tmin_tmp, tmax_tmp );
  28980. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  28981. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  28982. return vec2( t0, t1 );
  28983. } );
  28984. this.fragmentNode = Fn( () => {
  28985. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  28986. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  28987. const rayDir = vDirection.normalize();
  28988. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  28989. bounds.x.greaterThan( bounds.y ).discard();
  28990. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  28991. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  28992. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  28993. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  28994. delta.divAssign( materialReference( 'steps', 'float' ) );
  28995. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  28996. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  28997. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  28998. if ( this.testNode !== null ) {
  28999. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  29000. } else {
  29001. // default to show surface of mesh
  29002. ac.a.assign( 1 );
  29003. Break();
  29004. }
  29005. p.addAssign( rayDir.mul( delta ) );
  29006. } );
  29007. ac.a.equal( 0 ).discard();
  29008. return vec4( ac );
  29009. } )();
  29010. super.setup( builder );
  29011. }
  29012. }
  29013. class Animation {
  29014. constructor( nodes, info ) {
  29015. this.nodes = nodes;
  29016. this.info = info;
  29017. this.animationLoop = null;
  29018. this.requestId = null;
  29019. this._init();
  29020. }
  29021. _init() {
  29022. const update = ( time, frame ) => {
  29023. this.requestId = self.requestAnimationFrame( update );
  29024. if ( this.info.autoReset === true ) this.info.reset();
  29025. this.nodes.nodeFrame.update();
  29026. this.info.frame = this.nodes.nodeFrame.frameId;
  29027. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  29028. };
  29029. update();
  29030. }
  29031. dispose() {
  29032. self.cancelAnimationFrame( this.requestId );
  29033. this.requestId = null;
  29034. }
  29035. setAnimationLoop( callback ) {
  29036. this.animationLoop = callback;
  29037. }
  29038. }
  29039. class ChainMap {
  29040. constructor() {
  29041. this.weakMap = new WeakMap();
  29042. }
  29043. get( keys ) {
  29044. let map = this.weakMap;
  29045. for ( let i = 0; i < keys.length; i ++ ) {
  29046. map = map.get( keys[ i ] );
  29047. if ( map === undefined ) return undefined;
  29048. }
  29049. return map.get( keys[ keys.length - 1 ] );
  29050. }
  29051. set( keys, value ) {
  29052. let map = this.weakMap;
  29053. for ( let i = 0; i < keys.length; i ++ ) {
  29054. const key = keys[ i ];
  29055. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  29056. map = map.get( key );
  29057. }
  29058. return map.set( keys[ keys.length - 1 ], value );
  29059. }
  29060. delete( keys ) {
  29061. let map = this.weakMap;
  29062. for ( let i = 0; i < keys.length; i ++ ) {
  29063. map = map.get( keys[ i ] );
  29064. if ( map === undefined ) return false;
  29065. }
  29066. return map.delete( keys[ keys.length - 1 ] );
  29067. }
  29068. }
  29069. const _plane = /*@__PURE__*/ new Plane();
  29070. class ClippingContext {
  29071. constructor() {
  29072. this.version = 0;
  29073. this.globalClippingCount = 0;
  29074. this.localClippingCount = 0;
  29075. this.localClippingEnabled = false;
  29076. this.localClipIntersection = false;
  29077. this.planes = [];
  29078. this.parentVersion = 0;
  29079. this.viewNormalMatrix = new Matrix3();
  29080. this.cacheKey = 0;
  29081. }
  29082. projectPlanes( source, offset ) {
  29083. const l = source.length;
  29084. const planes = this.planes;
  29085. for ( let i = 0; i < l; i ++ ) {
  29086. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  29087. const v = planes[ offset + i ];
  29088. const normal = _plane.normal;
  29089. v.x = - normal.x;
  29090. v.y = - normal.y;
  29091. v.z = - normal.z;
  29092. v.w = _plane.constant;
  29093. }
  29094. }
  29095. updateGlobal( renderer, camera ) {
  29096. const rendererClippingPlanes = renderer.clippingPlanes;
  29097. this.viewMatrix = camera.matrixWorldInverse;
  29098. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29099. let update = false;
  29100. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  29101. const l = rendererClippingPlanes.length;
  29102. if ( l !== this.globalClippingCount ) {
  29103. const planes = [];
  29104. for ( let i = 0; i < l; i ++ ) {
  29105. planes.push( new Vector4() );
  29106. }
  29107. this.globalClippingCount = l;
  29108. this.planes = planes;
  29109. update = true;
  29110. }
  29111. this.projectPlanes( rendererClippingPlanes, 0 );
  29112. } else if ( this.globalClippingCount !== 0 ) {
  29113. this.globalClippingCount = 0;
  29114. this.planes = [];
  29115. update = true;
  29116. }
  29117. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  29118. this.localClippingEnabled = renderer.localClippingEnabled;
  29119. update = true;
  29120. }
  29121. if ( update ) {
  29122. this.version ++;
  29123. this.cacheKey = hash$1( this.globalClippingCount, this.localClippingEnabled === true ? 1 : 0 );
  29124. }
  29125. }
  29126. update( parent, material ) {
  29127. let update = false;
  29128. if ( this !== parent && parent.version !== this.parentVersion ) {
  29129. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  29130. this.localClippingEnabled = parent.localClippingEnabled;
  29131. this.planes = Array.from( parent.planes );
  29132. this.parentVersion = parent.version;
  29133. this.viewMatrix = parent.viewMatrix;
  29134. this.viewNormalMatrix = parent.viewNormalMatrix;
  29135. update = true;
  29136. }
  29137. if ( this.localClippingEnabled ) {
  29138. const localClippingPlanes = material.clippingPlanes;
  29139. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  29140. const l = localClippingPlanes.length;
  29141. const planes = this.planes;
  29142. const offset = this.globalClippingCount;
  29143. if ( update || l !== this.localClippingCount ) {
  29144. planes.length = offset + l;
  29145. for ( let i = 0; i < l; i ++ ) {
  29146. planes[ offset + i ] = new Vector4();
  29147. }
  29148. this.localClippingCount = l;
  29149. update = true;
  29150. }
  29151. this.projectPlanes( localClippingPlanes, offset );
  29152. } else if ( this.localClippingCount !== 0 ) {
  29153. this.localClippingCount = 0;
  29154. update = true;
  29155. }
  29156. if ( this.localClipIntersection !== material.clipIntersection ) {
  29157. this.localClipIntersection = material.clipIntersection;
  29158. update = true;
  29159. }
  29160. }
  29161. if ( update ) {
  29162. this.version += parent.version;
  29163. this.cacheKey = hash$1( parent.cacheKey, this.localClippingCount, this.localClipIntersection === true ? 1 : 0 );
  29164. }
  29165. }
  29166. }
  29167. let _id$7 = 0;
  29168. function getKeys( obj ) {
  29169. const keys = Object.keys( obj );
  29170. let proto = Object.getPrototypeOf( obj );
  29171. while ( proto ) {
  29172. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29173. for ( const key in descriptors ) {
  29174. if ( descriptors[ key ] !== undefined ) {
  29175. const descriptor = descriptors[ key ];
  29176. if ( descriptor && typeof descriptor.get === 'function' ) {
  29177. keys.push( key );
  29178. }
  29179. }
  29180. }
  29181. proto = Object.getPrototypeOf( proto );
  29182. }
  29183. return keys;
  29184. }
  29185. class RenderObject {
  29186. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  29187. this._nodes = nodes;
  29188. this._geometries = geometries;
  29189. this.id = _id$7 ++;
  29190. this.renderer = renderer;
  29191. this.object = object;
  29192. this.material = material;
  29193. this.scene = scene;
  29194. this.camera = camera;
  29195. this.lightsNode = lightsNode;
  29196. this.context = renderContext;
  29197. this.geometry = object.geometry;
  29198. this.version = material.version;
  29199. this.drawRange = null;
  29200. this.attributes = null;
  29201. this.pipeline = null;
  29202. this.vertexBuffers = null;
  29203. this.drawParams = null;
  29204. this.bundle = null;
  29205. this.updateClipping( renderContext.clippingContext );
  29206. this.clippingContextVersion = this.clippingContext.version;
  29207. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29208. this.initialCacheKey = this.getCacheKey();
  29209. this._nodeBuilderState = null;
  29210. this._bindings = null;
  29211. this._monitor = null;
  29212. this.onDispose = null;
  29213. this.isRenderObject = true;
  29214. this.onMaterialDispose = () => {
  29215. this.dispose();
  29216. };
  29217. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29218. }
  29219. updateClipping( parent ) {
  29220. const material = this.material;
  29221. let clippingContext = this.clippingContext;
  29222. if ( Array.isArray( material.clippingPlanes ) ) {
  29223. if ( clippingContext === parent || ! clippingContext ) {
  29224. clippingContext = new ClippingContext();
  29225. this.clippingContext = clippingContext;
  29226. }
  29227. clippingContext.update( parent, material );
  29228. } else if ( this.clippingContext !== parent ) {
  29229. this.clippingContext = parent;
  29230. }
  29231. }
  29232. get clippingNeedsUpdate() {
  29233. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  29234. this.clippingContextVersion = this.clippingContext.version;
  29235. return true;
  29236. }
  29237. getNodeBuilderState() {
  29238. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29239. }
  29240. getMonitor() {
  29241. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29242. }
  29243. getBindings() {
  29244. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29245. }
  29246. getIndex() {
  29247. return this._geometries.getIndex( this );
  29248. }
  29249. getChainArray() {
  29250. return [ this.object, this.material, this.context, this.lightsNode ];
  29251. }
  29252. getAttributes() {
  29253. if ( this.attributes !== null ) return this.attributes;
  29254. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29255. const geometry = this.geometry;
  29256. const attributes = [];
  29257. const vertexBuffers = new Set();
  29258. for ( const nodeAttribute of nodeAttributes ) {
  29259. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29260. if ( attribute === undefined ) continue;
  29261. attributes.push( attribute );
  29262. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29263. vertexBuffers.add( bufferAttribute );
  29264. }
  29265. this.attributes = attributes;
  29266. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29267. return attributes;
  29268. }
  29269. getVertexBuffers() {
  29270. if ( this.vertexBuffers === null ) this.getAttributes();
  29271. return this.vertexBuffers;
  29272. }
  29273. getDrawParameters() {
  29274. const { object, material, geometry, group, drawRange } = this;
  29275. const drawParams = this.drawParams || ( this.drawParams = {
  29276. vertexCount: 0,
  29277. firstVertex: 0,
  29278. instanceCount: 0,
  29279. firstInstance: 0
  29280. } );
  29281. const index = this.getIndex();
  29282. const hasIndex = ( index !== null );
  29283. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29284. if ( instanceCount === 0 ) return null;
  29285. drawParams.instanceCount = instanceCount;
  29286. if ( object.isBatchedMesh === true ) return drawParams;
  29287. let rangeFactor = 1;
  29288. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29289. rangeFactor = 2;
  29290. }
  29291. let firstVertex = drawRange.start * rangeFactor;
  29292. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29293. if ( group !== null ) {
  29294. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29295. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29296. }
  29297. const itemCount = hasIndex === true ? index.count : geometry.attributes.position.count;
  29298. firstVertex = Math.max( firstVertex, 0 );
  29299. lastVertex = Math.min( lastVertex, itemCount );
  29300. const count = lastVertex - firstVertex;
  29301. if ( count < 0 || count === Infinity ) return null;
  29302. drawParams.vertexCount = count;
  29303. drawParams.firstVertex = firstVertex;
  29304. return drawParams;
  29305. }
  29306. getGeometryCacheKey() {
  29307. const { geometry } = this;
  29308. let cacheKey = '';
  29309. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29310. const attribute = geometry.attributes[ name ];
  29311. cacheKey += name + ',';
  29312. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29313. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29314. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29315. if ( attribute.normalized ) cacheKey += 'n,';
  29316. }
  29317. if ( geometry.index ) {
  29318. cacheKey += 'index,';
  29319. }
  29320. return cacheKey;
  29321. }
  29322. getMaterialCacheKey() {
  29323. const { object, material } = this;
  29324. let cacheKey = material.customProgramCacheKey();
  29325. for ( const property of getKeys( material ) ) {
  29326. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29327. const value = material[ property ];
  29328. let valueKey;
  29329. if ( value !== null ) {
  29330. // some material values require a formatting
  29331. const type = typeof value;
  29332. if ( type === 'number' ) {
  29333. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29334. } else if ( type === 'object' ) {
  29335. valueKey = '{';
  29336. if ( value.isTexture ) {
  29337. valueKey += value.mapping;
  29338. }
  29339. valueKey += '}';
  29340. } else {
  29341. valueKey = String( value );
  29342. }
  29343. } else {
  29344. valueKey = String( value );
  29345. }
  29346. cacheKey += /*property + ':' +*/ valueKey + ',';
  29347. }
  29348. cacheKey += this.clippingContext.cacheKey + ',';
  29349. if ( object.geometry ) {
  29350. cacheKey += this.getGeometryCacheKey();
  29351. }
  29352. if ( object.skeleton ) {
  29353. cacheKey += object.skeleton.bones.length + ',';
  29354. }
  29355. if ( object.morphTargetInfluences ) {
  29356. cacheKey += object.morphTargetInfluences.length + ',';
  29357. }
  29358. if ( object.isBatchedMesh ) {
  29359. cacheKey += object._matricesTexture.uuid + ',';
  29360. if ( object._colorsTexture !== null ) {
  29361. cacheKey += object._colorsTexture.uuid + ',';
  29362. }
  29363. }
  29364. if ( object.count > 1 ) {
  29365. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29366. cacheKey += object.uuid + ',';
  29367. }
  29368. return hashString( cacheKey );
  29369. }
  29370. get needsUpdate() {
  29371. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29372. }
  29373. getDynamicCacheKey() {
  29374. // Environment Nodes Cache Key
  29375. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  29376. if ( this.object.receiveShadow ) {
  29377. cacheKey += 1;
  29378. }
  29379. return cacheKey;
  29380. }
  29381. getCacheKey() {
  29382. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  29383. }
  29384. dispose() {
  29385. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29386. this.onDispose();
  29387. }
  29388. }
  29389. const chainArray = [];
  29390. class RenderObjects {
  29391. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29392. this.renderer = renderer;
  29393. this.nodes = nodes;
  29394. this.geometries = geometries;
  29395. this.pipelines = pipelines;
  29396. this.bindings = bindings;
  29397. this.info = info;
  29398. this.chainMaps = {};
  29399. }
  29400. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  29401. const chainMap = this.getChainMap( passId );
  29402. // reuse chainArray
  29403. chainArray[ 0 ] = object;
  29404. chainArray[ 1 ] = material;
  29405. chainArray[ 2 ] = renderContext;
  29406. chainArray[ 3 ] = lightsNode;
  29407. let renderObject = chainMap.get( chainArray );
  29408. if ( renderObject === undefined ) {
  29409. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  29410. chainMap.set( chainArray, renderObject );
  29411. } else {
  29412. renderObject.updateClipping( renderContext.clippingContext );
  29413. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  29414. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29415. renderObject.dispose();
  29416. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  29417. } else {
  29418. renderObject.version = material.version;
  29419. }
  29420. }
  29421. }
  29422. return renderObject;
  29423. }
  29424. getChainMap( passId = 'default' ) {
  29425. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29426. }
  29427. dispose() {
  29428. this.chainMaps = {};
  29429. }
  29430. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  29431. const chainMap = this.getChainMap( passId );
  29432. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  29433. renderObject.onDispose = () => {
  29434. this.pipelines.delete( renderObject );
  29435. this.bindings.delete( renderObject );
  29436. this.nodes.delete( renderObject );
  29437. chainMap.delete( renderObject.getChainArray() );
  29438. };
  29439. return renderObject;
  29440. }
  29441. }
  29442. class DataMap {
  29443. constructor() {
  29444. this.data = new WeakMap();
  29445. }
  29446. get( object ) {
  29447. let map = this.data.get( object );
  29448. if ( map === undefined ) {
  29449. map = {};
  29450. this.data.set( object, map );
  29451. }
  29452. return map;
  29453. }
  29454. delete( object ) {
  29455. let map;
  29456. if ( this.data.has( object ) ) {
  29457. map = this.data.get( object );
  29458. this.data.delete( object );
  29459. }
  29460. return map;
  29461. }
  29462. has( object ) {
  29463. return this.data.has( object );
  29464. }
  29465. dispose() {
  29466. this.data = new WeakMap();
  29467. }
  29468. }
  29469. const AttributeType = {
  29470. VERTEX: 1,
  29471. INDEX: 2,
  29472. STORAGE: 4
  29473. };
  29474. // size of a chunk in bytes (STD140 layout)
  29475. const GPU_CHUNK_BYTES = 16;
  29476. // @TODO: Move to src/constants.js
  29477. const BlendColorFactor = 211;
  29478. const OneMinusBlendColorFactor = 212;
  29479. class Attributes extends DataMap {
  29480. constructor( backend ) {
  29481. super();
  29482. this.backend = backend;
  29483. }
  29484. delete( attribute ) {
  29485. const attributeData = super.delete( attribute );
  29486. if ( attributeData !== undefined ) {
  29487. this.backend.destroyAttribute( attribute );
  29488. }
  29489. return attributeData;
  29490. }
  29491. update( attribute, type ) {
  29492. const data = this.get( attribute );
  29493. if ( data.version === undefined ) {
  29494. if ( type === AttributeType.VERTEX ) {
  29495. this.backend.createAttribute( attribute );
  29496. } else if ( type === AttributeType.INDEX ) {
  29497. this.backend.createIndexAttribute( attribute );
  29498. } else if ( type === AttributeType.STORAGE ) {
  29499. this.backend.createStorageAttribute( attribute );
  29500. }
  29501. data.version = this._getBufferAttribute( attribute ).version;
  29502. } else {
  29503. const bufferAttribute = this._getBufferAttribute( attribute );
  29504. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29505. this.backend.updateAttribute( attribute );
  29506. data.version = bufferAttribute.version;
  29507. }
  29508. }
  29509. }
  29510. _getBufferAttribute( attribute ) {
  29511. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29512. return attribute;
  29513. }
  29514. }
  29515. function arrayNeedsUint32( array ) {
  29516. // assumes larger values usually on last
  29517. for ( let i = array.length - 1; i >= 0; -- i ) {
  29518. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29519. }
  29520. return false;
  29521. }
  29522. function getWireframeVersion( geometry ) {
  29523. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29524. }
  29525. function getWireframeIndex( geometry ) {
  29526. const indices = [];
  29527. const geometryIndex = geometry.index;
  29528. const geometryPosition = geometry.attributes.position;
  29529. if ( geometryIndex !== null ) {
  29530. const array = geometryIndex.array;
  29531. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29532. const a = array[ i + 0 ];
  29533. const b = array[ i + 1 ];
  29534. const c = array[ i + 2 ];
  29535. indices.push( a, b, b, c, c, a );
  29536. }
  29537. } else {
  29538. const array = geometryPosition.array;
  29539. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29540. const a = i + 0;
  29541. const b = i + 1;
  29542. const c = i + 2;
  29543. indices.push( a, b, b, c, c, a );
  29544. }
  29545. }
  29546. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29547. attribute.version = getWireframeVersion( geometry );
  29548. return attribute;
  29549. }
  29550. class Geometries extends DataMap {
  29551. constructor( attributes, info ) {
  29552. super();
  29553. this.attributes = attributes;
  29554. this.info = info;
  29555. this.wireframes = new WeakMap();
  29556. this.attributeCall = new WeakMap();
  29557. }
  29558. has( renderObject ) {
  29559. const geometry = renderObject.geometry;
  29560. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29561. }
  29562. updateForRender( renderObject ) {
  29563. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29564. this.updateAttributes( renderObject );
  29565. }
  29566. initGeometry( renderObject ) {
  29567. const geometry = renderObject.geometry;
  29568. const geometryData = this.get( geometry );
  29569. geometryData.initialized = true;
  29570. this.info.memory.geometries ++;
  29571. const onDispose = () => {
  29572. this.info.memory.geometries --;
  29573. const index = geometry.index;
  29574. const geometryAttributes = renderObject.getAttributes();
  29575. if ( index !== null ) {
  29576. this.attributes.delete( index );
  29577. }
  29578. for ( const geometryAttribute of geometryAttributes ) {
  29579. this.attributes.delete( geometryAttribute );
  29580. }
  29581. const wireframeAttribute = this.wireframes.get( geometry );
  29582. if ( wireframeAttribute !== undefined ) {
  29583. this.attributes.delete( wireframeAttribute );
  29584. }
  29585. geometry.removeEventListener( 'dispose', onDispose );
  29586. };
  29587. geometry.addEventListener( 'dispose', onDispose );
  29588. }
  29589. updateAttributes( renderObject ) {
  29590. const attributes = renderObject.getAttributes();
  29591. for ( const attribute of attributes ) {
  29592. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29593. this.updateAttribute( attribute, AttributeType.STORAGE );
  29594. } else {
  29595. this.updateAttribute( attribute, AttributeType.VERTEX );
  29596. }
  29597. }
  29598. const index = this.getIndex( renderObject );
  29599. if ( index !== null ) {
  29600. this.updateAttribute( index, AttributeType.INDEX );
  29601. }
  29602. }
  29603. updateAttribute( attribute, type ) {
  29604. const callId = this.info.render.calls;
  29605. if ( ! attribute.isInterleavedBufferAttribute ) {
  29606. if ( this.attributeCall.get( attribute ) !== callId ) {
  29607. this.attributes.update( attribute, type );
  29608. this.attributeCall.set( attribute, callId );
  29609. }
  29610. } else {
  29611. if ( this.attributeCall.get( attribute ) === undefined ) {
  29612. this.attributes.update( attribute, type );
  29613. this.attributeCall.set( attribute, callId );
  29614. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29615. this.attributes.update( attribute, type );
  29616. this.attributeCall.set( attribute.data, callId );
  29617. this.attributeCall.set( attribute, callId );
  29618. }
  29619. }
  29620. }
  29621. getIndex( renderObject ) {
  29622. const { geometry, material } = renderObject;
  29623. let index = geometry.index;
  29624. if ( material.wireframe === true ) {
  29625. const wireframes = this.wireframes;
  29626. let wireframeAttribute = wireframes.get( geometry );
  29627. if ( wireframeAttribute === undefined ) {
  29628. wireframeAttribute = getWireframeIndex( geometry );
  29629. wireframes.set( geometry, wireframeAttribute );
  29630. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29631. this.attributes.delete( wireframeAttribute );
  29632. wireframeAttribute = getWireframeIndex( geometry );
  29633. wireframes.set( geometry, wireframeAttribute );
  29634. }
  29635. index = wireframeAttribute;
  29636. }
  29637. return index;
  29638. }
  29639. }
  29640. class Info {
  29641. constructor() {
  29642. this.autoReset = true;
  29643. this.frame = 0;
  29644. this.calls = 0;
  29645. this.render = {
  29646. calls: 0,
  29647. frameCalls: 0,
  29648. drawCalls: 0,
  29649. triangles: 0,
  29650. points: 0,
  29651. lines: 0,
  29652. timestamp: 0,
  29653. previousFrameCalls: 0,
  29654. timestampCalls: 0
  29655. };
  29656. this.compute = {
  29657. calls: 0,
  29658. frameCalls: 0,
  29659. timestamp: 0,
  29660. previousFrameCalls: 0,
  29661. timestampCalls: 0
  29662. };
  29663. this.memory = {
  29664. geometries: 0,
  29665. textures: 0
  29666. };
  29667. }
  29668. update( object, count, instanceCount ) {
  29669. this.render.drawCalls ++;
  29670. if ( object.isMesh || object.isSprite ) {
  29671. this.render.triangles += instanceCount * ( count / 3 );
  29672. } else if ( object.isPoints ) {
  29673. this.render.points += instanceCount * count;
  29674. } else if ( object.isLineSegments ) {
  29675. this.render.lines += instanceCount * ( count / 2 );
  29676. } else if ( object.isLine ) {
  29677. this.render.lines += instanceCount * ( count - 1 );
  29678. } else {
  29679. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  29680. }
  29681. }
  29682. updateTimestamp( type, time ) {
  29683. if ( this[ type ].timestampCalls === 0 ) {
  29684. this[ type ].timestamp = 0;
  29685. }
  29686. this[ type ].timestamp += time;
  29687. this[ type ].timestampCalls ++;
  29688. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  29689. this[ type ].timestampCalls = 0;
  29690. }
  29691. }
  29692. reset() {
  29693. const previousRenderFrameCalls = this.render.frameCalls;
  29694. this.render.previousFrameCalls = previousRenderFrameCalls;
  29695. const previousComputeFrameCalls = this.compute.frameCalls;
  29696. this.compute.previousFrameCalls = previousComputeFrameCalls;
  29697. this.render.drawCalls = 0;
  29698. this.render.frameCalls = 0;
  29699. this.compute.frameCalls = 0;
  29700. this.render.triangles = 0;
  29701. this.render.points = 0;
  29702. this.render.lines = 0;
  29703. }
  29704. dispose() {
  29705. this.reset();
  29706. this.calls = 0;
  29707. this.render.calls = 0;
  29708. this.compute.calls = 0;
  29709. this.render.timestamp = 0;
  29710. this.compute.timestamp = 0;
  29711. this.memory.geometries = 0;
  29712. this.memory.textures = 0;
  29713. }
  29714. }
  29715. class Pipeline {
  29716. constructor( cacheKey ) {
  29717. this.cacheKey = cacheKey;
  29718. this.usedTimes = 0;
  29719. }
  29720. }
  29721. class RenderPipeline extends Pipeline {
  29722. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  29723. super( cacheKey );
  29724. this.vertexProgram = vertexProgram;
  29725. this.fragmentProgram = fragmentProgram;
  29726. }
  29727. }
  29728. class ComputePipeline extends Pipeline {
  29729. constructor( cacheKey, computeProgram ) {
  29730. super( cacheKey );
  29731. this.computeProgram = computeProgram;
  29732. this.isComputePipeline = true;
  29733. }
  29734. }
  29735. let _id$6 = 0;
  29736. class ProgrammableStage {
  29737. constructor( code, type, transforms = null, attributes = null ) {
  29738. this.id = _id$6 ++;
  29739. this.code = code;
  29740. this.stage = type;
  29741. this.transforms = transforms;
  29742. this.attributes = attributes;
  29743. this.usedTimes = 0;
  29744. }
  29745. }
  29746. class Pipelines extends DataMap {
  29747. constructor( backend, nodes ) {
  29748. super();
  29749. this.backend = backend;
  29750. this.nodes = nodes;
  29751. this.bindings = null; // set by the bindings
  29752. this.caches = new Map();
  29753. this.programs = {
  29754. vertex: new Map(),
  29755. fragment: new Map(),
  29756. compute: new Map()
  29757. };
  29758. }
  29759. getForCompute( computeNode, bindings ) {
  29760. const { backend } = this;
  29761. const data = this.get( computeNode );
  29762. if ( this._needsComputeUpdate( computeNode ) ) {
  29763. const previousPipeline = data.pipeline;
  29764. if ( previousPipeline ) {
  29765. previousPipeline.usedTimes --;
  29766. previousPipeline.computeProgram.usedTimes --;
  29767. }
  29768. // get shader
  29769. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  29770. // programmable stage
  29771. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  29772. if ( stageCompute === undefined ) {
  29773. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  29774. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  29775. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  29776. backend.createProgram( stageCompute );
  29777. }
  29778. // determine compute pipeline
  29779. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  29780. let pipeline = this.caches.get( cacheKey );
  29781. if ( pipeline === undefined ) {
  29782. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29783. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  29784. }
  29785. // keep track of all used times
  29786. pipeline.usedTimes ++;
  29787. stageCompute.usedTimes ++;
  29788. //
  29789. data.version = computeNode.version;
  29790. data.pipeline = pipeline;
  29791. }
  29792. return data.pipeline;
  29793. }
  29794. getForRender( renderObject, promises = null ) {
  29795. const { backend } = this;
  29796. const data = this.get( renderObject );
  29797. if ( this._needsRenderUpdate( renderObject ) ) {
  29798. const previousPipeline = data.pipeline;
  29799. if ( previousPipeline ) {
  29800. previousPipeline.usedTimes --;
  29801. previousPipeline.vertexProgram.usedTimes --;
  29802. previousPipeline.fragmentProgram.usedTimes --;
  29803. }
  29804. // get shader
  29805. const nodeBuilderState = renderObject.getNodeBuilderState();
  29806. // programmable stages
  29807. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  29808. if ( stageVertex === undefined ) {
  29809. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  29810. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  29811. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  29812. backend.createProgram( stageVertex );
  29813. }
  29814. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  29815. if ( stageFragment === undefined ) {
  29816. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  29817. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  29818. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  29819. backend.createProgram( stageFragment );
  29820. }
  29821. // determine render pipeline
  29822. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  29823. let pipeline = this.caches.get( cacheKey );
  29824. if ( pipeline === undefined ) {
  29825. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29826. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  29827. } else {
  29828. renderObject.pipeline = pipeline;
  29829. }
  29830. // keep track of all used times
  29831. pipeline.usedTimes ++;
  29832. stageVertex.usedTimes ++;
  29833. stageFragment.usedTimes ++;
  29834. //
  29835. data.pipeline = pipeline;
  29836. }
  29837. return data.pipeline;
  29838. }
  29839. delete( object ) {
  29840. const pipeline = this.get( object ).pipeline;
  29841. if ( pipeline ) {
  29842. // pipeline
  29843. pipeline.usedTimes --;
  29844. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  29845. // programs
  29846. if ( pipeline.isComputePipeline ) {
  29847. pipeline.computeProgram.usedTimes --;
  29848. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  29849. } else {
  29850. pipeline.fragmentProgram.usedTimes --;
  29851. pipeline.vertexProgram.usedTimes --;
  29852. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  29853. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  29854. }
  29855. }
  29856. return super.delete( object );
  29857. }
  29858. dispose() {
  29859. super.dispose();
  29860. this.caches = new Map();
  29861. this.programs = {
  29862. vertex: new Map(),
  29863. fragment: new Map(),
  29864. compute: new Map()
  29865. };
  29866. }
  29867. updateForRender( renderObject ) {
  29868. this.getForRender( renderObject );
  29869. }
  29870. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  29871. // check for existing pipeline
  29872. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  29873. let pipeline = this.caches.get( cacheKey );
  29874. if ( pipeline === undefined ) {
  29875. pipeline = new ComputePipeline( cacheKey, stageCompute );
  29876. this.caches.set( cacheKey, pipeline );
  29877. this.backend.createComputePipeline( pipeline, bindings );
  29878. }
  29879. return pipeline;
  29880. }
  29881. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  29882. // check for existing pipeline
  29883. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  29884. let pipeline = this.caches.get( cacheKey );
  29885. if ( pipeline === undefined ) {
  29886. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  29887. this.caches.set( cacheKey, pipeline );
  29888. renderObject.pipeline = pipeline;
  29889. this.backend.createRenderPipeline( renderObject, promises );
  29890. }
  29891. return pipeline;
  29892. }
  29893. _getComputeCacheKey( computeNode, stageCompute ) {
  29894. return computeNode.id + ',' + stageCompute.id;
  29895. }
  29896. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  29897. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  29898. }
  29899. _releasePipeline( pipeline ) {
  29900. this.caches.delete( pipeline.cacheKey );
  29901. }
  29902. _releaseProgram( program ) {
  29903. const code = program.code;
  29904. const stage = program.stage;
  29905. this.programs[ stage ].delete( code );
  29906. }
  29907. _needsComputeUpdate( computeNode ) {
  29908. const data = this.get( computeNode );
  29909. return data.pipeline === undefined || data.version !== computeNode.version;
  29910. }
  29911. _needsRenderUpdate( renderObject ) {
  29912. const data = this.get( renderObject );
  29913. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  29914. }
  29915. }
  29916. class Bindings extends DataMap {
  29917. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  29918. super();
  29919. this.backend = backend;
  29920. this.textures = textures;
  29921. this.pipelines = pipelines;
  29922. this.attributes = attributes;
  29923. this.nodes = nodes;
  29924. this.info = info;
  29925. this.pipelines.bindings = this; // assign bindings to pipelines
  29926. }
  29927. getForRender( renderObject ) {
  29928. const bindings = renderObject.getBindings();
  29929. for ( const bindGroup of bindings ) {
  29930. const groupData = this.get( bindGroup );
  29931. if ( groupData.bindGroup === undefined ) {
  29932. // each object defines an array of bindings (ubos, textures, samplers etc.)
  29933. this._init( bindGroup );
  29934. this.backend.createBindings( bindGroup, bindings );
  29935. groupData.bindGroup = bindGroup;
  29936. }
  29937. }
  29938. return bindings;
  29939. }
  29940. getForCompute( computeNode ) {
  29941. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  29942. for ( const bindGroup of bindings ) {
  29943. const groupData = this.get( bindGroup );
  29944. if ( groupData.bindGroup === undefined ) {
  29945. this._init( bindGroup );
  29946. this.backend.createBindings( bindGroup, bindings );
  29947. groupData.bindGroup = bindGroup;
  29948. }
  29949. }
  29950. return bindings;
  29951. }
  29952. updateForCompute( computeNode ) {
  29953. this._updateBindings( this.getForCompute( computeNode ) );
  29954. }
  29955. updateForRender( renderObject ) {
  29956. this._updateBindings( this.getForRender( renderObject ) );
  29957. }
  29958. _updateBindings( bindings ) {
  29959. for ( const bindGroup of bindings ) {
  29960. this._update( bindGroup, bindings );
  29961. }
  29962. }
  29963. _init( bindGroup ) {
  29964. for ( const binding of bindGroup.bindings ) {
  29965. if ( binding.isSampledTexture ) {
  29966. this.textures.updateTexture( binding.texture );
  29967. } else if ( binding.isStorageBuffer ) {
  29968. const attribute = binding.attribute;
  29969. this.attributes.update( attribute, AttributeType.STORAGE );
  29970. }
  29971. }
  29972. }
  29973. _update( bindGroup, bindings ) {
  29974. const { backend } = this;
  29975. let needsBindingsUpdate = false;
  29976. // iterate over all bindings and check if buffer updates or a new binding group is required
  29977. for ( const binding of bindGroup.bindings ) {
  29978. if ( binding.isNodeUniformsGroup ) {
  29979. const updated = this.nodes.updateGroup( binding );
  29980. if ( ! updated ) continue;
  29981. }
  29982. if ( binding.isUniformBuffer ) {
  29983. const updated = binding.update();
  29984. if ( updated ) {
  29985. backend.updateBinding( binding );
  29986. }
  29987. } else if ( binding.isSampler ) {
  29988. binding.update();
  29989. } else if ( binding.isSampledTexture ) {
  29990. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  29991. const updated = binding.update();
  29992. const texture = binding.texture;
  29993. if ( updated ) {
  29994. this.textures.updateTexture( texture );
  29995. }
  29996. const textureData = backend.get( texture );
  29997. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  29998. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  29999. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  30000. this.textures.updateTexture( texture );
  30001. needsBindingsUpdate = true;
  30002. }
  30003. if ( texture.isStorageTexture === true ) {
  30004. const textureData = this.get( texture );
  30005. if ( binding.store === true ) {
  30006. textureData.needsMipmap = true;
  30007. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  30008. this.backend.generateMipmaps( texture );
  30009. textureData.needsMipmap = false;
  30010. }
  30011. }
  30012. }
  30013. }
  30014. if ( needsBindingsUpdate === true ) {
  30015. this.backend.updateBindings( bindGroup, bindings );
  30016. }
  30017. }
  30018. }
  30019. class NodeAttribute {
  30020. constructor( name, type, node = null ) {
  30021. this.isNodeAttribute = true;
  30022. this.name = name;
  30023. this.type = type;
  30024. this.node = node;
  30025. }
  30026. }
  30027. class NodeUniform {
  30028. constructor( name, type, node ) {
  30029. this.isNodeUniform = true;
  30030. this.name = name;
  30031. this.type = type;
  30032. this.node = node.getSelf();
  30033. }
  30034. get value() {
  30035. return this.node.value;
  30036. }
  30037. set value( val ) {
  30038. this.node.value = val;
  30039. }
  30040. get id() {
  30041. return this.node.id;
  30042. }
  30043. get groupNode() {
  30044. return this.node.groupNode;
  30045. }
  30046. }
  30047. class NodeVar {
  30048. constructor( name, type ) {
  30049. this.isNodeVar = true;
  30050. this.name = name;
  30051. this.type = type;
  30052. }
  30053. }
  30054. class NodeVarying extends NodeVar {
  30055. constructor( name, type ) {
  30056. super( name, type );
  30057. this.needsInterpolation = false;
  30058. this.isNodeVarying = true;
  30059. }
  30060. }
  30061. class NodeCode {
  30062. constructor( name, type, code = '' ) {
  30063. this.name = name;
  30064. this.type = type;
  30065. this.code = code;
  30066. Object.defineProperty( this, 'isNodeCode', { value: true } );
  30067. }
  30068. }
  30069. let id$1 = 0;
  30070. class NodeCache {
  30071. constructor( parent = null ) {
  30072. this.id = id$1 ++;
  30073. this.nodesData = new WeakMap();
  30074. this.parent = parent;
  30075. }
  30076. getData( node ) {
  30077. let data = this.nodesData.get( node );
  30078. if ( data === undefined && this.parent !== null ) {
  30079. data = this.parent.getData( node );
  30080. }
  30081. return data;
  30082. }
  30083. setData( node, data ) {
  30084. this.nodesData.set( node, data );
  30085. }
  30086. }
  30087. class ParameterNode extends PropertyNode {
  30088. static get type() {
  30089. return 'ParameterNode';
  30090. }
  30091. constructor( nodeType, name = null ) {
  30092. super( nodeType, name );
  30093. this.isParameterNode = true;
  30094. }
  30095. getHash() {
  30096. return this.uuid;
  30097. }
  30098. generate() {
  30099. return this.name;
  30100. }
  30101. }
  30102. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30103. class CodeNode extends Node {
  30104. static get type() {
  30105. return 'CodeNode';
  30106. }
  30107. constructor( code = '', includes = [], language = '' ) {
  30108. super( 'code' );
  30109. this.isCodeNode = true;
  30110. this.code = code;
  30111. this.language = language;
  30112. this.includes = includes;
  30113. }
  30114. isGlobal() {
  30115. return true;
  30116. }
  30117. setIncludes( includes ) {
  30118. this.includes = includes;
  30119. return this;
  30120. }
  30121. getIncludes( /*builder*/ ) {
  30122. return this.includes;
  30123. }
  30124. generate( builder ) {
  30125. const includes = this.getIncludes( builder );
  30126. for ( const include of includes ) {
  30127. include.build( builder );
  30128. }
  30129. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  30130. nodeCode.code = this.code;
  30131. return nodeCode.code;
  30132. }
  30133. serialize( data ) {
  30134. super.serialize( data );
  30135. data.code = this.code;
  30136. data.language = this.language;
  30137. }
  30138. deserialize( data ) {
  30139. super.deserialize( data );
  30140. this.code = data.code;
  30141. this.language = data.language;
  30142. }
  30143. }
  30144. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  30145. const js = ( src, includes ) => code( src, includes, 'js' );
  30146. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  30147. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  30148. class FunctionNode extends CodeNode {
  30149. static get type() {
  30150. return 'FunctionNode';
  30151. }
  30152. constructor( code = '', includes = [], language = '' ) {
  30153. super( code, includes, language );
  30154. }
  30155. getNodeType( builder ) {
  30156. return this.getNodeFunction( builder ).type;
  30157. }
  30158. getInputs( builder ) {
  30159. return this.getNodeFunction( builder ).inputs;
  30160. }
  30161. getNodeFunction( builder ) {
  30162. const nodeData = builder.getDataFromNode( this );
  30163. let nodeFunction = nodeData.nodeFunction;
  30164. if ( nodeFunction === undefined ) {
  30165. nodeFunction = builder.parser.parseFunction( this.code );
  30166. nodeData.nodeFunction = nodeFunction;
  30167. }
  30168. return nodeFunction;
  30169. }
  30170. generate( builder, output ) {
  30171. super.generate( builder );
  30172. const nodeFunction = this.getNodeFunction( builder );
  30173. const name = nodeFunction.name;
  30174. const type = nodeFunction.type;
  30175. const nodeCode = builder.getCodeFromNode( this, type );
  30176. if ( name !== '' ) {
  30177. // use a custom property name
  30178. nodeCode.name = name;
  30179. }
  30180. const propertyName = builder.getPropertyName( nodeCode );
  30181. const code = this.getNodeFunction( builder ).getCode( propertyName );
  30182. nodeCode.code = code + '\n';
  30183. if ( output === 'property' ) {
  30184. return propertyName;
  30185. } else {
  30186. return builder.format( `${ propertyName }()`, type, output );
  30187. }
  30188. }
  30189. }
  30190. const nativeFn = ( code, includes = [], language = '' ) => {
  30191. for ( let i = 0; i < includes.length; i ++ ) {
  30192. const include = includes[ i ];
  30193. // TSL Function: glslFn, wgslFn
  30194. if ( typeof include === 'function' ) {
  30195. includes[ i ] = include.functionNode;
  30196. }
  30197. }
  30198. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  30199. const fn = ( ...params ) => functionNode.call( ...params );
  30200. fn.functionNode = functionNode;
  30201. return fn;
  30202. };
  30203. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  30204. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  30205. class Uniform {
  30206. constructor( name, value ) {
  30207. this.name = name;
  30208. this.value = value;
  30209. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  30210. this.itemSize = 0;
  30211. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  30212. }
  30213. setValue( value ) {
  30214. this.value = value;
  30215. }
  30216. getValue() {
  30217. return this.value;
  30218. }
  30219. }
  30220. class NumberUniform extends Uniform {
  30221. constructor( name, value = 0 ) {
  30222. super( name, value );
  30223. this.isNumberUniform = true;
  30224. this.boundary = 4;
  30225. this.itemSize = 1;
  30226. }
  30227. }
  30228. class Vector2Uniform extends Uniform {
  30229. constructor( name, value = new Vector2() ) {
  30230. super( name, value );
  30231. this.isVector2Uniform = true;
  30232. this.boundary = 8;
  30233. this.itemSize = 2;
  30234. }
  30235. }
  30236. class Vector3Uniform extends Uniform {
  30237. constructor( name, value = new Vector3() ) {
  30238. super( name, value );
  30239. this.isVector3Uniform = true;
  30240. this.boundary = 16;
  30241. this.itemSize = 3;
  30242. }
  30243. }
  30244. class Vector4Uniform extends Uniform {
  30245. constructor( name, value = new Vector4() ) {
  30246. super( name, value );
  30247. this.isVector4Uniform = true;
  30248. this.boundary = 16;
  30249. this.itemSize = 4;
  30250. }
  30251. }
  30252. class ColorUniform extends Uniform {
  30253. constructor( name, value = new Color() ) {
  30254. super( name, value );
  30255. this.isColorUniform = true;
  30256. this.boundary = 16;
  30257. this.itemSize = 3;
  30258. }
  30259. }
  30260. class Matrix3Uniform extends Uniform {
  30261. constructor( name, value = new Matrix3() ) {
  30262. super( name, value );
  30263. this.isMatrix3Uniform = true;
  30264. this.boundary = 48;
  30265. this.itemSize = 12;
  30266. }
  30267. }
  30268. class Matrix4Uniform extends Uniform {
  30269. constructor( name, value = new Matrix4() ) {
  30270. super( name, value );
  30271. this.isMatrix4Uniform = true;
  30272. this.boundary = 64;
  30273. this.itemSize = 16;
  30274. }
  30275. }
  30276. class NumberNodeUniform extends NumberUniform {
  30277. constructor( nodeUniform ) {
  30278. super( nodeUniform.name, nodeUniform.value );
  30279. this.nodeUniform = nodeUniform;
  30280. }
  30281. getValue() {
  30282. return this.nodeUniform.value;
  30283. }
  30284. }
  30285. class Vector2NodeUniform extends Vector2Uniform {
  30286. constructor( nodeUniform ) {
  30287. super( nodeUniform.name, nodeUniform.value );
  30288. this.nodeUniform = nodeUniform;
  30289. }
  30290. getValue() {
  30291. return this.nodeUniform.value;
  30292. }
  30293. }
  30294. class Vector3NodeUniform extends Vector3Uniform {
  30295. constructor( nodeUniform ) {
  30296. super( nodeUniform.name, nodeUniform.value );
  30297. this.nodeUniform = nodeUniform;
  30298. }
  30299. getValue() {
  30300. return this.nodeUniform.value;
  30301. }
  30302. }
  30303. class Vector4NodeUniform extends Vector4Uniform {
  30304. constructor( nodeUniform ) {
  30305. super( nodeUniform.name, nodeUniform.value );
  30306. this.nodeUniform = nodeUniform;
  30307. }
  30308. getValue() {
  30309. return this.nodeUniform.value;
  30310. }
  30311. }
  30312. class ColorNodeUniform extends ColorUniform {
  30313. constructor( nodeUniform ) {
  30314. super( nodeUniform.name, nodeUniform.value );
  30315. this.nodeUniform = nodeUniform;
  30316. }
  30317. getValue() {
  30318. return this.nodeUniform.value;
  30319. }
  30320. }
  30321. class Matrix3NodeUniform extends Matrix3Uniform {
  30322. constructor( nodeUniform ) {
  30323. super( nodeUniform.name, nodeUniform.value );
  30324. this.nodeUniform = nodeUniform;
  30325. }
  30326. getValue() {
  30327. return this.nodeUniform.value;
  30328. }
  30329. }
  30330. class Matrix4NodeUniform extends Matrix4Uniform {
  30331. constructor( nodeUniform ) {
  30332. super( nodeUniform.name, nodeUniform.value );
  30333. this.nodeUniform = nodeUniform;
  30334. }
  30335. getValue() {
  30336. return this.nodeUniform.value;
  30337. }
  30338. }
  30339. class StackNode extends Node {
  30340. static get type() {
  30341. return 'StackNode';
  30342. }
  30343. constructor( parent = null ) {
  30344. super();
  30345. this.nodes = [];
  30346. this.outputNode = null;
  30347. this.parent = parent;
  30348. this._currentCond = null;
  30349. this.isStackNode = true;
  30350. }
  30351. getNodeType( builder ) {
  30352. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30353. }
  30354. add( node ) {
  30355. this.nodes.push( node );
  30356. return this;
  30357. }
  30358. If( boolNode, method ) {
  30359. const methodNode = new ShaderNode( method );
  30360. this._currentCond = select( boolNode, methodNode );
  30361. return this.add( this._currentCond );
  30362. }
  30363. ElseIf( boolNode, method ) {
  30364. const methodNode = new ShaderNode( method );
  30365. const ifNode = select( boolNode, methodNode );
  30366. this._currentCond.elseNode = ifNode;
  30367. this._currentCond = ifNode;
  30368. return this;
  30369. }
  30370. Else( method ) {
  30371. this._currentCond.elseNode = new ShaderNode( method );
  30372. return this;
  30373. }
  30374. build( builder, ...params ) {
  30375. const previousStack = getCurrentStack();
  30376. setCurrentStack( this );
  30377. for ( const node of this.nodes ) {
  30378. node.build( builder, 'void' );
  30379. }
  30380. setCurrentStack( previousStack );
  30381. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30382. }
  30383. //
  30384. else( ...params ) { // @deprecated, r168
  30385. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30386. return this.Else( ...params );
  30387. }
  30388. elseif( ...params ) { // @deprecated, r168
  30389. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30390. return this.ElseIf( ...params );
  30391. }
  30392. }
  30393. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30394. const LOD_MIN = 4;
  30395. // The standard deviations (radians) associated with the extra mips. These are
  30396. // chosen to approximate a Trowbridge-Reitz distribution function times the
  30397. // geometric shadowing function. These sigma values squared must match the
  30398. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  30399. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  30400. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  30401. // samples and exit early, but not recompile the shader.
  30402. const MAX_SAMPLES = 20;
  30403. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  30404. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  30405. const _clearColor$2 = /*@__PURE__*/ new Color();
  30406. let _oldTarget = null;
  30407. let _oldActiveCubeFace = 0;
  30408. let _oldActiveMipmapLevel = 0;
  30409. // Golden Ratio
  30410. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  30411. const INV_PHI = 1 / PHI;
  30412. // Vertices of a dodecahedron (except the opposites, which represent the
  30413. // same axis), used as axis directions evenly spread on a sphere.
  30414. const _axisDirections = [
  30415. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  30416. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  30417. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  30418. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  30419. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  30420. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  30421. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  30422. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  30423. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  30424. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  30425. ];
  30426. //
  30427. // WebGPU Face indices
  30428. const _faceLib = [
  30429. 3, 1, 5,
  30430. 0, 4, 2
  30431. ];
  30432. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  30433. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  30434. /**
  30435. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  30436. * (PMREM) from a cubeMap environment texture. This allows different levels of
  30437. * blur to be quickly accessed based on material roughness. It is packed into a
  30438. * special CubeUV format that allows us to perform custom interpolation so that
  30439. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  30440. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  30441. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  30442. * higher roughness levels. In this way we maintain resolution to smoothly
  30443. * interpolate diffuse lighting while limiting sampling computation.
  30444. *
  30445. * Paper: Fast, Accurate Image-Based Lighting
  30446. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  30447. */
  30448. class PMREMGenerator {
  30449. constructor( renderer ) {
  30450. this._renderer = renderer;
  30451. this._pingPongRenderTarget = null;
  30452. this._lodMax = 0;
  30453. this._cubeSize = 0;
  30454. this._lodPlanes = [];
  30455. this._sizeLods = [];
  30456. this._sigmas = [];
  30457. this._lodMeshes = [];
  30458. this._blurMaterial = null;
  30459. this._cubemapMaterial = null;
  30460. this._equirectMaterial = null;
  30461. this._backgroundBox = null;
  30462. }
  30463. /**
  30464. * Generates a PMREM from a supplied Scene, which can be faster than using an
  30465. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  30466. * in radians to be applied to the scene before PMREM generation. Optional near
  30467. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  30468. * is placed at the origin).
  30469. */
  30470. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  30471. _oldTarget = this._renderer.getRenderTarget();
  30472. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30473. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30474. this._setSize( 256 );
  30475. const cubeUVRenderTarget = this._allocateTargets();
  30476. cubeUVRenderTarget.depthBuffer = true;
  30477. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  30478. if ( sigma > 0 ) {
  30479. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  30480. }
  30481. this._applyPMREM( cubeUVRenderTarget );
  30482. this._cleanup( cubeUVRenderTarget );
  30483. return cubeUVRenderTarget;
  30484. }
  30485. /**
  30486. * Generates a PMREM from an equirectangular texture, which can be either LDR
  30487. * or HDR. The ideal input image size is 1k (1024 x 512),
  30488. * as this matches best with the 256 x 256 cubemap output.
  30489. */
  30490. fromEquirectangular( equirectangular, renderTarget = null ) {
  30491. return this._fromTexture( equirectangular, renderTarget );
  30492. }
  30493. /**
  30494. * Generates a PMREM from an cubemap texture, which can be either LDR
  30495. * or HDR. The ideal input cube size is 256 x 256,
  30496. * as this matches best with the 256 x 256 cubemap output.
  30497. */
  30498. fromCubemap( cubemap, renderTarget = null ) {
  30499. return this._fromTexture( cubemap, renderTarget );
  30500. }
  30501. /**
  30502. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  30503. * your texture's network fetch for increased concurrency.
  30504. */
  30505. async compileCubemapShader() {
  30506. if ( this._cubemapMaterial === null ) {
  30507. this._cubemapMaterial = _getCubemapMaterial();
  30508. await this._compileMaterial( this._cubemapMaterial );
  30509. }
  30510. }
  30511. /**
  30512. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  30513. * your texture's network fetch for increased concurrency.
  30514. */
  30515. async compileEquirectangularShader() {
  30516. if ( this._equirectMaterial === null ) {
  30517. this._equirectMaterial = _getEquirectMaterial();
  30518. await this._compileMaterial( this._equirectMaterial );
  30519. }
  30520. }
  30521. /**
  30522. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  30523. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  30524. * one of them will cause any others to also become unusable.
  30525. */
  30526. dispose() {
  30527. this._dispose();
  30528. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  30529. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  30530. if ( this._backgroundBox !== null ) {
  30531. this._backgroundBox.geometry.dispose();
  30532. this._backgroundBox.material.dispose();
  30533. }
  30534. }
  30535. // private interface
  30536. _setSize( cubeSize ) {
  30537. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  30538. this._cubeSize = Math.pow( 2, this._lodMax );
  30539. }
  30540. _dispose() {
  30541. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  30542. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  30543. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  30544. this._lodPlanes[ i ].dispose();
  30545. }
  30546. }
  30547. _cleanup( outputTarget ) {
  30548. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  30549. outputTarget.scissorTest = false;
  30550. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  30551. }
  30552. _fromTexture( texture, renderTarget ) {
  30553. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  30554. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  30555. } else { // Equirectangular
  30556. this._setSize( texture.image.width / 4 );
  30557. }
  30558. _oldTarget = this._renderer.getRenderTarget();
  30559. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30560. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30561. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  30562. this._textureToCubeUV( texture, cubeUVRenderTarget );
  30563. this._applyPMREM( cubeUVRenderTarget );
  30564. this._cleanup( cubeUVRenderTarget );
  30565. return cubeUVRenderTarget;
  30566. }
  30567. _allocateTargets() {
  30568. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  30569. const height = 4 * this._cubeSize;
  30570. const params = {
  30571. magFilter: LinearFilter,
  30572. minFilter: LinearFilter,
  30573. generateMipmaps: false,
  30574. type: HalfFloatType,
  30575. format: RGBAFormat,
  30576. colorSpace: LinearSRGBColorSpace,
  30577. //depthBuffer: false
  30578. };
  30579. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  30580. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  30581. if ( this._pingPongRenderTarget !== null ) {
  30582. this._dispose();
  30583. }
  30584. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  30585. const { _lodMax } = this;
  30586. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  30587. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  30588. }
  30589. return cubeUVRenderTarget;
  30590. }
  30591. async _compileMaterial( material ) {
  30592. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  30593. await this._renderer.compile( tmpMesh, _flatCamera );
  30594. }
  30595. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  30596. const cubeCamera = _cubeCamera;
  30597. cubeCamera.near = near;
  30598. cubeCamera.far = far;
  30599. // px, py, pz, nx, ny, nz
  30600. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  30601. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  30602. const renderer = this._renderer;
  30603. const originalAutoClear = renderer.autoClear;
  30604. renderer.getClearColor( _clearColor$2 );
  30605. renderer.autoClear = false;
  30606. let backgroundBox = this._backgroundBox;
  30607. if ( backgroundBox === null ) {
  30608. const backgroundMaterial = new MeshBasicMaterial( {
  30609. name: 'PMREM.Background',
  30610. side: BackSide,
  30611. depthWrite: false,
  30612. depthTest: false
  30613. } );
  30614. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  30615. }
  30616. let useSolidColor = false;
  30617. const background = scene.background;
  30618. if ( background ) {
  30619. if ( background.isColor ) {
  30620. backgroundBox.material.color.copy( background );
  30621. scene.background = null;
  30622. useSolidColor = true;
  30623. }
  30624. } else {
  30625. backgroundBox.material.color.copy( _clearColor$2 );
  30626. useSolidColor = true;
  30627. }
  30628. renderer.setRenderTarget( cubeUVRenderTarget );
  30629. renderer.clear();
  30630. if ( useSolidColor ) {
  30631. renderer.render( backgroundBox, cubeCamera );
  30632. }
  30633. for ( let i = 0; i < 6; i ++ ) {
  30634. const col = i % 3;
  30635. if ( col === 0 ) {
  30636. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30637. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  30638. } else if ( col === 1 ) {
  30639. cubeCamera.up.set( 0, 0, upSign[ i ] );
  30640. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  30641. } else {
  30642. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30643. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  30644. }
  30645. const size = this._cubeSize;
  30646. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  30647. renderer.render( scene, cubeCamera );
  30648. }
  30649. renderer.autoClear = originalAutoClear;
  30650. scene.background = background;
  30651. }
  30652. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  30653. const renderer = this._renderer;
  30654. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  30655. if ( isCubeTexture ) {
  30656. if ( this._cubemapMaterial === null ) {
  30657. this._cubemapMaterial = _getCubemapMaterial( texture );
  30658. }
  30659. } else {
  30660. if ( this._equirectMaterial === null ) {
  30661. this._equirectMaterial = _getEquirectMaterial( texture );
  30662. }
  30663. }
  30664. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  30665. material.fragmentNode.value = texture;
  30666. const mesh = this._lodMeshes[ 0 ];
  30667. mesh.material = material;
  30668. const size = this._cubeSize;
  30669. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  30670. renderer.setRenderTarget( cubeUVRenderTarget );
  30671. renderer.render( mesh, _flatCamera );
  30672. }
  30673. _applyPMREM( cubeUVRenderTarget ) {
  30674. const renderer = this._renderer;
  30675. const autoClear = renderer.autoClear;
  30676. renderer.autoClear = false;
  30677. const n = this._lodPlanes.length;
  30678. for ( let i = 1; i < n; i ++ ) {
  30679. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  30680. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  30681. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  30682. }
  30683. renderer.autoClear = autoClear;
  30684. }
  30685. /**
  30686. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  30687. * vertically and horizontally, but this breaks down on a cube. Here we apply
  30688. * the blur latitudinally (around the poles), and then longitudinally (towards
  30689. * the poles) to approximate the orthogonally-separable blur. It is least
  30690. * accurate at the poles, but still does a decent job.
  30691. */
  30692. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  30693. const pingPongRenderTarget = this._pingPongRenderTarget;
  30694. this._halfBlur(
  30695. cubeUVRenderTarget,
  30696. pingPongRenderTarget,
  30697. lodIn,
  30698. lodOut,
  30699. sigma,
  30700. 'latitudinal',
  30701. poleAxis );
  30702. this._halfBlur(
  30703. pingPongRenderTarget,
  30704. cubeUVRenderTarget,
  30705. lodOut,
  30706. lodOut,
  30707. sigma,
  30708. 'longitudinal',
  30709. poleAxis );
  30710. }
  30711. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  30712. const renderer = this._renderer;
  30713. const blurMaterial = this._blurMaterial;
  30714. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  30715. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  30716. }
  30717. // Number of standard deviations at which to cut off the discrete approximation.
  30718. const STANDARD_DEVIATIONS = 3;
  30719. const blurMesh = this._lodMeshes[ lodOut ];
  30720. blurMesh.material = blurMaterial;
  30721. const blurUniforms = blurMaterial.uniforms;
  30722. const pixels = this._sizeLods[ lodIn ] - 1;
  30723. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  30724. const sigmaPixels = sigmaRadians / radiansPerPixel;
  30725. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  30726. if ( samples > MAX_SAMPLES ) {
  30727. console.warn( `sigmaRadians, ${
  30728. sigmaRadians}, is too large and will clip, as it requested ${
  30729. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  30730. }
  30731. const weights = [];
  30732. let sum = 0;
  30733. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  30734. const x = i / sigmaPixels;
  30735. const weight = Math.exp( - x * x / 2 );
  30736. weights.push( weight );
  30737. if ( i === 0 ) {
  30738. sum += weight;
  30739. } else if ( i < samples ) {
  30740. sum += 2 * weight;
  30741. }
  30742. }
  30743. for ( let i = 0; i < weights.length; i ++ ) {
  30744. weights[ i ] = weights[ i ] / sum;
  30745. }
  30746. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  30747. blurUniforms.envMap.value = targetIn.texture;
  30748. blurUniforms.samples.value = samples;
  30749. blurUniforms.weights.array = weights;
  30750. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  30751. if ( poleAxis ) {
  30752. blurUniforms.poleAxis.value = poleAxis;
  30753. }
  30754. const { _lodMax } = this;
  30755. blurUniforms.dTheta.value = radiansPerPixel;
  30756. blurUniforms.mipInt.value = _lodMax - lodIn;
  30757. const outputSize = this._sizeLods[ lodOut ];
  30758. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  30759. const y = 4 * ( this._cubeSize - outputSize );
  30760. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  30761. renderer.setRenderTarget( targetOut );
  30762. renderer.render( blurMesh, _flatCamera );
  30763. }
  30764. }
  30765. function _createPlanes( lodMax ) {
  30766. const lodPlanes = [];
  30767. const sizeLods = [];
  30768. const sigmas = [];
  30769. const lodMeshes = [];
  30770. let lod = lodMax;
  30771. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  30772. for ( let i = 0; i < totalLods; i ++ ) {
  30773. const sizeLod = Math.pow( 2, lod );
  30774. sizeLods.push( sizeLod );
  30775. let sigma = 1.0 / sizeLod;
  30776. if ( i > lodMax - LOD_MIN ) {
  30777. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  30778. } else if ( i === 0 ) {
  30779. sigma = 0;
  30780. }
  30781. sigmas.push( sigma );
  30782. const texelSize = 1.0 / ( sizeLod - 2 );
  30783. const min = - texelSize;
  30784. const max = 1 + texelSize;
  30785. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  30786. const cubeFaces = 6;
  30787. const vertices = 6;
  30788. const positionSize = 3;
  30789. const uvSize = 2;
  30790. const faceIndexSize = 1;
  30791. const position = new Float32Array( positionSize * vertices * cubeFaces );
  30792. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  30793. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  30794. for ( let face = 0; face < cubeFaces; face ++ ) {
  30795. const x = ( face % 3 ) * 2 / 3 - 1;
  30796. const y = face > 2 ? 0 : - 1;
  30797. const coordinates = [
  30798. x, y, 0,
  30799. x + 2 / 3, y, 0,
  30800. x + 2 / 3, y + 1, 0,
  30801. x, y, 0,
  30802. x + 2 / 3, y + 1, 0,
  30803. x, y + 1, 0
  30804. ];
  30805. const faceIdx = _faceLib[ face ];
  30806. position.set( coordinates, positionSize * vertices * faceIdx );
  30807. uv.set( uv1, uvSize * vertices * faceIdx );
  30808. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  30809. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  30810. }
  30811. const planes = new BufferGeometry();
  30812. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  30813. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  30814. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  30815. lodPlanes.push( planes );
  30816. lodMeshes.push( new Mesh( planes, null ) );
  30817. if ( lod > LOD_MIN ) {
  30818. lod --;
  30819. }
  30820. }
  30821. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  30822. }
  30823. function _createRenderTarget( width, height, params ) {
  30824. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  30825. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  30826. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  30827. cubeUVRenderTarget.texture.isPMREMTexture = true;
  30828. cubeUVRenderTarget.scissorTest = true;
  30829. return cubeUVRenderTarget;
  30830. }
  30831. function _setViewport( target, x, y, width, height ) {
  30832. target.viewport.set( x, y, width, height );
  30833. target.scissor.set( x, y, width, height );
  30834. }
  30835. function _getMaterial( type ) {
  30836. const material = new NodeMaterial();
  30837. material.depthTest = false;
  30838. material.depthWrite = false;
  30839. material.blending = NoBlending;
  30840. material.name = `PMREM_${ type }`;
  30841. return material;
  30842. }
  30843. function _getBlurShader( lodMax, width, height ) {
  30844. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  30845. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  30846. const dTheta = uniform( 0 );
  30847. const n = float( MAX_SAMPLES );
  30848. const latitudinal = uniform( 0 ); // false, bool
  30849. const samples = uniform( 1 ); // int
  30850. const envMap = texture( null );
  30851. const mipInt = uniform( 0 ); // int
  30852. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  30853. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  30854. const CUBEUV_MAX_MIP = float( lodMax );
  30855. const materialUniforms = {
  30856. n,
  30857. latitudinal,
  30858. weights,
  30859. poleAxis,
  30860. outputDirection,
  30861. dTheta,
  30862. samples,
  30863. envMap,
  30864. mipInt,
  30865. CUBEUV_TEXEL_WIDTH,
  30866. CUBEUV_TEXEL_HEIGHT,
  30867. CUBEUV_MAX_MIP
  30868. };
  30869. const material = _getMaterial( 'blur' );
  30870. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  30871. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  30872. return material;
  30873. }
  30874. function _getCubemapMaterial( envTexture ) {
  30875. const material = _getMaterial( 'cubemap' );
  30876. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  30877. return material;
  30878. }
  30879. function _getEquirectMaterial( envTexture ) {
  30880. const material = _getMaterial( 'equirect' );
  30881. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  30882. return material;
  30883. }
  30884. let _id$5 = 0;
  30885. class BindGroup {
  30886. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30887. this.name = name;
  30888. this.bindings = bindings;
  30889. this.index = index;
  30890. this.bindingsReference = bindingsReference;
  30891. this.id = _id$5 ++;
  30892. }
  30893. }
  30894. const rendererCache = new WeakMap();
  30895. const typeFromLength = new Map( [
  30896. [ 2, 'vec2' ],
  30897. [ 3, 'vec3' ],
  30898. [ 4, 'vec4' ],
  30899. [ 9, 'mat3' ],
  30900. [ 16, 'mat4' ]
  30901. ] );
  30902. const typeFromArray = new Map( [
  30903. [ Int8Array, 'int' ],
  30904. [ Int16Array, 'int' ],
  30905. [ Int32Array, 'int' ],
  30906. [ Uint8Array, 'uint' ],
  30907. [ Uint16Array, 'uint' ],
  30908. [ Uint32Array, 'uint' ],
  30909. [ Float32Array, 'float' ]
  30910. ] );
  30911. const toFloat = ( value ) => {
  30912. value = Number( value );
  30913. return value + ( value % 1 ? '' : '.0' );
  30914. };
  30915. class NodeBuilder {
  30916. constructor( object, renderer, parser ) {
  30917. this.object = object;
  30918. this.material = ( object && object.material ) || null;
  30919. this.geometry = ( object && object.geometry ) || null;
  30920. this.renderer = renderer;
  30921. this.parser = parser;
  30922. this.scene = null;
  30923. this.camera = null;
  30924. this.nodes = [];
  30925. this.updateNodes = [];
  30926. this.updateBeforeNodes = [];
  30927. this.updateAfterNodes = [];
  30928. this.hashNodes = {};
  30929. this.monitor = null;
  30930. this.lightsNode = null;
  30931. this.environmentNode = null;
  30932. this.fogNode = null;
  30933. this.clippingContext = null;
  30934. this.vertexShader = null;
  30935. this.fragmentShader = null;
  30936. this.computeShader = null;
  30937. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30938. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30939. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30940. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30941. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30942. this.bindingsIndexes = {};
  30943. this.bindGroups = null;
  30944. this.attributes = [];
  30945. this.bufferAttributes = [];
  30946. this.varyings = [];
  30947. this.codes = {};
  30948. this.vars = {};
  30949. this.flow = { code: '' };
  30950. this.chaining = [];
  30951. this.stack = stack();
  30952. this.stacks = [];
  30953. this.tab = '\t';
  30954. this.currentFunctionNode = null;
  30955. this.context = {
  30956. material: this.material
  30957. };
  30958. this.cache = new NodeCache();
  30959. this.globalCache = this.cache;
  30960. this.flowsData = new WeakMap();
  30961. this.shaderStage = null;
  30962. this.buildStage = null;
  30963. this.useComparisonMethod = false;
  30964. }
  30965. getBindGroupsCache() {
  30966. let bindGroupsCache = rendererCache.get( this.renderer );
  30967. if ( bindGroupsCache === undefined ) {
  30968. bindGroupsCache = new ChainMap();
  30969. rendererCache.set( this.renderer, bindGroupsCache );
  30970. }
  30971. return bindGroupsCache;
  30972. }
  30973. createRenderTarget( width, height, options ) {
  30974. return new RenderTarget( width, height, options );
  30975. }
  30976. createCubeRenderTarget( size, options ) {
  30977. return new CubeRenderTarget( size, options );
  30978. }
  30979. createPMREMGenerator() {
  30980. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30981. return new PMREMGenerator( this.renderer );
  30982. }
  30983. includes( node ) {
  30984. return this.nodes.includes( node );
  30985. }
  30986. _getBindGroup( groupName, bindings ) {
  30987. const bindGroupsCache = this.getBindGroupsCache();
  30988. //
  30989. const bindingsArray = [];
  30990. let sharedGroup = true;
  30991. for ( const binding of bindings ) {
  30992. bindingsArray.push( binding );
  30993. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30994. }
  30995. //
  30996. let bindGroup;
  30997. if ( sharedGroup ) {
  30998. bindGroup = bindGroupsCache.get( bindingsArray );
  30999. if ( bindGroup === undefined ) {
  31000. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31001. bindGroupsCache.set( bindingsArray, bindGroup );
  31002. }
  31003. } else {
  31004. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31005. }
  31006. return bindGroup;
  31007. }
  31008. getBindGroupArray( groupName, shaderStage ) {
  31009. const bindings = this.bindings[ shaderStage ];
  31010. let bindGroup = bindings[ groupName ];
  31011. if ( bindGroup === undefined ) {
  31012. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31013. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31014. }
  31015. bindings[ groupName ] = bindGroup = [];
  31016. }
  31017. return bindGroup;
  31018. }
  31019. getBindings() {
  31020. let bindingsGroups = this.bindGroups;
  31021. if ( bindingsGroups === null ) {
  31022. const groups = {};
  31023. const bindings = this.bindings;
  31024. for ( const shaderStage of shaderStages ) {
  31025. for ( const groupName in bindings[ shaderStage ] ) {
  31026. const uniforms = bindings[ shaderStage ][ groupName ];
  31027. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31028. groupUniforms.push( ...uniforms );
  31029. }
  31030. }
  31031. bindingsGroups = [];
  31032. for ( const groupName in groups ) {
  31033. const group = groups[ groupName ];
  31034. const bindingsGroup = this._getBindGroup( groupName, group );
  31035. bindingsGroups.push( bindingsGroup );
  31036. }
  31037. this.bindGroups = bindingsGroups;
  31038. }
  31039. return bindingsGroups;
  31040. }
  31041. sortBindingGroups() {
  31042. const bindingsGroups = this.getBindings();
  31043. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  31044. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  31045. const bindingGroup = bindingsGroups[ i ];
  31046. this.bindingsIndexes[ bindingGroup.name ].group = i;
  31047. bindingGroup.index = i;
  31048. }
  31049. }
  31050. setHashNode( node, hash ) {
  31051. this.hashNodes[ hash ] = node;
  31052. }
  31053. addNode( node ) {
  31054. if ( this.nodes.includes( node ) === false ) {
  31055. this.nodes.push( node );
  31056. this.setHashNode( node, node.getHash( this ) );
  31057. }
  31058. }
  31059. buildUpdateNodes() {
  31060. for ( const node of this.nodes ) {
  31061. const updateType = node.getUpdateType();
  31062. const updateBeforeType = node.getUpdateBeforeType();
  31063. const updateAfterType = node.getUpdateAfterType();
  31064. if ( updateType !== NodeUpdateType.NONE ) {
  31065. this.updateNodes.push( node.getSelf() );
  31066. }
  31067. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  31068. this.updateBeforeNodes.push( node.getSelf() );
  31069. }
  31070. if ( updateAfterType !== NodeUpdateType.NONE ) {
  31071. this.updateAfterNodes.push( node.getSelf() );
  31072. }
  31073. }
  31074. }
  31075. get currentNode() {
  31076. return this.chaining[ this.chaining.length - 1 ];
  31077. }
  31078. isFilteredTexture( texture ) {
  31079. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  31080. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  31081. }
  31082. addChain( node ) {
  31083. /*
  31084. if ( this.chaining.indexOf( node ) !== - 1 ) {
  31085. console.warn( 'Recursive node: ', node );
  31086. }
  31087. */
  31088. this.chaining.push( node );
  31089. }
  31090. removeChain( node ) {
  31091. const lastChain = this.chaining.pop();
  31092. if ( lastChain !== node ) {
  31093. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  31094. }
  31095. }
  31096. getMethod( method ) {
  31097. return method;
  31098. }
  31099. getNodeFromHash( hash ) {
  31100. return this.hashNodes[ hash ];
  31101. }
  31102. addFlow( shaderStage, node ) {
  31103. this.flowNodes[ shaderStage ].push( node );
  31104. return node;
  31105. }
  31106. setContext( context ) {
  31107. this.context = context;
  31108. }
  31109. getContext() {
  31110. return this.context;
  31111. }
  31112. getSharedContext() {
  31113. ({ ...this.context });
  31114. return this.context;
  31115. }
  31116. setCache( cache ) {
  31117. this.cache = cache;
  31118. }
  31119. getCache() {
  31120. return this.cache;
  31121. }
  31122. getCacheFromNode( node, parent = true ) {
  31123. const data = this.getDataFromNode( node );
  31124. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31125. return data.cache;
  31126. }
  31127. isAvailable( /*name*/ ) {
  31128. return false;
  31129. }
  31130. getVertexIndex() {
  31131. console.warn( 'Abstract function.' );
  31132. }
  31133. getInstanceIndex() {
  31134. console.warn( 'Abstract function.' );
  31135. }
  31136. getDrawIndex() {
  31137. console.warn( 'Abstract function.' );
  31138. }
  31139. getFrontFacing() {
  31140. console.warn( 'Abstract function.' );
  31141. }
  31142. getFragCoord() {
  31143. console.warn( 'Abstract function.' );
  31144. }
  31145. isFlipY() {
  31146. return false;
  31147. }
  31148. increaseUsage( node ) {
  31149. const nodeData = this.getDataFromNode( node );
  31150. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31151. return nodeData.usageCount;
  31152. }
  31153. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31154. console.warn( 'Abstract function.' );
  31155. }
  31156. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  31157. console.warn( 'Abstract function.' );
  31158. }
  31159. generateConst( type, value = null ) {
  31160. if ( value === null ) {
  31161. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31162. else if ( type === 'bool' ) value = false;
  31163. else if ( type === 'color' ) value = new Color();
  31164. else if ( type === 'vec2' ) value = new Vector2();
  31165. else if ( type === 'vec3' ) value = new Vector3();
  31166. else if ( type === 'vec4' ) value = new Vector4();
  31167. }
  31168. if ( type === 'float' ) return toFloat( value );
  31169. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31170. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31171. if ( type === 'bool' ) return value ? 'true' : 'false';
  31172. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31173. const typeLength = this.getTypeLength( type );
  31174. const componentType = this.getComponentType( type );
  31175. const generateConst = value => this.generateConst( componentType, value );
  31176. if ( typeLength === 2 ) {
  31177. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31178. } else if ( typeLength === 3 ) {
  31179. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31180. } else if ( typeLength === 4 ) {
  31181. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31182. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  31183. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31184. } else if ( typeLength > 4 ) {
  31185. return `${ this.getType( type ) }()`;
  31186. }
  31187. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31188. }
  31189. getType( type ) {
  31190. if ( type === 'color' ) return 'vec3';
  31191. return type;
  31192. }
  31193. hasGeometryAttribute( name ) {
  31194. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31195. }
  31196. getAttribute( name, type ) {
  31197. const attributes = this.attributes;
  31198. // find attribute
  31199. for ( const attribute of attributes ) {
  31200. if ( attribute.name === name ) {
  31201. return attribute;
  31202. }
  31203. }
  31204. // create a new if no exist
  31205. const attribute = new NodeAttribute( name, type );
  31206. attributes.push( attribute );
  31207. return attribute;
  31208. }
  31209. getPropertyName( node/*, shaderStage*/ ) {
  31210. return node.name;
  31211. }
  31212. isVector( type ) {
  31213. return /vec\d/.test( type );
  31214. }
  31215. isMatrix( type ) {
  31216. return /mat\d/.test( type );
  31217. }
  31218. isReference( type ) {
  31219. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31220. }
  31221. needsToWorkingColorSpace( /*texture*/ ) {
  31222. return false;
  31223. }
  31224. getComponentTypeFromTexture( texture ) {
  31225. const type = texture.type;
  31226. if ( texture.isDataTexture ) {
  31227. if ( type === IntType ) return 'int';
  31228. if ( type === UnsignedIntType ) return 'uint';
  31229. }
  31230. return 'float';
  31231. }
  31232. getElementType( type ) {
  31233. if ( type === 'mat2' ) return 'vec2';
  31234. if ( type === 'mat3' ) return 'vec3';
  31235. if ( type === 'mat4' ) return 'vec4';
  31236. return this.getComponentType( type );
  31237. }
  31238. getComponentType( type ) {
  31239. type = this.getVectorType( type );
  31240. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31241. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31242. if ( componentType === null ) return null;
  31243. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31244. if ( componentType[ 1 ] === 'i' ) return 'int';
  31245. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31246. return 'float';
  31247. }
  31248. getVectorType( type ) {
  31249. if ( type === 'color' ) return 'vec3';
  31250. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31251. return type;
  31252. }
  31253. getTypeFromLength( length, componentType = 'float' ) {
  31254. if ( length === 1 ) return componentType;
  31255. const baseType = typeFromLength.get( length );
  31256. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31257. return prefix + baseType;
  31258. }
  31259. getTypeFromArray( array ) {
  31260. return typeFromArray.get( array.constructor );
  31261. }
  31262. getTypeFromAttribute( attribute ) {
  31263. let dataAttribute = attribute;
  31264. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31265. const array = dataAttribute.array;
  31266. const itemSize = attribute.itemSize;
  31267. const normalized = attribute.normalized;
  31268. let arrayType;
  31269. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31270. arrayType = this.getTypeFromArray( array );
  31271. }
  31272. return this.getTypeFromLength( itemSize, arrayType );
  31273. }
  31274. getTypeLength( type ) {
  31275. const vecType = this.getVectorType( type );
  31276. const vecNum = /vec([2-4])/.exec( vecType );
  31277. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31278. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31279. if ( /mat2/.test( type ) === true ) return 4;
  31280. if ( /mat3/.test( type ) === true ) return 9;
  31281. if ( /mat4/.test( type ) === true ) return 16;
  31282. return 0;
  31283. }
  31284. getVectorFromMatrix( type ) {
  31285. return type.replace( 'mat', 'vec' );
  31286. }
  31287. changeComponentType( type, newComponentType ) {
  31288. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31289. }
  31290. getIntegerType( type ) {
  31291. const componentType = this.getComponentType( type );
  31292. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31293. return this.changeComponentType( type, 'int' );
  31294. }
  31295. addStack() {
  31296. this.stack = stack( this.stack );
  31297. this.stacks.push( getCurrentStack() || this.stack );
  31298. setCurrentStack( this.stack );
  31299. return this.stack;
  31300. }
  31301. removeStack() {
  31302. const lastStack = this.stack;
  31303. this.stack = lastStack.parent;
  31304. setCurrentStack( this.stacks.pop() );
  31305. return lastStack;
  31306. }
  31307. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31308. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31309. let nodeData = cache.getData( node );
  31310. if ( nodeData === undefined ) {
  31311. nodeData = {};
  31312. cache.setData( node, nodeData );
  31313. }
  31314. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31315. return nodeData[ shaderStage ];
  31316. }
  31317. getNodeProperties( node, shaderStage = 'any' ) {
  31318. const nodeData = this.getDataFromNode( node, shaderStage );
  31319. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31320. }
  31321. getBufferAttributeFromNode( node, type ) {
  31322. const nodeData = this.getDataFromNode( node );
  31323. let bufferAttribute = nodeData.bufferAttribute;
  31324. if ( bufferAttribute === undefined ) {
  31325. const index = this.uniforms.index ++;
  31326. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31327. this.bufferAttributes.push( bufferAttribute );
  31328. nodeData.bufferAttribute = bufferAttribute;
  31329. }
  31330. return bufferAttribute;
  31331. }
  31332. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  31333. const nodeData = this.getDataFromNode( node, shaderStage );
  31334. if ( nodeData.structType === undefined ) {
  31335. const index = this.structs.index ++;
  31336. node.name = `StructType${ index }`;
  31337. this.structs[ shaderStage ].push( node );
  31338. nodeData.structType = node;
  31339. }
  31340. return node;
  31341. }
  31342. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31343. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31344. let nodeUniform = nodeData.uniform;
  31345. if ( nodeUniform === undefined ) {
  31346. const index = this.uniforms.index ++;
  31347. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31348. this.uniforms[ shaderStage ].push( nodeUniform );
  31349. nodeData.uniform = nodeUniform;
  31350. }
  31351. return nodeUniform;
  31352. }
  31353. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  31354. const nodeData = this.getDataFromNode( node, shaderStage );
  31355. let nodeVar = nodeData.variable;
  31356. if ( nodeVar === undefined ) {
  31357. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31358. if ( name === null ) name = 'nodeVar' + vars.length;
  31359. nodeVar = new NodeVar( name, type );
  31360. vars.push( nodeVar );
  31361. nodeData.variable = nodeVar;
  31362. }
  31363. return nodeVar;
  31364. }
  31365. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31366. const nodeData = this.getDataFromNode( node, 'any' );
  31367. let nodeVarying = nodeData.varying;
  31368. if ( nodeVarying === undefined ) {
  31369. const varyings = this.varyings;
  31370. const index = varyings.length;
  31371. if ( name === null ) name = 'nodeVarying' + index;
  31372. nodeVarying = new NodeVarying( name, type );
  31373. varyings.push( nodeVarying );
  31374. nodeData.varying = nodeVarying;
  31375. }
  31376. return nodeVarying;
  31377. }
  31378. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31379. const nodeData = this.getDataFromNode( node );
  31380. let nodeCode = nodeData.code;
  31381. if ( nodeCode === undefined ) {
  31382. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31383. const index = codes.length;
  31384. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31385. codes.push( nodeCode );
  31386. nodeData.code = nodeCode;
  31387. }
  31388. return nodeCode;
  31389. }
  31390. addFlowCodeHierarchy( node, nodeBlock ) {
  31391. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31392. let needsFlowCode = true;
  31393. let nodeBlockHierarchy = nodeBlock;
  31394. while ( nodeBlockHierarchy ) {
  31395. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31396. needsFlowCode = false;
  31397. break;
  31398. }
  31399. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31400. }
  31401. if ( needsFlowCode ) {
  31402. for ( const flowCode of flowCodes ) {
  31403. this.addLineFlowCode( flowCode );
  31404. }
  31405. }
  31406. }
  31407. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31408. const nodeData = this.getDataFromNode( node );
  31409. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31410. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31411. flowCodes.push( code );
  31412. codeBlock.set( nodeBlock, true );
  31413. }
  31414. addLineFlowCode( code, node = null ) {
  31415. if ( code === '' ) return this;
  31416. if ( node !== null && this.context.nodeBlock ) {
  31417. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31418. }
  31419. code = this.tab + code;
  31420. if ( ! /;\s*$/.test( code ) ) {
  31421. code = code + ';\n';
  31422. }
  31423. this.flow.code += code;
  31424. return this;
  31425. }
  31426. addFlowCode( code ) {
  31427. this.flow.code += code;
  31428. return this;
  31429. }
  31430. addFlowTab() {
  31431. this.tab += '\t';
  31432. return this;
  31433. }
  31434. removeFlowTab() {
  31435. this.tab = this.tab.slice( 0, - 1 );
  31436. return this;
  31437. }
  31438. getFlowData( node/*, shaderStage*/ ) {
  31439. return this.flowsData.get( node );
  31440. }
  31441. flowNode( node ) {
  31442. const output = node.getNodeType( this );
  31443. const flowData = this.flowChildNode( node, output );
  31444. this.flowsData.set( node, flowData );
  31445. return flowData;
  31446. }
  31447. buildFunctionNode( shaderNode ) {
  31448. const fn = new FunctionNode();
  31449. const previous = this.currentFunctionNode;
  31450. this.currentFunctionNode = fn;
  31451. fn.code = this.buildFunctionCode( shaderNode );
  31452. this.currentFunctionNode = previous;
  31453. return fn;
  31454. }
  31455. flowShaderNode( shaderNode ) {
  31456. const layout = shaderNode.layout;
  31457. const inputs = {
  31458. [ Symbol.iterator ]() {
  31459. let index = 0;
  31460. const values = Object.values( this );
  31461. return {
  31462. next: () => ( {
  31463. value: values[ index ],
  31464. done: index ++ >= values.length
  31465. } )
  31466. };
  31467. }
  31468. };
  31469. for ( const input of layout.inputs ) {
  31470. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31471. }
  31472. //
  31473. shaderNode.layout = null;
  31474. const callNode = shaderNode.call( inputs );
  31475. const flowData = this.flowStagesNode( callNode, layout.type );
  31476. shaderNode.layout = layout;
  31477. return flowData;
  31478. }
  31479. flowStagesNode( node, output = null ) {
  31480. const previousFlow = this.flow;
  31481. const previousVars = this.vars;
  31482. const previousCache = this.cache;
  31483. const previousBuildStage = this.buildStage;
  31484. const previousStack = this.stack;
  31485. const flow = {
  31486. code: ''
  31487. };
  31488. this.flow = flow;
  31489. this.vars = {};
  31490. this.cache = new NodeCache();
  31491. this.stack = stack();
  31492. for ( const buildStage of defaultBuildStages ) {
  31493. this.setBuildStage( buildStage );
  31494. flow.result = node.build( this, output );
  31495. }
  31496. flow.vars = this.getVars( this.shaderStage );
  31497. this.flow = previousFlow;
  31498. this.vars = previousVars;
  31499. this.cache = previousCache;
  31500. this.stack = previousStack;
  31501. this.setBuildStage( previousBuildStage );
  31502. return flow;
  31503. }
  31504. getFunctionOperator() {
  31505. return null;
  31506. }
  31507. flowChildNode( node, output = null ) {
  31508. const previousFlow = this.flow;
  31509. const flow = {
  31510. code: ''
  31511. };
  31512. this.flow = flow;
  31513. flow.result = node.build( this, output );
  31514. this.flow = previousFlow;
  31515. return flow;
  31516. }
  31517. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31518. const previousShaderStage = this.shaderStage;
  31519. this.setShaderStage( shaderStage );
  31520. const flowData = this.flowChildNode( node, output );
  31521. if ( propertyName !== null ) {
  31522. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31523. }
  31524. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31525. this.setShaderStage( previousShaderStage );
  31526. return flowData;
  31527. }
  31528. getAttributesArray() {
  31529. return this.attributes.concat( this.bufferAttributes );
  31530. }
  31531. getAttributes( /*shaderStage*/ ) {
  31532. console.warn( 'Abstract function.' );
  31533. }
  31534. getVaryings( /*shaderStage*/ ) {
  31535. console.warn( 'Abstract function.' );
  31536. }
  31537. getVar( type, name ) {
  31538. return `${ this.getType( type ) } ${ name }`;
  31539. }
  31540. getVars( shaderStage ) {
  31541. let snippet = '';
  31542. const vars = this.vars[ shaderStage ];
  31543. if ( vars !== undefined ) {
  31544. for ( const variable of vars ) {
  31545. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31546. }
  31547. }
  31548. return snippet;
  31549. }
  31550. getUniforms( /*shaderStage*/ ) {
  31551. console.warn( 'Abstract function.' );
  31552. }
  31553. getCodes( shaderStage ) {
  31554. const codes = this.codes[ shaderStage ];
  31555. let code = '';
  31556. if ( codes !== undefined ) {
  31557. for ( const nodeCode of codes ) {
  31558. code += nodeCode.code + '\n';
  31559. }
  31560. }
  31561. return code;
  31562. }
  31563. getHash() {
  31564. return this.vertexShader + this.fragmentShader + this.computeShader;
  31565. }
  31566. setShaderStage( shaderStage ) {
  31567. this.shaderStage = shaderStage;
  31568. }
  31569. getShaderStage() {
  31570. return this.shaderStage;
  31571. }
  31572. setBuildStage( buildStage ) {
  31573. this.buildStage = buildStage;
  31574. }
  31575. getBuildStage() {
  31576. return this.buildStage;
  31577. }
  31578. buildCode() {
  31579. console.warn( 'Abstract function.' );
  31580. }
  31581. build() {
  31582. const { object, material, renderer } = this;
  31583. if ( material !== null ) {
  31584. let nodeMaterial = renderer.nodes.library.fromMaterial( material );
  31585. if ( nodeMaterial === null ) {
  31586. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31587. nodeMaterial = new NodeMaterial();
  31588. }
  31589. nodeMaterial.build( this );
  31590. } else {
  31591. this.addFlow( 'compute', object );
  31592. }
  31593. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31594. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31595. // generate() -> stage 3: generate shader
  31596. for ( const buildStage of defaultBuildStages ) {
  31597. this.setBuildStage( buildStage );
  31598. if ( this.context.vertex && this.context.vertex.isNode ) {
  31599. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31600. }
  31601. for ( const shaderStage of shaderStages ) {
  31602. this.setShaderStage( shaderStage );
  31603. const flowNodes = this.flowNodes[ shaderStage ];
  31604. for ( const node of flowNodes ) {
  31605. if ( buildStage === 'generate' ) {
  31606. this.flowNode( node );
  31607. } else {
  31608. node.build( this );
  31609. }
  31610. }
  31611. }
  31612. }
  31613. this.setBuildStage( null );
  31614. this.setShaderStage( null );
  31615. // stage 4: build code for a specific output
  31616. this.buildCode();
  31617. this.buildUpdateNodes();
  31618. return this;
  31619. }
  31620. getNodeUniform( uniformNode, type ) {
  31621. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31622. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31623. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31624. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31625. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31626. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31627. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31628. throw new Error( `Uniform "${type}" not declared.` );
  31629. }
  31630. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31631. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31632. }
  31633. format( snippet, fromType, toType ) {
  31634. fromType = this.getVectorType( fromType );
  31635. toType = this.getVectorType( toType );
  31636. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31637. return snippet;
  31638. }
  31639. const fromTypeLength = this.getTypeLength( fromType );
  31640. const toTypeLength = this.getTypeLength( toType );
  31641. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31642. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31643. }
  31644. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31645. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31646. }
  31647. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31648. // @TODO: ignore for now
  31649. return snippet;
  31650. }
  31651. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31652. // @TODO: ignore for now
  31653. return snippet;
  31654. }
  31655. if ( fromTypeLength === toTypeLength ) {
  31656. return `${ this.getType( toType ) }( ${ snippet } )`;
  31657. }
  31658. if ( fromTypeLength > toTypeLength ) {
  31659. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31660. }
  31661. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31662. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31663. }
  31664. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31665. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31666. }
  31667. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31668. // convert a number value to vector type, e.g:
  31669. // vec3( 1u ) -> vec3( float( 1u ) )
  31670. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31671. }
  31672. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31673. }
  31674. getSignature() {
  31675. return `// Three.js r${ REVISION } - Node System\n`;
  31676. }
  31677. }
  31678. class NodeFrame {
  31679. constructor() {
  31680. this.time = 0;
  31681. this.deltaTime = 0;
  31682. this.frameId = 0;
  31683. this.renderId = 0;
  31684. this.startTime = null;
  31685. this.updateMap = new WeakMap();
  31686. this.updateBeforeMap = new WeakMap();
  31687. this.updateAfterMap = new WeakMap();
  31688. this.renderer = null;
  31689. this.material = null;
  31690. this.camera = null;
  31691. this.object = null;
  31692. this.scene = null;
  31693. }
  31694. _getMaps( referenceMap, nodeRef ) {
  31695. let maps = referenceMap.get( nodeRef );
  31696. if ( maps === undefined ) {
  31697. maps = {
  31698. renderMap: new WeakMap(),
  31699. frameMap: new WeakMap()
  31700. };
  31701. referenceMap.set( nodeRef, maps );
  31702. }
  31703. return maps;
  31704. }
  31705. updateBeforeNode( node ) {
  31706. const updateType = node.getUpdateBeforeType();
  31707. const reference = node.updateReference( this );
  31708. if ( updateType === NodeUpdateType.FRAME ) {
  31709. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31710. if ( frameMap.get( reference ) !== this.frameId ) {
  31711. if ( node.updateBefore( this ) !== false ) {
  31712. frameMap.set( reference, this.frameId );
  31713. }
  31714. }
  31715. } else if ( updateType === NodeUpdateType.RENDER ) {
  31716. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31717. if ( renderMap.get( reference ) !== this.renderId ) {
  31718. if ( node.updateBefore( this ) !== false ) {
  31719. renderMap.set( reference, this.renderId );
  31720. }
  31721. }
  31722. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31723. node.updateBefore( this );
  31724. }
  31725. }
  31726. updateAfterNode( node ) {
  31727. const updateType = node.getUpdateAfterType();
  31728. const reference = node.updateReference( this );
  31729. if ( updateType === NodeUpdateType.FRAME ) {
  31730. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31731. if ( frameMap.get( reference ) !== this.frameId ) {
  31732. if ( node.updateAfter( this ) !== false ) {
  31733. frameMap.set( reference, this.frameId );
  31734. }
  31735. }
  31736. } else if ( updateType === NodeUpdateType.RENDER ) {
  31737. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31738. if ( renderMap.get( reference ) !== this.renderId ) {
  31739. if ( node.updateAfter( this ) !== false ) {
  31740. renderMap.set( reference, this.renderId );
  31741. }
  31742. }
  31743. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31744. node.updateAfter( this );
  31745. }
  31746. }
  31747. updateNode( node ) {
  31748. const updateType = node.getUpdateType();
  31749. const reference = node.updateReference( this );
  31750. if ( updateType === NodeUpdateType.FRAME ) {
  31751. const { frameMap } = this._getMaps( this.updateMap, reference );
  31752. if ( frameMap.get( reference ) !== this.frameId ) {
  31753. if ( node.update( this ) !== false ) {
  31754. frameMap.set( reference, this.frameId );
  31755. }
  31756. }
  31757. } else if ( updateType === NodeUpdateType.RENDER ) {
  31758. const { renderMap } = this._getMaps( this.updateMap, reference );
  31759. if ( renderMap.get( reference ) !== this.renderId ) {
  31760. if ( node.update( this ) !== false ) {
  31761. renderMap.set( reference, this.renderId );
  31762. }
  31763. }
  31764. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31765. node.update( this );
  31766. }
  31767. }
  31768. update() {
  31769. this.frameId ++;
  31770. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31771. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31772. this.lastTime = performance.now();
  31773. this.time += this.deltaTime;
  31774. }
  31775. }
  31776. class NodeFunctionInput {
  31777. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31778. this.type = type;
  31779. this.name = name;
  31780. this.count = count;
  31781. this.qualifier = qualifier;
  31782. this.isConst = isConst;
  31783. }
  31784. }
  31785. NodeFunctionInput.isNodeFunctionInput = true;
  31786. class StructTypeNode extends Node {
  31787. static get type() {
  31788. return 'StructTypeNode';
  31789. }
  31790. constructor( types ) {
  31791. super();
  31792. this.types = types;
  31793. this.isStructTypeNode = true;
  31794. }
  31795. getMemberTypes() {
  31796. return this.types;
  31797. }
  31798. }
  31799. class OutputStructNode extends Node {
  31800. static get type() {
  31801. return 'OutputStructNode';
  31802. }
  31803. constructor( ...members ) {
  31804. super();
  31805. this.members = members;
  31806. this.isOutputStructNode = true;
  31807. }
  31808. setup( builder ) {
  31809. super.setup( builder );
  31810. const members = this.members;
  31811. const types = [];
  31812. for ( let i = 0; i < members.length; i ++ ) {
  31813. types.push( members[ i ].getNodeType( builder ) );
  31814. }
  31815. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  31816. }
  31817. generate( builder, output ) {
  31818. const propertyName = builder.getOutputStructName();
  31819. const members = this.members;
  31820. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  31821. for ( let i = 0; i < members.length; i ++ ) {
  31822. const snippet = members[ i ].build( builder, output );
  31823. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  31824. }
  31825. return propertyName;
  31826. }
  31827. }
  31828. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  31829. function getTextureIndex( textures, name ) {
  31830. for ( let i = 0; i < textures.length; i ++ ) {
  31831. if ( textures[ i ].name === name ) {
  31832. return i;
  31833. }
  31834. }
  31835. return - 1;
  31836. }
  31837. class MRTNode extends OutputStructNode {
  31838. static get type() {
  31839. return 'MRTNode';
  31840. }
  31841. constructor( outputNodes ) {
  31842. super();
  31843. this.outputNodes = outputNodes;
  31844. this.isMRTNode = true;
  31845. }
  31846. has( name ) {
  31847. return this.outputNodes[ name ] !== undefined;
  31848. }
  31849. get( name ) {
  31850. return this.outputNodes[ name ];
  31851. }
  31852. merge( mrtNode ) {
  31853. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  31854. return mrt( outputs );
  31855. }
  31856. setup( builder ) {
  31857. const outputNodes = this.outputNodes;
  31858. const mrt = builder.renderer.getRenderTarget();
  31859. const members = [];
  31860. const textures = mrt.textures;
  31861. for ( const name in outputNodes ) {
  31862. const index = getTextureIndex( textures, name );
  31863. members[ index ] = vec4( outputNodes[ name ] );
  31864. }
  31865. this.members = members;
  31866. return super.setup( builder );
  31867. }
  31868. }
  31869. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  31870. class FunctionOverloadingNode extends Node {
  31871. static get type() {
  31872. return 'FunctionOverloadingNode';
  31873. }
  31874. constructor( functionNodes = [], ...parametersNodes ) {
  31875. super();
  31876. this.functionNodes = functionNodes;
  31877. this.parametersNodes = parametersNodes;
  31878. this._candidateFnCall = null;
  31879. this.global = true;
  31880. }
  31881. getNodeType() {
  31882. return this.functionNodes[ 0 ].shaderNode.layout.type;
  31883. }
  31884. setup( builder ) {
  31885. const params = this.parametersNodes;
  31886. let candidateFnCall = this._candidateFnCall;
  31887. if ( candidateFnCall === null ) {
  31888. let candidateFn = null;
  31889. let candidateScore = - 1;
  31890. for ( const functionNode of this.functionNodes ) {
  31891. const shaderNode = functionNode.shaderNode;
  31892. const layout = shaderNode.layout;
  31893. if ( layout === null ) {
  31894. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  31895. }
  31896. const inputs = layout.inputs;
  31897. if ( params.length === inputs.length ) {
  31898. let score = 0;
  31899. for ( let i = 0; i < params.length; i ++ ) {
  31900. const param = params[ i ];
  31901. const input = inputs[ i ];
  31902. if ( param.getNodeType( builder ) === input.type ) {
  31903. score ++;
  31904. } else {
  31905. score = 0;
  31906. }
  31907. }
  31908. if ( score > candidateScore ) {
  31909. candidateFn = functionNode;
  31910. candidateScore = score;
  31911. }
  31912. }
  31913. }
  31914. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  31915. }
  31916. return candidateFnCall;
  31917. }
  31918. }
  31919. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  31920. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  31921. class TimerNode extends UniformNode {
  31922. static get type() {
  31923. return 'TimerNode';
  31924. }
  31925. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  31926. super( value );
  31927. this.scope = scope;
  31928. this.scale = scale;
  31929. this.updateType = NodeUpdateType.FRAME;
  31930. }
  31931. /*
  31932. @TODO:
  31933. getNodeType( builder ) {
  31934. const scope = this.scope;
  31935. if ( scope === TimerNode.FRAME ) {
  31936. return 'uint';
  31937. }
  31938. return 'float';
  31939. }
  31940. */
  31941. update( frame ) {
  31942. const scope = this.scope;
  31943. const scale = this.scale;
  31944. if ( scope === TimerNode.LOCAL ) {
  31945. this.value += frame.deltaTime * scale;
  31946. } else if ( scope === TimerNode.DELTA ) {
  31947. this.value = frame.deltaTime * scale;
  31948. } else if ( scope === TimerNode.FRAME ) {
  31949. this.value = frame.frameId;
  31950. } else {
  31951. // global
  31952. this.value = frame.time * scale;
  31953. }
  31954. }
  31955. serialize( data ) {
  31956. super.serialize( data );
  31957. data.scope = this.scope;
  31958. data.scale = this.scale;
  31959. }
  31960. deserialize( data ) {
  31961. super.deserialize( data );
  31962. this.scope = data.scope;
  31963. this.scale = data.scale;
  31964. }
  31965. }
  31966. TimerNode.LOCAL = 'local';
  31967. TimerNode.GLOBAL = 'global';
  31968. TimerNode.DELTA = 'delta';
  31969. TimerNode.FRAME = 'frame';
  31970. // @TODO: add support to use node in timeScale
  31971. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  31972. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  31973. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  31974. const frameId = /*@__PURE__*/ nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  31975. class OscNode extends Node {
  31976. static get type() {
  31977. return 'OscNode';
  31978. }
  31979. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  31980. super();
  31981. this.method = method;
  31982. this.timeNode = timeNode;
  31983. }
  31984. getNodeType( builder ) {
  31985. return this.timeNode.getNodeType( builder );
  31986. }
  31987. setup() {
  31988. const method = this.method;
  31989. const timeNode = nodeObject( this.timeNode );
  31990. let outputNode = null;
  31991. if ( method === OscNode.SINE ) {
  31992. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  31993. } else if ( method === OscNode.SQUARE ) {
  31994. outputNode = timeNode.fract().round();
  31995. } else if ( method === OscNode.TRIANGLE ) {
  31996. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  31997. } else if ( method === OscNode.SAWTOOTH ) {
  31998. outputNode = timeNode.fract();
  31999. }
  32000. return outputNode;
  32001. }
  32002. serialize( data ) {
  32003. super.serialize( data );
  32004. data.method = this.method;
  32005. }
  32006. deserialize( data ) {
  32007. super.deserialize( data );
  32008. this.method = data.method;
  32009. }
  32010. }
  32011. OscNode.SINE = 'sine';
  32012. OscNode.SQUARE = 'square';
  32013. OscNode.TRIANGLE = 'triangle';
  32014. OscNode.SAWTOOTH = 'sawtooth';
  32015. const oscSine = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SINE );
  32016. const oscSquare = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SQUARE );
  32017. const oscTriangle = /*@__PURE__*/ nodeProxy( OscNode, OscNode.TRIANGLE );
  32018. const oscSawtooth = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SAWTOOTH );
  32019. class SpriteSheetUVNode extends Node {
  32020. static get type() {
  32021. return 'SpriteSheetUVNode';
  32022. }
  32023. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  32024. super( 'vec2' );
  32025. this.countNode = countNode;
  32026. this.uvNode = uvNode;
  32027. this.frameNode = frameNode;
  32028. }
  32029. setup() {
  32030. const { frameNode, uvNode, countNode } = this;
  32031. const { width, height } = countNode;
  32032. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  32033. const column = frameNum.mod( width );
  32034. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  32035. const scale = countNode.reciprocal();
  32036. const uvFrameOffset = vec2( column, row );
  32037. return uvNode.add( uvFrameOffset ).mul( scale );
  32038. }
  32039. }
  32040. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  32041. class StorageArrayElementNode extends ArrayElementNode {
  32042. static get type() {
  32043. return 'StorageArrayElementNode';
  32044. }
  32045. constructor( storageBufferNode, indexNode ) {
  32046. super( storageBufferNode, indexNode );
  32047. this.isStorageArrayElementNode = true;
  32048. }
  32049. set storageBufferNode( value ) {
  32050. this.node = value;
  32051. }
  32052. get storageBufferNode() {
  32053. return this.node;
  32054. }
  32055. setup( builder ) {
  32056. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  32057. if ( this.node.bufferObject === true ) {
  32058. builder.setupPBO( this.node );
  32059. }
  32060. }
  32061. return super.setup( builder );
  32062. }
  32063. generate( builder, output ) {
  32064. let snippet;
  32065. const isAssignContext = builder.context.assign;
  32066. //
  32067. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  32068. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  32069. snippet = builder.generatePBO( this );
  32070. } else {
  32071. snippet = this.node.build( builder );
  32072. }
  32073. } else {
  32074. snippet = super.generate( builder );
  32075. }
  32076. if ( isAssignContext !== true ) {
  32077. const type = this.getNodeType( builder );
  32078. snippet = builder.format( snippet, type, output );
  32079. }
  32080. return snippet;
  32081. }
  32082. }
  32083. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  32084. class TriplanarTexturesNode extends Node {
  32085. static get type() {
  32086. return 'TriplanarTexturesNode';
  32087. }
  32088. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  32089. super( 'vec4' );
  32090. this.textureXNode = textureXNode;
  32091. this.textureYNode = textureYNode;
  32092. this.textureZNode = textureZNode;
  32093. this.scaleNode = scaleNode;
  32094. this.positionNode = positionNode;
  32095. this.normalNode = normalNode;
  32096. }
  32097. setup() {
  32098. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  32099. // Ref: https://github.com/keijiro/StandardTriplanar
  32100. // Blending factor of triplanar mapping
  32101. let bf = normalNode.abs().normalize();
  32102. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  32103. // Triplanar mapping
  32104. const tx = positionNode.yz.mul( scaleNode );
  32105. const ty = positionNode.zx.mul( scaleNode );
  32106. const tz = positionNode.xy.mul( scaleNode );
  32107. // Base color
  32108. const textureX = textureXNode.value;
  32109. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  32110. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  32111. const cx = texture( textureX, tx ).mul( bf.x );
  32112. const cy = texture( textureY, ty ).mul( bf.y );
  32113. const cz = texture( textureZ, tz ).mul( bf.z );
  32114. return add( cx, cy, cz );
  32115. }
  32116. }
  32117. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  32118. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  32119. const _reflectorPlane = new Plane();
  32120. const _normal = new Vector3();
  32121. const _reflectorWorldPosition = new Vector3();
  32122. const _cameraWorldPosition = new Vector3();
  32123. const _rotationMatrix = new Matrix4();
  32124. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  32125. const clipPlane = new Vector4();
  32126. const _view = new Vector3();
  32127. const _target = new Vector3();
  32128. const _q = new Vector4();
  32129. const _size$9 = new Vector2();
  32130. const _defaultRT = new RenderTarget();
  32131. const _defaultUV = screenUV.flipX();
  32132. let _inReflector = false;
  32133. class ReflectorNode extends TextureNode {
  32134. static get type() {
  32135. return 'ReflectorNode';
  32136. }
  32137. constructor( parameters = {} ) {
  32138. super( _defaultRT.texture, _defaultUV );
  32139. const {
  32140. target = new Object3D(),
  32141. resolution = 1,
  32142. generateMipmaps = false,
  32143. bounces = true
  32144. } = parameters;
  32145. //
  32146. this.target = target;
  32147. this.resolution = resolution;
  32148. this.generateMipmaps = generateMipmaps;
  32149. this.bounces = bounces;
  32150. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  32151. this.virtualCameras = new WeakMap();
  32152. this.renderTargets = new WeakMap();
  32153. }
  32154. _updateResolution( renderTarget, renderer ) {
  32155. const resolution = this.resolution;
  32156. renderer.getDrawingBufferSize( _size$9 );
  32157. renderTarget.setSize( Math.round( _size$9.width * resolution ), Math.round( _size$9.height * resolution ) );
  32158. }
  32159. setup( builder ) {
  32160. this._updateResolution( _defaultRT, builder.renderer );
  32161. return super.setup( builder );
  32162. }
  32163. getTextureNode() {
  32164. return this.textureNode;
  32165. }
  32166. getVirtualCamera( camera ) {
  32167. let virtualCamera = this.virtualCameras.get( camera );
  32168. if ( virtualCamera === undefined ) {
  32169. virtualCamera = camera.clone();
  32170. this.virtualCameras.set( camera, virtualCamera );
  32171. }
  32172. return virtualCamera;
  32173. }
  32174. getRenderTarget( camera ) {
  32175. let renderTarget = this.renderTargets.get( camera );
  32176. if ( renderTarget === undefined ) {
  32177. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  32178. if ( this.generateMipmaps === true ) {
  32179. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  32180. renderTarget.texture.generateMipmaps = true;
  32181. }
  32182. this.renderTargets.set( camera, renderTarget );
  32183. }
  32184. return renderTarget;
  32185. }
  32186. updateBefore( frame ) {
  32187. if ( this.bounces === false && _inReflector ) return false;
  32188. _inReflector = true;
  32189. const { scene, camera, renderer, material } = frame;
  32190. const { target } = this;
  32191. const virtualCamera = this.getVirtualCamera( camera );
  32192. const renderTarget = this.getRenderTarget( virtualCamera );
  32193. renderer.getDrawingBufferSize( _size$9 );
  32194. this._updateResolution( renderTarget, renderer );
  32195. //
  32196. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  32197. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  32198. _rotationMatrix.extractRotation( target.matrixWorld );
  32199. _normal.set( 0, 0, 1 );
  32200. _normal.applyMatrix4( _rotationMatrix );
  32201. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  32202. // Avoid rendering when reflector is facing away
  32203. if ( _view.dot( _normal ) > 0 ) return;
  32204. _view.reflect( _normal ).negate();
  32205. _view.add( _reflectorWorldPosition );
  32206. _rotationMatrix.extractRotation( camera.matrixWorld );
  32207. _lookAtPosition.set( 0, 0, - 1 );
  32208. _lookAtPosition.applyMatrix4( _rotationMatrix );
  32209. _lookAtPosition.add( _cameraWorldPosition );
  32210. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  32211. _target.reflect( _normal ).negate();
  32212. _target.add( _reflectorWorldPosition );
  32213. //
  32214. virtualCamera.coordinateSystem = camera.coordinateSystem;
  32215. virtualCamera.position.copy( _view );
  32216. virtualCamera.up.set( 0, 1, 0 );
  32217. virtualCamera.up.applyMatrix4( _rotationMatrix );
  32218. virtualCamera.up.reflect( _normal );
  32219. virtualCamera.lookAt( _target );
  32220. virtualCamera.near = camera.near;
  32221. virtualCamera.far = camera.far;
  32222. virtualCamera.updateMatrixWorld();
  32223. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  32224. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  32225. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  32226. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  32227. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  32228. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  32229. const projectionMatrix = virtualCamera.projectionMatrix;
  32230. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  32231. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  32232. _q.z = - 1.0;
  32233. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  32234. // Calculate the scaled plane vector
  32235. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  32236. const clipBias = 0;
  32237. // Replacing the third row of the projection matrix
  32238. projectionMatrix.elements[ 2 ] = clipPlane.x;
  32239. projectionMatrix.elements[ 6 ] = clipPlane.y;
  32240. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  32241. projectionMatrix.elements[ 14 ] = clipPlane.w;
  32242. //
  32243. this.value = renderTarget.texture;
  32244. material.visible = false;
  32245. const currentRenderTarget = renderer.getRenderTarget();
  32246. const currentMRT = renderer.getMRT();
  32247. renderer.setMRT( null );
  32248. renderer.setRenderTarget( renderTarget );
  32249. renderer.render( scene, virtualCamera );
  32250. renderer.setMRT( currentMRT );
  32251. renderer.setRenderTarget( currentRenderTarget );
  32252. material.visible = true;
  32253. _inReflector = false;
  32254. }
  32255. }
  32256. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  32257. // Helper for passes that need to fill the viewport with a single quad.
  32258. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  32259. // https://github.com/mrdoob/three.js/pull/21358
  32260. class QuadGeometry extends BufferGeometry {
  32261. constructor( flipY = false ) {
  32262. super();
  32263. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  32264. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  32265. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  32266. }
  32267. }
  32268. const _geometry = /*@__PURE__*/ new QuadGeometry();
  32269. class QuadMesh extends Mesh {
  32270. constructor( material = null ) {
  32271. super( _geometry, material );
  32272. this.camera = _camera;
  32273. this.isQuadMesh = true;
  32274. }
  32275. renderAsync( renderer ) {
  32276. return renderer.renderAsync( this, _camera );
  32277. }
  32278. render( renderer ) {
  32279. renderer.render( this, _camera );
  32280. }
  32281. }
  32282. const _size$8 = /*@__PURE__*/ new Vector2();
  32283. class RTTNode extends TextureNode {
  32284. static get type() {
  32285. return 'RTTNode';
  32286. }
  32287. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  32288. const renderTarget = new RenderTarget( width, height, options );
  32289. super( renderTarget.texture, uv() );
  32290. this.node = node;
  32291. this.width = width;
  32292. this.height = height;
  32293. this.renderTarget = renderTarget;
  32294. this.textureNeedsUpdate = true;
  32295. this.autoUpdate = true;
  32296. this.updateMap = new WeakMap();
  32297. this._rttNode = null;
  32298. this._quadMesh = new QuadMesh( new NodeMaterial() );
  32299. this.updateBeforeType = NodeUpdateType.RENDER;
  32300. }
  32301. get autoSize() {
  32302. return this.width === null;
  32303. }
  32304. setup( builder ) {
  32305. this._rttNode = this.node.context( builder.getSharedContext() );
  32306. this._quadMesh.material.name = 'RTT';
  32307. this._quadMesh.material.needsUpdate = true;
  32308. return super.setup( builder );
  32309. }
  32310. setSize( width, height ) {
  32311. this.width = width;
  32312. this.height = height;
  32313. const effectiveWidth = width * this.pixelRatio;
  32314. const effectiveHeight = height * this.pixelRatio;
  32315. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32316. this.textureNeedsUpdate = true;
  32317. }
  32318. setPixelRatio( pixelRatio ) {
  32319. this.pixelRatio = pixelRatio;
  32320. this.setSize( this.width, this.height );
  32321. }
  32322. updateBefore( { renderer } ) {
  32323. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  32324. this.textureNeedsUpdate = false;
  32325. //
  32326. if ( this.autoSize === true ) {
  32327. this.pixelRatio = renderer.getPixelRatio();
  32328. const size = renderer.getSize( _size$8 );
  32329. this.setSize( size.width, size.height );
  32330. }
  32331. //
  32332. this._quadMesh.material.fragmentNode = this._rttNode;
  32333. //
  32334. const currentRenderTarget = renderer.getRenderTarget();
  32335. renderer.setRenderTarget( this.renderTarget );
  32336. this._quadMesh.render( renderer );
  32337. renderer.setRenderTarget( currentRenderTarget );
  32338. }
  32339. clone() {
  32340. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  32341. newNode.sampler = this.sampler;
  32342. newNode.referenceNode = this;
  32343. return newNode;
  32344. }
  32345. }
  32346. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  32347. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  32348. class VertexColorNode extends AttributeNode {
  32349. static get type() {
  32350. return 'VertexColorNode';
  32351. }
  32352. constructor( index = 0 ) {
  32353. super( null, 'vec4' );
  32354. this.isVertexColorNode = true;
  32355. this.index = index;
  32356. }
  32357. getAttributeName( /*builder*/ ) {
  32358. const index = this.index;
  32359. return 'color' + ( index > 0 ? index : '' );
  32360. }
  32361. generate( builder ) {
  32362. const attributeName = this.getAttributeName( builder );
  32363. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  32364. let result;
  32365. if ( geometryAttribute === true ) {
  32366. result = super.generate( builder );
  32367. } else {
  32368. // Vertex color fallback should be white
  32369. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  32370. }
  32371. return result;
  32372. }
  32373. serialize( data ) {
  32374. super.serialize( data );
  32375. data.index = this.index;
  32376. }
  32377. deserialize( data ) {
  32378. super.deserialize( data );
  32379. this.index = data.index;
  32380. }
  32381. }
  32382. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  32383. class PointUVNode extends Node {
  32384. static get type() {
  32385. return 'PointUVNode';
  32386. }
  32387. constructor() {
  32388. super( 'vec2' );
  32389. this.isPointUVNode = true;
  32390. }
  32391. generate( /*builder*/ ) {
  32392. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  32393. }
  32394. }
  32395. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  32396. class SceneNode extends Node {
  32397. static get type() {
  32398. return 'SceneNode';
  32399. }
  32400. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  32401. super();
  32402. this.scope = scope;
  32403. this.scene = scene;
  32404. }
  32405. setup( builder ) {
  32406. const scope = this.scope;
  32407. const scene = this.scene !== null ? this.scene : builder.scene;
  32408. let output;
  32409. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  32410. output = reference( 'backgroundBlurriness', 'float', scene );
  32411. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  32412. output = reference( 'backgroundIntensity', 'float', scene );
  32413. } else {
  32414. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  32415. }
  32416. return output;
  32417. }
  32418. }
  32419. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  32420. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  32421. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  32422. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  32423. const GPUPrimitiveTopology = {
  32424. PointList: 'point-list',
  32425. LineList: 'line-list',
  32426. LineStrip: 'line-strip',
  32427. TriangleList: 'triangle-list',
  32428. TriangleStrip: 'triangle-strip',
  32429. };
  32430. const GPUCompareFunction = {
  32431. Never: 'never',
  32432. Less: 'less',
  32433. Equal: 'equal',
  32434. LessEqual: 'less-equal',
  32435. Greater: 'greater',
  32436. NotEqual: 'not-equal',
  32437. GreaterEqual: 'greater-equal',
  32438. Always: 'always'
  32439. };
  32440. const GPUStoreOp = {
  32441. Store: 'store',
  32442. Discard: 'discard'
  32443. };
  32444. const GPULoadOp = {
  32445. Load: 'load',
  32446. Clear: 'clear'
  32447. };
  32448. const GPUFrontFace = {
  32449. CCW: 'ccw',
  32450. CW: 'cw'
  32451. };
  32452. const GPUCullMode = {
  32453. None: 'none',
  32454. Front: 'front',
  32455. Back: 'back'
  32456. };
  32457. const GPUIndexFormat = {
  32458. Uint16: 'uint16',
  32459. Uint32: 'uint32'
  32460. };
  32461. const GPUTextureFormat = {
  32462. // 8-bit formats
  32463. R8Unorm: 'r8unorm',
  32464. R8Snorm: 'r8snorm',
  32465. R8Uint: 'r8uint',
  32466. R8Sint: 'r8sint',
  32467. // 16-bit formats
  32468. R16Uint: 'r16uint',
  32469. R16Sint: 'r16sint',
  32470. R16Float: 'r16float',
  32471. RG8Unorm: 'rg8unorm',
  32472. RG8Snorm: 'rg8snorm',
  32473. RG8Uint: 'rg8uint',
  32474. RG8Sint: 'rg8sint',
  32475. // 32-bit formats
  32476. R32Uint: 'r32uint',
  32477. R32Sint: 'r32sint',
  32478. R32Float: 'r32float',
  32479. RG16Uint: 'rg16uint',
  32480. RG16Sint: 'rg16sint',
  32481. RG16Float: 'rg16float',
  32482. RGBA8Unorm: 'rgba8unorm',
  32483. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  32484. RGBA8Snorm: 'rgba8snorm',
  32485. RGBA8Uint: 'rgba8uint',
  32486. RGBA8Sint: 'rgba8sint',
  32487. BGRA8Unorm: 'bgra8unorm',
  32488. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  32489. // Packed 32-bit formats
  32490. RGB9E5UFloat: 'rgb9e5ufloat',
  32491. RGB10A2Unorm: 'rgb10a2unorm',
  32492. RG11B10uFloat: 'rgb10a2unorm',
  32493. // 64-bit formats
  32494. RG32Uint: 'rg32uint',
  32495. RG32Sint: 'rg32sint',
  32496. RG32Float: 'rg32float',
  32497. RGBA16Uint: 'rgba16uint',
  32498. RGBA16Sint: 'rgba16sint',
  32499. RGBA16Float: 'rgba16float',
  32500. // 128-bit formats
  32501. RGBA32Uint: 'rgba32uint',
  32502. RGBA32Sint: 'rgba32sint',
  32503. RGBA32Float: 'rgba32float',
  32504. // Depth and stencil formats
  32505. Stencil8: 'stencil8',
  32506. Depth16Unorm: 'depth16unorm',
  32507. Depth24Plus: 'depth24plus',
  32508. Depth24PlusStencil8: 'depth24plus-stencil8',
  32509. Depth32Float: 'depth32float',
  32510. // 'depth32float-stencil8' extension
  32511. Depth32FloatStencil8: 'depth32float-stencil8',
  32512. // BC compressed formats usable if 'texture-compression-bc' is both
  32513. // supported by the device/user agent and enabled in requestDevice.
  32514. BC1RGBAUnorm: 'bc1-rgba-unorm',
  32515. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  32516. BC2RGBAUnorm: 'bc2-rgba-unorm',
  32517. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  32518. BC3RGBAUnorm: 'bc3-rgba-unorm',
  32519. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  32520. BC4RUnorm: 'bc4-r-unorm',
  32521. BC4RSnorm: 'bc4-r-snorm',
  32522. BC5RGUnorm: 'bc5-rg-unorm',
  32523. BC5RGSnorm: 'bc5-rg-snorm',
  32524. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  32525. BC6HRGBFloat: 'bc6h-rgb-float',
  32526. BC7RGBAUnorm: 'bc7-rgba-unorm',
  32527. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  32528. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  32529. // supported by the device/user agent and enabled in requestDevice.
  32530. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  32531. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  32532. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  32533. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  32534. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  32535. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  32536. EACR11Unorm: 'eac-r11unorm',
  32537. EACR11Snorm: 'eac-r11snorm',
  32538. EACRG11Unorm: 'eac-rg11unorm',
  32539. EACRG11Snorm: 'eac-rg11snorm',
  32540. // ASTC compressed formats usable if 'texture-compression-astc' is both
  32541. // supported by the device/user agent and enabled in requestDevice.
  32542. ASTC4x4Unorm: 'astc-4x4-unorm',
  32543. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  32544. ASTC5x4Unorm: 'astc-5x4-unorm',
  32545. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  32546. ASTC5x5Unorm: 'astc-5x5-unorm',
  32547. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  32548. ASTC6x5Unorm: 'astc-6x5-unorm',
  32549. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  32550. ASTC6x6Unorm: 'astc-6x6-unorm',
  32551. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  32552. ASTC8x5Unorm: 'astc-8x5-unorm',
  32553. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  32554. ASTC8x6Unorm: 'astc-8x6-unorm',
  32555. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  32556. ASTC8x8Unorm: 'astc-8x8-unorm',
  32557. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  32558. ASTC10x5Unorm: 'astc-10x5-unorm',
  32559. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  32560. ASTC10x6Unorm: 'astc-10x6-unorm',
  32561. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  32562. ASTC10x8Unorm: 'astc-10x8-unorm',
  32563. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  32564. ASTC10x10Unorm: 'astc-10x10-unorm',
  32565. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  32566. ASTC12x10Unorm: 'astc-12x10-unorm',
  32567. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  32568. ASTC12x12Unorm: 'astc-12x12-unorm',
  32569. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  32570. };
  32571. const GPUAddressMode = {
  32572. ClampToEdge: 'clamp-to-edge',
  32573. Repeat: 'repeat',
  32574. MirrorRepeat: 'mirror-repeat'
  32575. };
  32576. const GPUFilterMode = {
  32577. Linear: 'linear',
  32578. Nearest: 'nearest'
  32579. };
  32580. const GPUBlendFactor = {
  32581. Zero: 'zero',
  32582. One: 'one',
  32583. Src: 'src',
  32584. OneMinusSrc: 'one-minus-src',
  32585. SrcAlpha: 'src-alpha',
  32586. OneMinusSrcAlpha: 'one-minus-src-alpha',
  32587. Dst: 'dst',
  32588. OneMinusDstColor: 'one-minus-dst',
  32589. DstAlpha: 'dst-alpha',
  32590. OneMinusDstAlpha: 'one-minus-dst-alpha',
  32591. SrcAlphaSaturated: 'src-alpha-saturated',
  32592. Constant: 'constant',
  32593. OneMinusConstant: 'one-minus-constant'
  32594. };
  32595. const GPUBlendOperation = {
  32596. Add: 'add',
  32597. Subtract: 'subtract',
  32598. ReverseSubtract: 'reverse-subtract',
  32599. Min: 'min',
  32600. Max: 'max'
  32601. };
  32602. const GPUColorWriteFlags = {
  32603. None: 0,
  32604. Red: 0x1,
  32605. Green: 0x2,
  32606. Blue: 0x4,
  32607. Alpha: 0x8,
  32608. All: 0xF
  32609. };
  32610. const GPUStencilOperation = {
  32611. Keep: 'keep',
  32612. Zero: 'zero',
  32613. Replace: 'replace',
  32614. Invert: 'invert',
  32615. IncrementClamp: 'increment-clamp',
  32616. DecrementClamp: 'decrement-clamp',
  32617. IncrementWrap: 'increment-wrap',
  32618. DecrementWrap: 'decrement-wrap'
  32619. };
  32620. const GPUBufferBindingType = {
  32621. Uniform: 'uniform',
  32622. Storage: 'storage',
  32623. ReadOnlyStorage: 'read-only-storage'
  32624. };
  32625. const GPUStorageTextureAccess = {
  32626. WriteOnly: 'write-only',
  32627. ReadOnly: 'read-only',
  32628. ReadWrite: 'read-write',
  32629. };
  32630. const GPUTextureSampleType = {
  32631. Float: 'float',
  32632. UnfilterableFloat: 'unfilterable-float',
  32633. Depth: 'depth',
  32634. SInt: 'sint',
  32635. UInt: 'uint'
  32636. };
  32637. const GPUTextureDimension = {
  32638. OneD: '1d',
  32639. TwoD: '2d',
  32640. ThreeD: '3d'
  32641. };
  32642. const GPUTextureViewDimension = {
  32643. OneD: '1d',
  32644. TwoD: '2d',
  32645. TwoDArray: '2d-array',
  32646. Cube: 'cube',
  32647. CubeArray: 'cube-array',
  32648. ThreeD: '3d'
  32649. };
  32650. const GPUTextureAspect = {
  32651. All: 'all',
  32652. StencilOnly: 'stencil-only',
  32653. DepthOnly: 'depth-only'
  32654. };
  32655. const GPUInputStepMode = {
  32656. Vertex: 'vertex',
  32657. Instance: 'instance'
  32658. };
  32659. const GPUFeatureName = {
  32660. DepthClipControl: 'depth-clip-control',
  32661. Depth32FloatStencil8: 'depth32float-stencil8',
  32662. TextureCompressionBC: 'texture-compression-bc',
  32663. TextureCompressionETC2: 'texture-compression-etc2',
  32664. TextureCompressionASTC: 'texture-compression-astc',
  32665. TimestampQuery: 'timestamp-query',
  32666. IndirectFirstInstance: 'indirect-first-instance',
  32667. ShaderF16: 'shader-f16',
  32668. RG11B10UFloat: 'rg11b10ufloat-renderable',
  32669. BGRA8UNormStorage: 'bgra8unorm-storage',
  32670. Float32Filterable: 'float32-filterable',
  32671. ClipDistances: 'clip-distances',
  32672. DualSourceBlending: 'dual-source-blending',
  32673. Subgroups: 'subgroups'
  32674. };
  32675. class StorageBufferNode extends BufferNode {
  32676. static get type() {
  32677. return 'StorageBufferNode';
  32678. }
  32679. constructor( value, bufferType, bufferCount = 0 ) {
  32680. super( value, bufferType, bufferCount );
  32681. this.isStorageBufferNode = true;
  32682. this.access = GPUBufferBindingType.Storage;
  32683. this.isAtomic = false;
  32684. this.bufferObject = false;
  32685. this.bufferCount = bufferCount;
  32686. this._attribute = null;
  32687. this._varying = null;
  32688. this.global = true;
  32689. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  32690. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  32691. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  32692. else value.isStorageBufferAttribute = true;
  32693. }
  32694. }
  32695. getHash( builder ) {
  32696. if ( this.bufferCount === 0 ) {
  32697. let bufferData = builder.globalCache.getData( this.value );
  32698. if ( bufferData === undefined ) {
  32699. bufferData = {
  32700. node: this
  32701. };
  32702. builder.globalCache.setData( this.value, bufferData );
  32703. }
  32704. return bufferData.node.uuid;
  32705. }
  32706. return this.uuid;
  32707. }
  32708. getInputType( /*builder*/ ) {
  32709. return 'storageBuffer';
  32710. }
  32711. element( indexNode ) {
  32712. return storageElement( this, indexNode );
  32713. }
  32714. setBufferObject( value ) {
  32715. this.bufferObject = value;
  32716. return this;
  32717. }
  32718. setAccess( value ) {
  32719. this.access = value;
  32720. return this;
  32721. }
  32722. toReadOnly() {
  32723. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  32724. }
  32725. setAtomic( value ) {
  32726. this.isAtomic = value;
  32727. return this;
  32728. }
  32729. toAtomic() {
  32730. return this.setAtomic( true );
  32731. }
  32732. generate( builder ) {
  32733. if ( builder.isAvailable( 'storageBuffer' ) ) {
  32734. return super.generate( builder );
  32735. }
  32736. const nodeType = this.getNodeType( builder );
  32737. if ( this._attribute === null ) {
  32738. this._attribute = bufferAttribute( this.value );
  32739. this._varying = varying( this._attribute );
  32740. }
  32741. const output = this._varying.build( builder, nodeType );
  32742. builder.registerTransform( output, this._attribute );
  32743. return output;
  32744. }
  32745. }
  32746. // Read-Write Storage
  32747. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  32748. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  32749. class StorageTextureNode extends TextureNode {
  32750. static get type() {
  32751. return 'StorageTextureNode';
  32752. }
  32753. constructor( value, uvNode, storeNode = null ) {
  32754. super( value, uvNode );
  32755. this.storeNode = storeNode;
  32756. this.isStorageTextureNode = true;
  32757. this.access = GPUStorageTextureAccess.WriteOnly;
  32758. }
  32759. getInputType( /*builder*/ ) {
  32760. return 'storageTexture';
  32761. }
  32762. setup( builder ) {
  32763. super.setup( builder );
  32764. const properties = builder.getNodeProperties( this );
  32765. properties.storeNode = this.storeNode;
  32766. }
  32767. setAccess( value ) {
  32768. this.access = value;
  32769. return this;
  32770. }
  32771. generate( builder, output ) {
  32772. let snippet;
  32773. if ( this.storeNode !== null ) {
  32774. snippet = this.generateStore( builder );
  32775. } else {
  32776. snippet = super.generate( builder, output );
  32777. }
  32778. return snippet;
  32779. }
  32780. toReadOnly() {
  32781. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  32782. }
  32783. toWriteOnly() {
  32784. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  32785. }
  32786. generateStore( builder ) {
  32787. const properties = builder.getNodeProperties( this );
  32788. const { uvNode, storeNode } = properties;
  32789. const textureProperty = super.generate( builder, 'property' );
  32790. const uvSnippet = uvNode.build( builder, 'uvec2' );
  32791. const storeSnippet = storeNode.build( builder, 'vec4' );
  32792. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  32793. builder.addLineFlowCode( snippet, this );
  32794. }
  32795. }
  32796. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  32797. const textureStore = ( value, uvNode, storeNode ) => {
  32798. const node = storageTexture( value, uvNode, storeNode );
  32799. if ( storeNode !== null ) node.append();
  32800. return node;
  32801. };
  32802. class UserDataNode extends ReferenceNode {
  32803. static get type() {
  32804. return 'UserDataNode';
  32805. }
  32806. constructor( property, inputType, userData = null ) {
  32807. super( property, inputType, userData );
  32808. this.userData = userData;
  32809. }
  32810. updateReference( state ) {
  32811. this.reference = this.userData !== null ? this.userData : state.object.userData;
  32812. return this.reference;
  32813. }
  32814. }
  32815. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  32816. class PosterizeNode extends TempNode {
  32817. static get type() {
  32818. return 'PosterizeNode';
  32819. }
  32820. constructor( sourceNode, stepsNode ) {
  32821. super();
  32822. this.sourceNode = sourceNode;
  32823. this.stepsNode = stepsNode;
  32824. }
  32825. setup() {
  32826. const { sourceNode, stepsNode } = this;
  32827. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  32828. }
  32829. }
  32830. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  32831. let _sharedFramebuffer = null;
  32832. class ViewportSharedTextureNode extends ViewportTextureNode {
  32833. static get type() {
  32834. return 'ViewportSharedTextureNode';
  32835. }
  32836. constructor( uvNode = screenUV, levelNode = null ) {
  32837. if ( _sharedFramebuffer === null ) {
  32838. _sharedFramebuffer = new FramebufferTexture();
  32839. }
  32840. super( uvNode, levelNode, _sharedFramebuffer );
  32841. }
  32842. updateReference() {
  32843. return this;
  32844. }
  32845. }
  32846. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  32847. const _size$7 = /*@__PURE__*/ new Vector2();
  32848. class PassTextureNode extends TextureNode {
  32849. static get type() {
  32850. return 'PassTextureNode';
  32851. }
  32852. constructor( passNode, texture ) {
  32853. super( texture );
  32854. this.passNode = passNode;
  32855. this.setUpdateMatrix( false );
  32856. }
  32857. setup( builder ) {
  32858. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  32859. return super.setup( builder );
  32860. }
  32861. clone() {
  32862. return new this.constructor( this.passNode, this.value );
  32863. }
  32864. }
  32865. class PassMultipleTextureNode extends PassTextureNode {
  32866. static get type() {
  32867. return 'PassMultipleTextureNode';
  32868. }
  32869. constructor( passNode, textureName, previousTexture = false ) {
  32870. super( passNode, null );
  32871. this.textureName = textureName;
  32872. this.previousTexture = previousTexture;
  32873. }
  32874. updateTexture() {
  32875. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  32876. }
  32877. setup( builder ) {
  32878. this.updateTexture();
  32879. return super.setup( builder );
  32880. }
  32881. clone() {
  32882. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  32883. }
  32884. }
  32885. class PassNode extends TempNode {
  32886. static get type() {
  32887. return 'PassNode';
  32888. }
  32889. constructor( scope, scene, camera, options = {} ) {
  32890. super( 'vec4' );
  32891. this.scope = scope;
  32892. this.scene = scene;
  32893. this.camera = camera;
  32894. this.options = options;
  32895. this._pixelRatio = 1;
  32896. this._width = 1;
  32897. this._height = 1;
  32898. const depthTexture = new DepthTexture();
  32899. depthTexture.isRenderTargetTexture = true;
  32900. //depthTexture.type = FloatType;
  32901. depthTexture.name = 'depth';
  32902. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  32903. renderTarget.texture.name = 'output';
  32904. renderTarget.depthTexture = depthTexture;
  32905. this.renderTarget = renderTarget;
  32906. this.updateBeforeType = NodeUpdateType.FRAME;
  32907. this._textures = {
  32908. output: renderTarget.texture,
  32909. depth: depthTexture
  32910. };
  32911. this._textureNodes = {};
  32912. this._linearDepthNodes = {};
  32913. this._viewZNodes = {};
  32914. this._previousTextures = {};
  32915. this._previousTextureNodes = {};
  32916. this._cameraNear = uniform( 0 );
  32917. this._cameraFar = uniform( 0 );
  32918. this._mrt = null;
  32919. this.isPassNode = true;
  32920. }
  32921. setMRT( mrt ) {
  32922. this._mrt = mrt;
  32923. return this;
  32924. }
  32925. getMRT() {
  32926. return this._mrt;
  32927. }
  32928. isGlobal() {
  32929. return true;
  32930. }
  32931. getTexture( name ) {
  32932. let texture = this._textures[ name ];
  32933. if ( texture === undefined ) {
  32934. const refTexture = this.renderTarget.texture;
  32935. texture = refTexture.clone();
  32936. texture.isRenderTargetTexture = true;
  32937. texture.name = name;
  32938. this._textures[ name ] = texture;
  32939. this.renderTarget.textures.push( texture );
  32940. }
  32941. return texture;
  32942. }
  32943. getPreviousTexture( name ) {
  32944. let texture = this._previousTextures[ name ];
  32945. if ( texture === undefined ) {
  32946. texture = this.getTexture( name ).clone();
  32947. texture.isRenderTargetTexture = true;
  32948. this._previousTextures[ name ] = texture;
  32949. }
  32950. return texture;
  32951. }
  32952. toggleTexture( name ) {
  32953. const prevTexture = this._previousTextures[ name ];
  32954. if ( prevTexture !== undefined ) {
  32955. const texture = this._textures[ name ];
  32956. const index = this.renderTarget.textures.indexOf( texture );
  32957. this.renderTarget.textures[ index ] = prevTexture;
  32958. this._textures[ name ] = prevTexture;
  32959. this._previousTextures[ name ] = texture;
  32960. this._textureNodes[ name ].updateTexture();
  32961. this._previousTextureNodes[ name ].updateTexture();
  32962. }
  32963. }
  32964. getTextureNode( name = 'output' ) {
  32965. let textureNode = this._textureNodes[ name ];
  32966. if ( textureNode === undefined ) {
  32967. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  32968. this._textureNodes[ name ].updateTexture();
  32969. }
  32970. return textureNode;
  32971. }
  32972. getPreviousTextureNode( name = 'output' ) {
  32973. let textureNode = this._previousTextureNodes[ name ];
  32974. if ( textureNode === undefined ) {
  32975. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  32976. this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  32977. this._previousTextureNodes[ name ].updateTexture();
  32978. }
  32979. return textureNode;
  32980. }
  32981. getViewZNode( name = 'depth' ) {
  32982. let viewZNode = this._viewZNodes[ name ];
  32983. if ( viewZNode === undefined ) {
  32984. const cameraNear = this._cameraNear;
  32985. const cameraFar = this._cameraFar;
  32986. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  32987. }
  32988. return viewZNode;
  32989. }
  32990. getLinearDepthNode( name = 'depth' ) {
  32991. let linearDepthNode = this._linearDepthNodes[ name ];
  32992. if ( linearDepthNode === undefined ) {
  32993. const cameraNear = this._cameraNear;
  32994. const cameraFar = this._cameraFar;
  32995. const viewZNode = this.getViewZNode( name );
  32996. // TODO: just if ( builder.camera.isPerspectiveCamera )
  32997. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  32998. }
  32999. return linearDepthNode;
  33000. }
  33001. setup( { renderer } ) {
  33002. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  33003. // Disable MSAA for WebGL backend for now
  33004. if ( renderer.backend.isWebGLBackend === true ) {
  33005. this.renderTarget.samples = 0;
  33006. }
  33007. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  33008. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  33009. }
  33010. updateBefore( frame ) {
  33011. const { renderer } = frame;
  33012. const { scene, camera } = this;
  33013. this._pixelRatio = renderer.getPixelRatio();
  33014. const size = renderer.getSize( _size$7 );
  33015. this.setSize( size.width, size.height );
  33016. const currentRenderTarget = renderer.getRenderTarget();
  33017. const currentMRT = renderer.getMRT();
  33018. this._cameraNear.value = camera.near;
  33019. this._cameraFar.value = camera.far;
  33020. for ( const name in this._previousTextures ) {
  33021. this.toggleTexture( name );
  33022. }
  33023. renderer.setRenderTarget( this.renderTarget );
  33024. renderer.setMRT( this._mrt );
  33025. renderer.render( scene, camera );
  33026. renderer.setRenderTarget( currentRenderTarget );
  33027. renderer.setMRT( currentMRT );
  33028. }
  33029. setSize( width, height ) {
  33030. this._width = width;
  33031. this._height = height;
  33032. const effectiveWidth = this._width * this._pixelRatio;
  33033. const effectiveHeight = this._height * this._pixelRatio;
  33034. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  33035. }
  33036. setPixelRatio( pixelRatio ) {
  33037. this._pixelRatio = pixelRatio;
  33038. this.setSize( this._width, this._height );
  33039. }
  33040. dispose() {
  33041. this.renderTarget.dispose();
  33042. }
  33043. }
  33044. PassNode.COLOR = 'color';
  33045. PassNode.DEPTH = 'depth';
  33046. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  33047. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  33048. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  33049. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  33050. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  33051. const _quadMesh1 = /*@__PURE__*/ new QuadMesh();
  33052. const _quadMesh2 = /*@__PURE__*/ new QuadMesh();
  33053. class GaussianBlurNode extends TempNode {
  33054. static get type() {
  33055. return 'GaussianBlurNode';
  33056. }
  33057. constructor( textureNode, directionNode = null, sigma = 2 ) {
  33058. super( 'vec4' );
  33059. this.textureNode = textureNode;
  33060. this.directionNode = directionNode;
  33061. this.sigma = sigma;
  33062. this._invSize = uniform( new Vector2() );
  33063. this._passDirection = uniform( new Vector2() );
  33064. this._horizontalRT = new RenderTarget();
  33065. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  33066. this._verticalRT = new RenderTarget();
  33067. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  33068. this._textureNode = passTexture( this, this._verticalRT.texture );
  33069. this.updateBeforeType = NodeUpdateType.RENDER;
  33070. this.resolution = new Vector2( 1, 1 );
  33071. }
  33072. setSize( width, height ) {
  33073. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  33074. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  33075. this._invSize.value.set( 1 / width, 1 / height );
  33076. this._horizontalRT.setSize( width, height );
  33077. this._verticalRT.setSize( width, height );
  33078. }
  33079. updateBefore( frame ) {
  33080. const { renderer } = frame;
  33081. const textureNode = this.textureNode;
  33082. const map = textureNode.value;
  33083. const currentRenderTarget = renderer.getRenderTarget();
  33084. const currentMRT = renderer.getMRT();
  33085. const currentTexture = textureNode.value;
  33086. _quadMesh1.material = this._material;
  33087. _quadMesh2.material = this._material;
  33088. this.setSize( map.image.width, map.image.height );
  33089. const textureType = map.type;
  33090. this._horizontalRT.texture.type = textureType;
  33091. this._verticalRT.texture.type = textureType;
  33092. // clear
  33093. renderer.setMRT( null );
  33094. // horizontal
  33095. renderer.setRenderTarget( this._horizontalRT );
  33096. this._passDirection.value.set( 1, 0 );
  33097. _quadMesh1.render( renderer );
  33098. // vertical
  33099. textureNode.value = this._horizontalRT.texture;
  33100. renderer.setRenderTarget( this._verticalRT );
  33101. this._passDirection.value.set( 0, 1 );
  33102. _quadMesh2.render( renderer );
  33103. // restore
  33104. renderer.setRenderTarget( currentRenderTarget );
  33105. renderer.setMRT( currentMRT );
  33106. textureNode.value = currentTexture;
  33107. }
  33108. getTextureNode() {
  33109. return this._textureNode;
  33110. }
  33111. setup( builder ) {
  33112. const textureNode = this.textureNode;
  33113. if ( textureNode.isTextureNode !== true ) {
  33114. console.error( 'GaussianBlurNode requires a TextureNode.' );
  33115. return vec4();
  33116. }
  33117. //
  33118. const uvNode = textureNode.uvNode || uv();
  33119. const directionNode = vec2( this.directionNode || 1 );
  33120. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33121. const blur = Fn( () => {
  33122. const kernelSize = 3 + ( 2 * this.sigma );
  33123. const gaussianCoefficients = this._getCoefficients( kernelSize );
  33124. const invSize = this._invSize;
  33125. const direction = directionNode.mul( this._passDirection );
  33126. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  33127. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  33128. for ( let i = 1; i < kernelSize; i ++ ) {
  33129. const x = float( i );
  33130. const w = float( gaussianCoefficients[ i ] );
  33131. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  33132. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  33133. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  33134. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  33135. weightSum.addAssign( mul( 2.0, w ) );
  33136. }
  33137. return diffuseSum.div( weightSum );
  33138. } );
  33139. //
  33140. const material = this._material || ( this._material = new NodeMaterial() );
  33141. material.fragmentNode = blur().context( builder.getSharedContext() );
  33142. material.name = 'Gaussian_blur';
  33143. material.needsUpdate = true;
  33144. //
  33145. const properties = builder.getNodeProperties( this );
  33146. properties.textureNode = textureNode;
  33147. //
  33148. return this._textureNode;
  33149. }
  33150. dispose() {
  33151. this._horizontalRT.dispose();
  33152. this._verticalRT.dispose();
  33153. }
  33154. _getCoefficients( kernelRadius ) {
  33155. const coefficients = [];
  33156. for ( let i = 0; i < kernelRadius; i ++ ) {
  33157. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  33158. }
  33159. return coefficients;
  33160. }
  33161. }
  33162. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma ) );
  33163. const _size$6 = /*@__PURE__*/ new Vector2();
  33164. const _quadMeshComp = /*@__PURE__*/ new QuadMesh();
  33165. class AfterImageNode extends TempNode {
  33166. static get type() {
  33167. return 'AfterImageNode';
  33168. }
  33169. constructor( textureNode, damp = 0.96 ) {
  33170. super( textureNode );
  33171. this.textureNode = textureNode;
  33172. this.textureNodeOld = texture();
  33173. this.damp = uniform( damp );
  33174. this._compRT = new RenderTarget();
  33175. this._compRT.texture.name = 'AfterImageNode.comp';
  33176. this._oldRT = new RenderTarget();
  33177. this._oldRT.texture.name = 'AfterImageNode.old';
  33178. this._textureNode = passTexture( this, this._compRT.texture );
  33179. this.updateBeforeType = NodeUpdateType.RENDER;
  33180. }
  33181. getTextureNode() {
  33182. return this._textureNode;
  33183. }
  33184. setSize( width, height ) {
  33185. this._compRT.setSize( width, height );
  33186. this._oldRT.setSize( width, height );
  33187. }
  33188. updateBefore( frame ) {
  33189. const { renderer } = frame;
  33190. const textureNode = this.textureNode;
  33191. const map = textureNode.value;
  33192. const textureType = map.type;
  33193. this._compRT.texture.type = textureType;
  33194. this._oldRT.texture.type = textureType;
  33195. renderer.getDrawingBufferSize( _size$6 );
  33196. this.setSize( _size$6.x, _size$6.y );
  33197. const currentRenderTarget = renderer.getRenderTarget();
  33198. const currentTexture = textureNode.value;
  33199. this.textureNodeOld.value = this._oldRT.texture;
  33200. // comp
  33201. renderer.setRenderTarget( this._compRT );
  33202. _quadMeshComp.render( renderer );
  33203. // Swap the textures
  33204. const temp = this._oldRT;
  33205. this._oldRT = this._compRT;
  33206. this._compRT = temp;
  33207. renderer.setRenderTarget( currentRenderTarget );
  33208. textureNode.value = currentTexture;
  33209. }
  33210. setup( builder ) {
  33211. const textureNode = this.textureNode;
  33212. const textureNodeOld = this.textureNodeOld;
  33213. //
  33214. const uvNode = textureNode.uvNode || uv();
  33215. textureNodeOld.uvNode = uvNode;
  33216. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33217. const when_gt = Fn( ( [ x_immutable, y_immutable ] ) => {
  33218. const y = float( y_immutable ).toVar();
  33219. const x = vec4( x_immutable ).toVar();
  33220. return max$1( sign( x.sub( y ) ), 0.0 );
  33221. } );
  33222. const afterImg = Fn( () => {
  33223. const texelOld = vec4( textureNodeOld );
  33224. const texelNew = vec4( sampleTexture( uvNode ) );
  33225. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  33226. return max$1( texelNew, texelOld );
  33227. } );
  33228. //
  33229. const materialComposed = this._materialComposed || ( this._materialComposed = new NodeMaterial() );
  33230. materialComposed.name = 'AfterImage';
  33231. materialComposed.fragmentNode = afterImg();
  33232. _quadMeshComp.material = materialComposed;
  33233. //
  33234. const properties = builder.getNodeProperties( this );
  33235. properties.textureNode = textureNode;
  33236. //
  33237. return this._textureNode;
  33238. }
  33239. dispose() {
  33240. this._compRT.dispose();
  33241. this._oldRT.dispose();
  33242. }
  33243. }
  33244. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( convertToTexture( node ), damp ) );
  33245. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  33246. return luminance( color.rgb );
  33247. } );
  33248. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  33249. return adjustment.mix( luminance( color.rgb ), color.rgb );
  33250. } );
  33251. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  33252. const average = add( color.r, color.g, color.b ).div( 3.0 );
  33253. const mx = color.r.max( color.g.max( color.b ) );
  33254. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  33255. return mix( color.rgb, mx, amt );
  33256. } );
  33257. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  33258. const k = vec3( 0.57735, 0.57735, 0.57735 );
  33259. const cosAngle = adjustment.cos();
  33260. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  33261. } );
  33262. const _luminanceCoefficients = /*@__PURE__*/ new Vector3();
  33263. const luminance = (
  33264. color,
  33265. luminanceCoefficients = vec3( ... ColorManagement.getLuminanceCoefficients( _luminanceCoefficients ) )
  33266. ) => dot( color, luminanceCoefficients );
  33267. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  33268. const _quadMesh$5 = /*@__PURE__*/ new QuadMesh();
  33269. class AnamorphicNode extends TempNode {
  33270. static get type() {
  33271. return 'AnamorphicNode';
  33272. }
  33273. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  33274. super( 'vec4' );
  33275. this.textureNode = textureNode;
  33276. this.tresholdNode = tresholdNode;
  33277. this.scaleNode = scaleNode;
  33278. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  33279. this.samples = samples;
  33280. this.resolution = new Vector2( 1, 1 );
  33281. this._renderTarget = new RenderTarget();
  33282. this._renderTarget.texture.name = 'anamorphic';
  33283. this._invSize = uniform( new Vector2() );
  33284. this._textureNode = passTexture( this, this._renderTarget.texture );
  33285. this.updateBeforeType = NodeUpdateType.RENDER;
  33286. }
  33287. getTextureNode() {
  33288. return this._textureNode;
  33289. }
  33290. setSize( width, height ) {
  33291. this._invSize.value.set( 1 / width, 1 / height );
  33292. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  33293. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  33294. this._renderTarget.setSize( width, height );
  33295. }
  33296. updateBefore( frame ) {
  33297. const { renderer } = frame;
  33298. const textureNode = this.textureNode;
  33299. const map = textureNode.value;
  33300. this._renderTarget.texture.type = map.type;
  33301. const currentRenderTarget = renderer.getRenderTarget();
  33302. const currentTexture = textureNode.value;
  33303. _quadMesh$5.material = this._material;
  33304. this.setSize( map.image.width, map.image.height );
  33305. // render
  33306. renderer.setRenderTarget( this._renderTarget );
  33307. _quadMesh$5.render( renderer );
  33308. // restore
  33309. renderer.setRenderTarget( currentRenderTarget );
  33310. textureNode.value = currentTexture;
  33311. }
  33312. setup( builder ) {
  33313. const textureNode = this.textureNode;
  33314. const uvNode = textureNode.uvNode || uv();
  33315. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33316. const anamorph = Fn( () => {
  33317. const samples = this.samples;
  33318. const halfSamples = Math.floor( samples / 2 );
  33319. const total = vec3( 0 ).toVar();
  33320. Loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  33321. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  33322. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  33323. const color = sampleTexture( uv );
  33324. const pass = threshold( color, this.tresholdNode ).mul( softness );
  33325. total.addAssign( pass );
  33326. } );
  33327. return total.mul( this.colorNode );
  33328. } );
  33329. //
  33330. const material = this._material || ( this._material = new NodeMaterial() );
  33331. material.name = 'Anamorphic';
  33332. material.fragmentNode = anamorph();
  33333. //
  33334. const properties = builder.getNodeProperties( this );
  33335. properties.textureNode = textureNode;
  33336. //
  33337. return this._textureNode;
  33338. }
  33339. dispose() {
  33340. this._renderTarget.dispose();
  33341. }
  33342. }
  33343. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( convertToTexture( node ), nodeObject( threshold ), nodeObject( scale ), samples ) );
  33344. class SobelOperatorNode extends TempNode {
  33345. static get type() {
  33346. return 'SobelOperatorNode';
  33347. }
  33348. constructor( textureNode ) {
  33349. super();
  33350. this.textureNode = textureNode;
  33351. this.updateBeforeType = NodeUpdateType.RENDER;
  33352. this._invSize = uniform( new Vector2() );
  33353. }
  33354. updateBefore() {
  33355. const map = this.textureNode.value;
  33356. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  33357. }
  33358. setup() {
  33359. const { textureNode } = this;
  33360. const uvNode = textureNode.uvNode || uv();
  33361. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33362. const sobel = Fn( () => {
  33363. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  33364. const texel = this._invSize;
  33365. // kernel definition (in glsl matrices are filled in column-major order)
  33366. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  33367. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  33368. // fetch the 3x3 neighbourhood of a fragment
  33369. // first column
  33370. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  33371. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  33372. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  33373. // second column
  33374. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  33375. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  33376. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  33377. // third column
  33378. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  33379. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  33380. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  33381. // gradient value in x direction
  33382. const valueGx = add(
  33383. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  33384. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  33385. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  33386. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  33387. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  33388. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  33389. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  33390. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  33391. Gx[ 2 ][ 2 ].mul( tx2y2 )
  33392. );
  33393. // gradient value in y direction
  33394. const valueGy = add(
  33395. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  33396. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  33397. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  33398. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  33399. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  33400. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  33401. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  33402. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  33403. Gy[ 2 ][ 2 ].mul( tx2y2 )
  33404. );
  33405. // magnitute of the total gradient
  33406. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  33407. return vec4( vec3( G ), 1 );
  33408. } );
  33409. const outputNode = sobel();
  33410. return outputNode;
  33411. }
  33412. }
  33413. const sobel = ( node ) => nodeObject( new SobelOperatorNode( convertToTexture( node ) ) );
  33414. class DepthOfFieldNode extends TempNode {
  33415. static get type() {
  33416. return 'DepthOfFieldNode';
  33417. }
  33418. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  33419. super();
  33420. this.textureNode = textureNode;
  33421. this.viewZNode = viewZNode;
  33422. this.focusNode = focusNode;
  33423. this.apertureNode = apertureNode;
  33424. this.maxblurNode = maxblurNode;
  33425. this._aspect = uniform( 0 );
  33426. this.updateBeforeType = NodeUpdateType.RENDER;
  33427. }
  33428. updateBefore() {
  33429. const map = this.textureNode.value;
  33430. this._aspect.value = map.image.width / map.image.height;
  33431. }
  33432. setup() {
  33433. const textureNode = this.textureNode;
  33434. const uvNode = textureNode.uvNode || uv();
  33435. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33436. const dof = Fn( () => {
  33437. const aspectcorrect = vec2( 1.0, this._aspect );
  33438. const factor = this.focusNode.add( this.viewZNode );
  33439. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  33440. const dofblur9 = dofblur.mul( 0.9 );
  33441. const dofblur7 = dofblur.mul( 0.7 );
  33442. const dofblur4 = dofblur.mul( 0.4 );
  33443. let col = vec4( 0.0 );
  33444. col = col.add( sampleTexture( uvNode ) );
  33445. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33446. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33447. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33448. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33449. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33450. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33451. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33452. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33453. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33454. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33455. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33456. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33457. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33458. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33459. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33460. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33461. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33462. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33463. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33464. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33465. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33466. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33467. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33468. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33469. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33470. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33471. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33472. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33473. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33474. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33475. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33476. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33477. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33478. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33479. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33480. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33481. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33482. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33483. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33484. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33485. col = col.div( 41 );
  33486. col.a = 1;
  33487. return vec4( col );
  33488. } );
  33489. const outputNode = dof();
  33490. return outputNode;
  33491. }
  33492. }
  33493. const dof = ( node, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) => nodeObject( new DepthOfFieldNode( convertToTexture( node ), nodeObject( viewZNode ), nodeObject( focus ), nodeObject( aperture ), nodeObject( maxblur ) ) );
  33494. class DotScreenNode extends TempNode {
  33495. static get type() {
  33496. return 'DotScreenNode';
  33497. }
  33498. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  33499. super( 'vec4' );
  33500. this.inputNode = inputNode;
  33501. this.center = uniform( center );
  33502. this.angle = uniform( angle );
  33503. this.scale = uniform( scale );
  33504. }
  33505. setup() {
  33506. const inputNode = this.inputNode;
  33507. const pattern = Fn( () => {
  33508. const s = sin( this.angle );
  33509. const c = cos( this.angle );
  33510. const tex = uv().mul( screenSize ).sub( this.center );
  33511. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  33512. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  33513. } );
  33514. const dotScreen = Fn( () => {
  33515. const color = inputNode;
  33516. const average = add( color.r, color.g, color.b ).div( 3 );
  33517. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  33518. } );
  33519. const outputNode = dotScreen();
  33520. return outputNode;
  33521. }
  33522. }
  33523. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  33524. class RGBShiftNode extends TempNode {
  33525. static get type() {
  33526. return 'RGBShiftNode';
  33527. }
  33528. constructor( textureNode, amount = 0.005, angle = 0 ) {
  33529. super( 'vec4' );
  33530. this.textureNode = textureNode;
  33531. this.amount = uniform( amount );
  33532. this.angle = uniform( angle );
  33533. }
  33534. setup() {
  33535. const { textureNode } = this;
  33536. const uvNode = textureNode.uvNode || uv();
  33537. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33538. const rgbShift = Fn( () => {
  33539. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  33540. const cr = sampleTexture( uvNode.add( offset ) );
  33541. const cga = sampleTexture( uvNode );
  33542. const cb = sampleTexture( uvNode.sub( offset ) );
  33543. return vec4( cr.r, cga.g, cb.b, cga.a );
  33544. } );
  33545. return rgbShift();
  33546. }
  33547. }
  33548. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( convertToTexture( node ), amount, angle ) );
  33549. class FilmNode extends TempNode {
  33550. static get type() {
  33551. return 'FilmNode';
  33552. }
  33553. constructor( inputNode, intensityNode = null, uvNode = null ) {
  33554. super();
  33555. this.inputNode = inputNode;
  33556. this.intensityNode = intensityNode;
  33557. this.uvNode = uvNode;
  33558. }
  33559. setup() {
  33560. const uvNode = this.uvNode || uv();
  33561. const film = Fn( () => {
  33562. const base = this.inputNode.rgb;
  33563. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  33564. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  33565. if ( this.intensityNode !== null ) {
  33566. color = mix( base, color, this.intensityNode );
  33567. }
  33568. return vec4( color, this.inputNode.a );
  33569. } );
  33570. const outputNode = film();
  33571. return outputNode;
  33572. }
  33573. }
  33574. const film = /*@__PURE__*/ nodeProxy( FilmNode );
  33575. class Lut3DNode extends TempNode {
  33576. static get type() {
  33577. return 'Lut3DNode';
  33578. }
  33579. constructor( inputNode, lutNode, size, intensityNode ) {
  33580. super();
  33581. this.inputNode = inputNode;
  33582. this.lutNode = lutNode;
  33583. this.size = uniform( size );
  33584. this.intensityNode = intensityNode;
  33585. }
  33586. setup() {
  33587. const { inputNode, lutNode } = this;
  33588. const sampleLut = ( uv ) => lutNode.uv( uv );
  33589. const lut3D = Fn( () => {
  33590. const base = inputNode;
  33591. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  33592. const pixelWidth = float( 1.0 ).div( this.size );
  33593. const halfPixelWidth = float( 0.5 ).div( this.size );
  33594. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  33595. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  33596. return vec4( mix( base, lutValue, this.intensityNode ) );
  33597. } );
  33598. const outputNode = lut3D();
  33599. return outputNode;
  33600. }
  33601. }
  33602. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  33603. const _quadMesh$4 = /*@__PURE__*/ new QuadMesh();
  33604. const _currentClearColor$1 = /*@__PURE__*/ new Color();
  33605. const _size$5 = /*@__PURE__*/ new Vector2();
  33606. class GTAONode extends TempNode {
  33607. static get type() {
  33608. return 'GTAONode';
  33609. }
  33610. constructor( depthNode, normalNode, camera ) {
  33611. super();
  33612. this.depthNode = depthNode;
  33613. this.normalNode = normalNode;
  33614. this.radius = uniform( 0.25 );
  33615. this.resolution = uniform( new Vector2() );
  33616. this.thickness = uniform( 1 );
  33617. this.distanceExponent = uniform( 1 );
  33618. this.distanceFallOff = uniform( 1 );
  33619. this.scale = uniform( 1 );
  33620. this.noiseNode = texture( generateMagicSquareNoise() );
  33621. this.cameraProjectionMatrix = uniform( camera.projectionMatrix );
  33622. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  33623. this.SAMPLES = uniform( 16 );
  33624. this._aoRenderTarget = new RenderTarget();
  33625. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  33626. this._material = null;
  33627. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  33628. this.updateBeforeType = NodeUpdateType.FRAME;
  33629. }
  33630. getTextureNode() {
  33631. return this._textureNode;
  33632. }
  33633. setSize( width, height ) {
  33634. this.resolution.value.set( width, height );
  33635. this._aoRenderTarget.setSize( width, height );
  33636. }
  33637. updateBefore( frame ) {
  33638. const { renderer } = frame;
  33639. const size = renderer.getDrawingBufferSize( _size$5 );
  33640. const currentRenderTarget = renderer.getRenderTarget();
  33641. const currentMRT = renderer.getMRT();
  33642. renderer.getClearColor( _currentClearColor$1 );
  33643. const currentClearAlpha = renderer.getClearAlpha();
  33644. _quadMesh$4.material = this._material;
  33645. this.setSize( size.width, size.height );
  33646. // clear
  33647. renderer.setMRT( null );
  33648. renderer.setClearColor( 0xffffff, 1 );
  33649. // ao
  33650. renderer.setRenderTarget( this._aoRenderTarget );
  33651. _quadMesh$4.render( renderer );
  33652. // restore
  33653. renderer.setRenderTarget( currentRenderTarget );
  33654. renderer.setMRT( currentMRT );
  33655. renderer.setClearColor( _currentClearColor$1, currentClearAlpha );
  33656. }
  33657. setup( builder ) {
  33658. const uvNode = uv();
  33659. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  33660. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  33661. const getSceneUvAndDepth = Fn( ( [ sampleViewPos ] )=> {
  33662. const sampleClipPos = this.cameraProjectionMatrix.mul( vec4( sampleViewPos, 1.0 ) );
  33663. let sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  33664. sampleUv = vec2( sampleUv.x, sampleUv.y.oneMinus() );
  33665. const sampleSceneDepth = sampleDepth( sampleUv );
  33666. return vec3( sampleUv, sampleSceneDepth );
  33667. } );
  33668. const getViewPosition = Fn( ( [ screenPosition, depth ] ) => {
  33669. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  33670. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  33671. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  33672. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  33673. } );
  33674. const ao = Fn( () => {
  33675. const depth = sampleDepth( uvNode );
  33676. depth.greaterThanEqual( 1.0 ).discard();
  33677. const viewPosition = getViewPosition( uvNode, depth );
  33678. const viewNormal = this.normalNode.rgb.normalize();
  33679. const radiusToUse = this.radius;
  33680. const noiseResolution = textureSize( this.noiseNode, 0 );
  33681. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  33682. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  33683. const noiseTexel = sampleNoise( noiseUv );
  33684. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  33685. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  33686. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  33687. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  33688. const DIRECTIONS = this.SAMPLES.lessThan( 30 ).select( 3, 5 );
  33689. const STEPS = add( this.SAMPLES, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS );
  33690. const ao = float( 0 ).toVar();
  33691. Loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  33692. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI );
  33693. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  33694. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  33695. const viewDir = normalize( viewPosition.xyz.negate() );
  33696. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) );
  33697. const sliceTangent = cross( sliceBitangent, viewDir );
  33698. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  33699. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent );
  33700. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  33701. Loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  33702. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  33703. // x
  33704. const sampleSceneUvDepthX = getSceneUvAndDepth( viewPosition.add( sampleViewOffset ) );
  33705. const sampleSceneViewPositionX = getViewPosition( sampleSceneUvDepthX.xy, sampleSceneUvDepthX.z );
  33706. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition );
  33707. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  33708. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  33709. cosHorizons.x.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  33710. } );
  33711. // y
  33712. const sampleSceneUvDepthY = getSceneUvAndDepth( viewPosition.sub( sampleViewOffset ) );
  33713. const sampleSceneViewPositionY = getViewPosition( sampleSceneUvDepthY.xy, sampleSceneUvDepthY.z );
  33714. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition );
  33715. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  33716. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  33717. cosHorizons.y.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  33718. } );
  33719. } );
  33720. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) );
  33721. const nx = dot( normalInSlice, sliceTangent );
  33722. const ny = dot( normalInSlice, viewDir );
  33723. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  33724. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  33725. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  33726. ao.addAssign( occlusion );
  33727. } );
  33728. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  33729. ao.assign( pow( ao, this.scale ) );
  33730. return vec4( vec3( ao ), 1.0 );
  33731. } );
  33732. const material = this._material || ( this._material = new NodeMaterial() );
  33733. material.fragmentNode = ao().context( builder.getSharedContext() );
  33734. material.name = 'GTAO';
  33735. material.needsUpdate = true;
  33736. //
  33737. return this._textureNode;
  33738. }
  33739. dispose() {
  33740. this._aoRenderTarget.dispose();
  33741. }
  33742. }
  33743. function generateMagicSquareNoise( size = 5 ) {
  33744. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  33745. const magicSquare = generateMagicSquare( noiseSize );
  33746. const noiseSquareSize = magicSquare.length;
  33747. const data = new Uint8Array( noiseSquareSize * 4 );
  33748. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  33749. const iAng = magicSquare[ inx ];
  33750. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  33751. const randomVec = new Vector3(
  33752. Math.cos( angle ),
  33753. Math.sin( angle ),
  33754. 0
  33755. ).normalize();
  33756. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  33757. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  33758. data[ inx * 4 + 2 ] = 127;
  33759. data[ inx * 4 + 3 ] = 255;
  33760. }
  33761. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  33762. noiseTexture.wrapS = RepeatWrapping;
  33763. noiseTexture.wrapT = RepeatWrapping;
  33764. noiseTexture.needsUpdate = true;
  33765. return noiseTexture;
  33766. }
  33767. function generateMagicSquare( size ) {
  33768. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  33769. const noiseSquareSize = noiseSize * noiseSize;
  33770. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  33771. let i = Math.floor( noiseSize / 2 );
  33772. let j = noiseSize - 1;
  33773. for ( let num = 1; num <= noiseSquareSize; ) {
  33774. if ( i === - 1 && j === noiseSize ) {
  33775. j = noiseSize - 2;
  33776. i = 0;
  33777. } else {
  33778. if ( j === noiseSize ) {
  33779. j = 0;
  33780. }
  33781. if ( i < 0 ) {
  33782. i = noiseSize - 1;
  33783. }
  33784. }
  33785. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  33786. j -= 2;
  33787. i ++;
  33788. continue;
  33789. } else {
  33790. magicSquare[ i * noiseSize + j ] = num ++;
  33791. }
  33792. j ++;
  33793. i --;
  33794. }
  33795. return magicSquare;
  33796. }
  33797. const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
  33798. class DenoiseNode extends TempNode {
  33799. static get type() {
  33800. return 'DenoiseNode';
  33801. }
  33802. constructor( textureNode, depthNode, normalNode, noiseNode, camera ) {
  33803. super();
  33804. this.textureNode = textureNode;
  33805. this.depthNode = depthNode;
  33806. this.normalNode = normalNode;
  33807. this.noiseNode = noiseNode;
  33808. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  33809. this.lumaPhi = uniform( 5 );
  33810. this.depthPhi = uniform( 5 );
  33811. this.normalPhi = uniform( 5 );
  33812. this.radius = uniform( 5 );
  33813. this.index = uniform( 0 );
  33814. this._resolution = uniform( new Vector2() );
  33815. this._sampleVectors = uniformArray( generatePdSamplePointInitializer( 16, 2, 1 ) );
  33816. this.updateBeforeType = NodeUpdateType.RENDER;
  33817. }
  33818. updateBefore() {
  33819. const map = this.textureNode.value;
  33820. this._resolution.value.set( map.image.width, map.image.height );
  33821. }
  33822. setup() {
  33823. const uvNode = uv();
  33824. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  33825. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  33826. const sampleNormal = ( uv ) => this.normalNode.uv( uv );
  33827. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  33828. const getViewPosition = Fn( ( [ screenPosition, depth ] ) => {
  33829. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  33830. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  33831. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  33832. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  33833. } );
  33834. const denoiseSample = Fn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  33835. const texel = sampleTexture( sampleUv );
  33836. const depth = sampleDepth( sampleUv );
  33837. const normal = sampleNormal( sampleUv ).rgb.normalize();
  33838. const neighborColor = texel.rgb;
  33839. const viewPos = getViewPosition( sampleUv, depth );
  33840. const normalDiff = dot( viewNormal, normal ).toVar();
  33841. const normalSimilarity = pow( max$1( normalDiff, 0 ), this.normalPhi ).toVar();
  33842. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  33843. const lumaSimilarity = max$1( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  33844. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  33845. const depthSimilarity = max$1( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  33846. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  33847. return vec4( neighborColor.mul( w ), w );
  33848. } );
  33849. const denoise = Fn( ( [ uvNode ] ) => {
  33850. const depth = sampleDepth( uvNode );
  33851. const viewNormal = sampleNormal( uvNode ).rgb.normalize();
  33852. const texel = sampleTexture( uvNode );
  33853. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  33854. return texel;
  33855. } );
  33856. const center = vec3( texel.rgb );
  33857. const viewPosition = getViewPosition( uvNode, depth );
  33858. const noiseResolution = textureSize( this.noiseNode, 0 );
  33859. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  33860. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  33861. const noiseTexel = sampleNoise( noiseUv );
  33862. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  33863. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  33864. const noiseVec = vec2( x, y );
  33865. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y );
  33866. const totalWeight = float( 1.0 ).toVar();
  33867. const denoised = vec3( texel.rgb ).toVar();
  33868. Loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  33869. const sampleDir = this._sampleVectors.element( i ).toVar();
  33870. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
  33871. const sampleUv = uvNode.add( offset ).toVar();
  33872. const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  33873. denoised.addAssign( result.xyz );
  33874. totalWeight.addAssign( result.w );
  33875. } );
  33876. If( totalWeight.greaterThan( float( 0 ) ), () => {
  33877. denoised.divAssign( totalWeight );
  33878. } );
  33879. return vec4( denoised, texel.a );
  33880. } ).setLayout( {
  33881. name: 'denoise',
  33882. type: 'vec4',
  33883. inputs: [
  33884. { name: 'uv', type: 'vec2' }
  33885. ]
  33886. } );
  33887. const output = Fn( () => {
  33888. return denoise( uvNode );
  33889. } );
  33890. const outputNode = output();
  33891. return outputNode;
  33892. }
  33893. }
  33894. function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
  33895. const poissonDisk = generateDenoiseSamples( samples, rings, radiusExponent );
  33896. const array = [];
  33897. for ( let i = 0; i < samples; i ++ ) {
  33898. const sample = poissonDisk[ i ];
  33899. array.push( sample );
  33900. }
  33901. return array;
  33902. }
  33903. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  33904. const samples = [];
  33905. for ( let i = 0; i < numSamples; i ++ ) {
  33906. const angle = 2 * Math.PI * numRings * i / numSamples;
  33907. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  33908. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  33909. }
  33910. return samples;
  33911. }
  33912. const denoise = ( node, depthNode, normalNode, noiseNode, camera ) => nodeObject( new DenoiseNode( convertToTexture( node ), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( noiseNode ), camera ) );
  33913. class FXAANode extends TempNode {
  33914. static get type() {
  33915. return 'FXAANode';
  33916. }
  33917. constructor( textureNode ) {
  33918. super();
  33919. this.textureNode = textureNode;
  33920. this.updateBeforeType = NodeUpdateType.RENDER;
  33921. this._invSize = uniform( new Vector2() );
  33922. }
  33923. updateBefore() {
  33924. const map = this.textureNode.value;
  33925. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  33926. }
  33927. setup() {
  33928. const textureNode = this.textureNode.bias( - 100 );
  33929. const uvNode = textureNode.uvNode || uv();
  33930. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  33931. //----------------------------------------------------------------------------------
  33932. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  33933. // SDK Version: v3.00
  33934. // Email: gameworks@nvidia.com
  33935. // Site: http://developer.nvidia.com/
  33936. //
  33937. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  33938. //
  33939. // Redistribution and use in source and binary forms, with or without
  33940. // modification, are permitted provided that the following conditions
  33941. // are met:
  33942. // * Redistributions of source code must retain the above copyright
  33943. // notice, this list of conditions and the following disclaimer.
  33944. // * Redistributions in binary form must reproduce the above copyright
  33945. // notice, this list of conditions and the following disclaimer in the
  33946. // documentation and/or other materials provided with the distribution.
  33947. // * Neither the name of NVIDIA CORPORATION nor the names of its
  33948. // contributors may be used to endorse or promote products derived
  33949. // from this software without specific prior written permission.
  33950. //
  33951. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  33952. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  33953. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  33954. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  33955. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  33956. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  33957. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  33958. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  33959. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33960. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33961. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33962. //
  33963. //----------------------------------------------------------------------------------
  33964. const FxaaTexTop = ( p ) => textureNode.uv( p );
  33965. const FxaaTexOff = ( p, o, r ) => textureNode.uv( p.add( o.mul( r ) ) );
  33966. const NUM_SAMPLES = int( 5 );
  33967. const contrast = Fn( ( [ a_immutable, b_immutable ] ) => {
  33968. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  33969. const b = vec4( b_immutable ).toVar();
  33970. const a = vec4( a_immutable ).toVar();
  33971. const diff = vec4( abs( a.sub( b ) ) ).toVar();
  33972. return max$1( max$1( max$1( diff.r, diff.g ), diff.b ), diff.a );
  33973. } );
  33974. // FXAA3 QUALITY - PC
  33975. const FxaaPixelShader = Fn( ( [ uv, fxaaQualityRcpFrame, fxaaQualityEdgeThreshold, fxaaQualityinvEdgeThreshold ] ) => {
  33976. const rgbaM = FxaaTexTop( uv ).toVar();
  33977. const rgbaS = FxaaTexOff( uv, vec2( 0.0, - 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33978. const rgbaE = FxaaTexOff( uv, vec2( 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33979. const rgbaN = FxaaTexOff( uv, vec2( 0.0, 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33980. const rgbaW = FxaaTexOff( uv, vec2( - 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33981. // . S .
  33982. // W M E
  33983. // . N .
  33984. const contrastN = contrast( rgbaM, rgbaN ).toVar();
  33985. const contrastS = contrast( rgbaM, rgbaS ).toVar();
  33986. const contrastE = contrast( rgbaM, rgbaE ).toVar();
  33987. const contrastW = contrast( rgbaM, rgbaW ).toVar();
  33988. const maxValue = max$1( contrastN, max$1( contrastS, max$1( contrastE, contrastW ) ) ).toVar();
  33989. // . 0 .
  33990. // 0 0 0
  33991. // . 0 .
  33992. If( maxValue.lessThan( fxaaQualityEdgeThreshold ), () => {
  33993. return rgbaM; // assuming define FXAA_DISCARD is always 0
  33994. } );
  33995. //
  33996. const relativeVContrast = sub( contrastN.add( contrastS ), ( contrastE.add( contrastW ) ) ).toVar();
  33997. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  33998. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  33999. If( abs( relativeVContrast ).lessThan( 0.3 ), () => {
  34000. // locate the edge
  34001. const x = contrastE.greaterThan( contrastW ).select( 1, - 1 ).toVar();
  34002. const y = contrastS.greaterThan( contrastN ).select( 1, - 1 ).toVar();
  34003. const dirToEdge = vec2( x, y ).toVar();
  34004. // . 2 . . 1 .
  34005. // 1 0 2 ~= 0 0 1
  34006. // . 1 . . 0 .
  34007. // tap 2 pixels and see which ones are "outside" the edge, to
  34008. // determine if the edge is vertical or horizontal
  34009. const rgbaAlongH = FxaaTexOff( uv, vec2( dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy );
  34010. const matchAlongH = contrast( rgbaM, rgbaAlongH ).toVar();
  34011. // . 1 .
  34012. // 0 0 1
  34013. // . 0 H
  34014. const rgbaAlongV = FxaaTexOff( uv, vec2( dirToEdge.x.negate(), dirToEdge.y.negate() ), fxaaQualityRcpFrame.xy );
  34015. const matchAlongV = contrast( rgbaM, rgbaAlongV ).toVar();
  34016. // V 1 .
  34017. // 0 0 1
  34018. // . 0 .
  34019. relativeVContrast.assign( matchAlongV.sub( matchAlongH ) );
  34020. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  34021. If( abs( relativeVContrast ).lessThan( 0.3 ), () => { // 45 deg edge
  34022. // 1 1 .
  34023. // 0 0 1
  34024. // . 0 1
  34025. // do a simple blur
  34026. const sum = rgbaN.add( rgbaS ).add( rgbaE ).add( rgbaW );
  34027. return mix( rgbaM, sum.mul( 0.25 ), 0.4 );
  34028. } );
  34029. } );
  34030. const offNP = vec2().toVar();
  34031. If( relativeVContrast.lessThanEqual( 0 ), () => {
  34032. rgbaN.assign( rgbaW );
  34033. rgbaS.assign( rgbaE );
  34034. // . 0 . 1
  34035. // 1 0 1 -> 0
  34036. // . 0 . 1
  34037. offNP.x.assign( 0 );
  34038. offNP.y.assign( fxaaQualityRcpFrame.y );
  34039. } ).Else( () => {
  34040. offNP.x.assign( fxaaQualityRcpFrame.x );
  34041. offNP.y.assign( 0 );
  34042. } );
  34043. const mn = contrast( rgbaM, rgbaN ).toVar();
  34044. const ms = contrast( rgbaM, rgbaS ).toVar();
  34045. If( mn.lessThanEqual( ms ), () => {
  34046. rgbaN.assign( rgbaS );
  34047. } );
  34048. const doneN = int( 0 ).toVar();
  34049. const doneP = int( 0 ).toVar();
  34050. const nDist = float( 0 ).toVar();
  34051. const pDist = float( 0 ).toVar();
  34052. const posN = vec2( uv ).toVar();
  34053. const posP = vec2( uv ).toVar();
  34054. const iterationsUsedN = int( 0 ).toVar();
  34055. const iterationsUsedP = int( 0 ).toVar();
  34056. Loop( NUM_SAMPLES, ( { i } ) => {
  34057. const increment = i.add( 1 ).toVar();
  34058. If( doneN.equal( 0 ), () => {
  34059. nDist.addAssign( increment );
  34060. posN.assign( uv.add( offNP.mul( nDist ) ) );
  34061. const rgbaEndN = FxaaTexTop( posN.xy );
  34062. const nm = contrast( rgbaEndN, rgbaM ).toVar();
  34063. const nn = contrast( rgbaEndN, rgbaN ).toVar();
  34064. If( nm.greaterThan( nn ), () => {
  34065. doneN.assign( 1 );
  34066. } );
  34067. iterationsUsedN.assign( i );
  34068. } );
  34069. If( doneP.equal( 0 ), () => {
  34070. pDist.addAssign( increment );
  34071. posP.assign( uv.sub( offNP.mul( pDist ) ) );
  34072. const rgbaEndP = FxaaTexTop( posP.xy );
  34073. const pm = contrast( rgbaEndP, rgbaM ).toVar();
  34074. const pn = contrast( rgbaEndP, rgbaN ).toVar();
  34075. If( pm.greaterThan( pn ), () => {
  34076. doneP.assign( 1 );
  34077. } );
  34078. iterationsUsedP.assign( i );
  34079. } );
  34080. If( doneN.equal( 1 ).or( doneP.equal( 1 ) ), () => {
  34081. Break();
  34082. } );
  34083. } );
  34084. If( doneN.equal( 0 ).and( doneP.equal( 0 ) ), () => {
  34085. return rgbaM; // failed to find end of edge
  34086. } );
  34087. const distN = float( 1 ).toVar();
  34088. const distP = float( 1 ).toVar();
  34089. If( doneN.equal( 1 ), () => {
  34090. distN.assign( float( iterationsUsedN ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  34091. } );
  34092. If( doneP.equal( 1 ), () => {
  34093. distP.assign( float( iterationsUsedP ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  34094. } );
  34095. const dist = min$1( distN, distP );
  34096. // hacky way of reduces blurriness of mostly diagonal edges
  34097. // but reduces AA quality
  34098. dist.assign( pow( dist, 0.5 ) );
  34099. dist.assign( float( 1 ).sub( dist ) );
  34100. return mix( rgbaM, rgbaN, dist.mul( 0.5 ) );
  34101. } ).setLayout( {
  34102. name: 'FxaaPixelShader',
  34103. type: 'vec4',
  34104. inputs: [
  34105. { name: 'uv', type: 'vec2' },
  34106. { name: 'fxaaQualityRcpFrame', type: 'vec2' },
  34107. { name: 'fxaaQualityEdgeThreshold', type: 'float' },
  34108. { name: 'fxaaQualityinvEdgeThreshold', type: 'float' },
  34109. ]
  34110. } );
  34111. const fxaa = Fn( () => {
  34112. const edgeDetectionQuality = float( 0.2 );
  34113. const invEdgeDetectionQuality = float( 1 ).div( edgeDetectionQuality );
  34114. return FxaaPixelShader( uvNode, this._invSize, edgeDetectionQuality, invEdgeDetectionQuality );
  34115. } );
  34116. const outputNode = fxaa();
  34117. return outputNode;
  34118. }
  34119. }
  34120. const fxaa = ( node ) => nodeObject( new FXAANode( convertToTexture( node ) ) );
  34121. const _quadMesh$3 = /*@__PURE__*/ new QuadMesh();
  34122. const _clearColor$1 = /*@__PURE__*/ new Color( 0, 0, 0 );
  34123. const _currentClearColor = /*@__PURE__*/ new Color();
  34124. const _size$4 = /*@__PURE__*/ new Vector2();
  34125. const _BlurDirectionX = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
  34126. const _BlurDirectionY = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
  34127. class BloomNode extends TempNode {
  34128. static get type() {
  34129. return 'BloomNode';
  34130. }
  34131. constructor( inputNode, strength = 1, radius = 0, threshold = 0 ) {
  34132. super();
  34133. this.inputNode = inputNode;
  34134. this.strength = uniform( strength );
  34135. this.radius = uniform( radius );
  34136. this.threshold = uniform( threshold );
  34137. this.smoothWidth = uniform( 0.01 );
  34138. //
  34139. this._renderTargetsHorizontal = [];
  34140. this._renderTargetsVertical = [];
  34141. this._nMips = 5;
  34142. // render targets
  34143. this._renderTargetBright = new RenderTarget( 1, 1, { type: HalfFloatType } );
  34144. this._renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  34145. this._renderTargetBright.texture.generateMipmaps = false;
  34146. for ( let i = 0; i < this._nMips; i ++ ) {
  34147. const renderTargetHorizontal = new RenderTarget( 1, 1, { type: HalfFloatType } );
  34148. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  34149. renderTargetHorizontal.texture.generateMipmaps = false;
  34150. this._renderTargetsHorizontal.push( renderTargetHorizontal );
  34151. const renderTargetVertical = new RenderTarget( 1, 1, { type: HalfFloatType } );
  34152. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  34153. renderTargetVertical.texture.generateMipmaps = false;
  34154. this._renderTargetsVertical.push( renderTargetVertical );
  34155. }
  34156. // materials
  34157. this._compositeMaterial = null;
  34158. this._highPassFilterMaterial = null;
  34159. this._separableBlurMaterials = [];
  34160. // pass and texture nodes
  34161. this._textureNodeBright = texture( this._renderTargetBright.texture );
  34162. this._textureNodeBlur0 = texture( this._renderTargetsVertical[ 0 ].texture );
  34163. this._textureNodeBlur1 = texture( this._renderTargetsVertical[ 1 ].texture );
  34164. this._textureNodeBlur2 = texture( this._renderTargetsVertical[ 2 ].texture );
  34165. this._textureNodeBlur3 = texture( this._renderTargetsVertical[ 3 ].texture );
  34166. this._textureNodeBlur4 = texture( this._renderTargetsVertical[ 4 ].texture );
  34167. this._textureOutput = passTexture( this, this._renderTargetsHorizontal[ 0 ].texture );
  34168. this.updateBeforeType = NodeUpdateType.FRAME;
  34169. }
  34170. getTextureNode() {
  34171. return this._textureOutput;
  34172. }
  34173. setSize( width, height ) {
  34174. let resx = Math.round( width / 2 );
  34175. let resy = Math.round( height / 2 );
  34176. this._renderTargetBright.setSize( resx, resy );
  34177. for ( let i = 0; i < this._nMips; i ++ ) {
  34178. this._renderTargetsHorizontal[ i ].setSize( resx, resy );
  34179. this._renderTargetsVertical[ i ].setSize( resx, resy );
  34180. this._separableBlurMaterials[ i ].invSize.value.set( 1 / resx, 1 / resy );
  34181. resx = Math.round( resx / 2 );
  34182. resy = Math.round( resy / 2 );
  34183. }
  34184. }
  34185. updateBefore( frame ) {
  34186. const { renderer } = frame;
  34187. const size = renderer.getDrawingBufferSize( _size$4 );
  34188. this.setSize( size.width, size.height );
  34189. const currentRenderTarget = renderer.getRenderTarget();
  34190. const currentMRT = renderer.getMRT();
  34191. renderer.getClearColor( _currentClearColor );
  34192. const currentClearAlpha = renderer.getClearAlpha();
  34193. this.setSize( size.width, size.height );
  34194. renderer.setMRT( null );
  34195. renderer.setClearColor( _clearColor$1, 0 );
  34196. // 1. Extract Bright Areas
  34197. renderer.setRenderTarget( this._renderTargetBright );
  34198. _quadMesh$3.material = this._highPassFilterMaterial;
  34199. _quadMesh$3.render( renderer );
  34200. // 2. Blur All the mips progressively
  34201. let inputRenderTarget = this._renderTargetBright;
  34202. for ( let i = 0; i < this._nMips; i ++ ) {
  34203. _quadMesh$3.material = this._separableBlurMaterials[ i ];
  34204. this._separableBlurMaterials[ i ].colorTexture.value = inputRenderTarget.texture;
  34205. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionX;
  34206. renderer.setRenderTarget( this._renderTargetsHorizontal[ i ] );
  34207. renderer.clear();
  34208. _quadMesh$3.render( renderer );
  34209. this._separableBlurMaterials[ i ].colorTexture.value = this._renderTargetsHorizontal[ i ].texture;
  34210. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionY;
  34211. renderer.setRenderTarget( this._renderTargetsVertical[ i ] );
  34212. renderer.clear();
  34213. _quadMesh$3.render( renderer );
  34214. inputRenderTarget = this._renderTargetsVertical[ i ];
  34215. }
  34216. // 3. Composite All the mips
  34217. renderer.setRenderTarget( this._renderTargetsHorizontal[ 0 ] );
  34218. renderer.clear();
  34219. _quadMesh$3.material = this._compositeMaterial;
  34220. _quadMesh$3.render( renderer );
  34221. // restore
  34222. renderer.setRenderTarget( currentRenderTarget );
  34223. renderer.setMRT( currentMRT );
  34224. renderer.setClearColor( _currentClearColor, currentClearAlpha );
  34225. }
  34226. setup( builder ) {
  34227. // luminosity high pass material
  34228. const luminosityHighPass = Fn( () => {
  34229. const texel = this.inputNode;
  34230. const v = luminance( texel.rgb );
  34231. const alpha = smoothstep( this.threshold, this.threshold.add( this.smoothWidth ), v );
  34232. return mix( vec4( 0 ), texel, alpha );
  34233. } );
  34234. this._highPassFilterMaterial = this._highPassFilterMaterial || new NodeMaterial();
  34235. this._highPassFilterMaterial.fragmentNode = luminosityHighPass().context( builder.getSharedContext() );
  34236. this._highPassFilterMaterial.name = 'Bloom_highPass';
  34237. this._highPassFilterMaterial.needsUpdate = true;
  34238. // gaussian blur materials
  34239. const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
  34240. for ( let i = 0; i < this._nMips; i ++ ) {
  34241. this._separableBlurMaterials.push( this._getSeperableBlurMaterial( builder, kernelSizeArray[ i ] ) );
  34242. }
  34243. // composite material
  34244. const bloomFactors = uniformArray( [ 1.0, 0.8, 0.6, 0.4, 0.2 ] );
  34245. const bloomTintColors = uniformArray( [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ] );
  34246. const lerpBloomFactor = Fn( ( [ factor, radius ] ) => {
  34247. const mirrorFactor = float( 1.2 ).sub( factor );
  34248. return mix( factor, mirrorFactor, radius );
  34249. } ).setLayout( {
  34250. name: 'lerpBloomFactor',
  34251. type: 'float',
  34252. inputs: [
  34253. { name: 'factor', type: 'float' },
  34254. { name: 'radius', type: 'float' },
  34255. ]
  34256. } );
  34257. const compositePass = Fn( () => {
  34258. const color0 = lerpBloomFactor( bloomFactors.element( 0 ), this.radius ).mul( vec4( bloomTintColors.element( 0 ), 1.0 ) ).mul( this._textureNodeBlur0 );
  34259. const color1 = lerpBloomFactor( bloomFactors.element( 1 ), this.radius ).mul( vec4( bloomTintColors.element( 1 ), 1.0 ) ).mul( this._textureNodeBlur1 );
  34260. const color2 = lerpBloomFactor( bloomFactors.element( 2 ), this.radius ).mul( vec4( bloomTintColors.element( 2 ), 1.0 ) ).mul( this._textureNodeBlur2 );
  34261. const color3 = lerpBloomFactor( bloomFactors.element( 3 ), this.radius ).mul( vec4( bloomTintColors.element( 3 ), 1.0 ) ).mul( this._textureNodeBlur3 );
  34262. const color4 = lerpBloomFactor( bloomFactors.element( 4 ), this.radius ).mul( vec4( bloomTintColors.element( 4 ), 1.0 ) ).mul( this._textureNodeBlur4 );
  34263. const sum = color0.add( color1 ).add( color2 ).add( color3 ).add( color4 );
  34264. return sum.mul( this.strength );
  34265. } );
  34266. this._compositeMaterial = this._compositeMaterial || new NodeMaterial();
  34267. this._compositeMaterial.fragmentNode = compositePass().context( builder.getSharedContext() );
  34268. this._compositeMaterial.name = 'Bloom_comp';
  34269. this._compositeMaterial.needsUpdate = true;
  34270. //
  34271. return this._textureOutput;
  34272. }
  34273. dispose() {
  34274. for ( let i = 0; i < this._renderTargetsHorizontal.length; i ++ ) {
  34275. this._renderTargetsHorizontal[ i ].dispose();
  34276. }
  34277. for ( let i = 0; i < this._renderTargetsVertical.length; i ++ ) {
  34278. this._renderTargetsVertical[ i ].dispose();
  34279. }
  34280. this._renderTargetBright.dispose();
  34281. }
  34282. _getSeperableBlurMaterial( builder, kernelRadius ) {
  34283. const coefficients = [];
  34284. for ( let i = 0; i < kernelRadius; i ++ ) {
  34285. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  34286. }
  34287. //
  34288. const colorTexture = texture();
  34289. const gaussianCoefficients = uniformArray( coefficients );
  34290. const invSize = uniform( new Vector2() );
  34291. const direction = uniform( new Vector2( 0.5, 0.5 ) );
  34292. const uvNode = uv();
  34293. const sampleTexel = ( uv ) => colorTexture.uv( uv );
  34294. const seperableBlurPass = Fn( () => {
  34295. const weightSum = gaussianCoefficients.element( 0 ).toVar();
  34296. const diffuseSum = sampleTexel( uvNode ).rgb.mul( weightSum ).toVar();
  34297. Loop( { start: int( 1 ), end: int( kernelRadius ), type: 'int', condition: '<' }, ( { i } ) => {
  34298. const x = float( i );
  34299. const w = gaussianCoefficients.element( i );
  34300. const uvOffset = direction.mul( invSize ).mul( x );
  34301. const sample1 = sampleTexel( uvNode.add( uvOffset ) ).rgb;
  34302. const sample2 = sampleTexel( uvNode.sub( uvOffset ) ).rgb;
  34303. diffuseSum.addAssign( add( sample1, sample2 ).mul( w ) );
  34304. weightSum.addAssign( float( 2.0 ).mul( w ) );
  34305. } );
  34306. return vec4( diffuseSum.div( weightSum ), 1.0 );
  34307. } );
  34308. const seperableBlurMaterial = new NodeMaterial();
  34309. seperableBlurMaterial.fragmentNode = seperableBlurPass().context( builder.getSharedContext() );
  34310. seperableBlurMaterial.name = 'Bloom_seperable';
  34311. seperableBlurMaterial.needsUpdate = true;
  34312. // uniforms
  34313. seperableBlurMaterial.colorTexture = colorTexture;
  34314. seperableBlurMaterial.direction = direction;
  34315. seperableBlurMaterial.invSize = invSize;
  34316. return seperableBlurMaterial;
  34317. }
  34318. }
  34319. const bloom = ( node, strength, radius, threshold ) => nodeObject( new BloomNode( nodeObject( node ), strength, radius, threshold ) );
  34320. class TransitionNode extends TempNode {
  34321. static get type() {
  34322. return 'TransitionNode';
  34323. }
  34324. constructor( textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode ) {
  34325. super();
  34326. // Input textures
  34327. this.textureNodeA = textureNodeA;
  34328. this.textureNodeB = textureNodeB;
  34329. this.mixTextureNode = mixTextureNode;
  34330. // Uniforms
  34331. this.mixRatioNode = mixRatioNode;
  34332. this.thresholdNode = thresholdNode;
  34333. this.useTextureNode = useTextureNode;
  34334. }
  34335. setup() {
  34336. const { textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode } = this;
  34337. const sampleTexture = ( textureNode ) => {
  34338. const uvNodeTexture = textureNode.uvNode || uv();
  34339. return textureNode.uv( uvNodeTexture );
  34340. };
  34341. const transition = Fn( () => {
  34342. const texelOne = sampleTexture( textureNodeA );
  34343. const texelTwo = sampleTexture( textureNodeB );
  34344. const color = vec4().toVar();
  34345. If( useTextureNode.equal( int( 1 ) ), () => {
  34346. const transitionTexel = sampleTexture( mixTextureNode );
  34347. const r = mixRatioNode.mul( thresholdNode.mul( 2.0 ).add( 1.0 ) ).sub( thresholdNode );
  34348. const mixf = clamp( sub( transitionTexel.r, r ).mul( float( 1.0 ).div( thresholdNode ) ), 0.0, 1.0 );
  34349. color.assign( mix( texelOne, texelTwo, mixf ) );
  34350. } ).Else( () => {
  34351. color.assign( mix( texelTwo, texelOne, mixRatioNode ) );
  34352. } );
  34353. return color;
  34354. } );
  34355. const outputNode = transition();
  34356. return outputNode;
  34357. }
  34358. }
  34359. const transition = ( nodeA, nodeB, mixTexture, mixRatio = 0.0, threshold = 0.1, useTexture = 0 ) => nodeObject( new TransitionNode( convertToTexture( nodeA ), convertToTexture( nodeB ), convertToTexture( mixTexture ), nodeObject( mixRatio ), nodeObject( threshold ), nodeObject( useTexture ) ) );
  34360. class PixelationNode extends TempNode {
  34361. static get type() {
  34362. return 'PixelationNode';
  34363. }
  34364. constructor( textureNode, depthNode, normalNode, pixelSize, normalEdgeStrength, depthEdgeStrength ) {
  34365. super();
  34366. // Input textures
  34367. this.textureNode = textureNode;
  34368. this.depthNode = depthNode;
  34369. this.normalNode = normalNode;
  34370. // Input uniforms
  34371. this.pixelSize = pixelSize;
  34372. this.normalEdgeStrength = normalEdgeStrength;
  34373. this.depthEdgeStrength = depthEdgeStrength;
  34374. // Private uniforms
  34375. this._resolution = uniform( new Vector4() );
  34376. this.updateBeforeType = NodeUpdateType.RENDER;
  34377. }
  34378. updateBefore() {
  34379. const map = this.textureNode.value;
  34380. const width = map.image.width;
  34381. const height = map.image.height;
  34382. this._resolution.value.set( width, height, 1 / width, 1 / height );
  34383. }
  34384. setup() {
  34385. const { textureNode, depthNode, normalNode } = this;
  34386. const uvNodeTexture = textureNode.uvNode || uv();
  34387. const uvNodeDepth = depthNode.uvNode || uv();
  34388. const uvNodeNormal = normalNode.uvNode || uv();
  34389. const sampleTexture = () => textureNode.uv( uvNodeTexture );
  34390. const sampleDepth = ( x, y ) => depthNode.uv( uvNodeDepth.add( vec2( x, y ).mul( this._resolution.zw ) ) ).r;
  34391. const sampleNormal = ( x, y ) => normalNode.uv( uvNodeNormal.add( vec2( x, y ).mul( this._resolution.zw ) ) ).rgb.normalize();
  34392. const depthEdgeIndicator = ( depth ) => {
  34393. const diff = property( 'float', 'diff' );
  34394. diff.addAssign( clamp( sampleDepth( 1, 0 ).sub( depth ) ) );
  34395. diff.addAssign( clamp( sampleDepth( - 1, 0 ).sub( depth ) ) );
  34396. diff.addAssign( clamp( sampleDepth( 0, 1 ).sub( depth ) ) );
  34397. diff.addAssign( clamp( sampleDepth( 0, - 1 ).sub( depth ) ) );
  34398. return floor( smoothstep( 0.01, 0.02, diff ).mul( 2 ) ).div( 2 );
  34399. };
  34400. const neighborNormalEdgeIndicator = ( x, y, depth, normal ) => {
  34401. const depthDiff = sampleDepth( x, y ).sub( depth );
  34402. const neighborNormal = sampleNormal( x, y );
  34403. // Edge pixels should yield to faces who's normals are closer to the bias normal.
  34404. const normalEdgeBias = vec3( 1, 1, 1 ); // This should probably be a parameter.
  34405. const normalDiff = dot( normal.sub( neighborNormal ), normalEdgeBias );
  34406. const normalIndicator = clamp( smoothstep( - 0.01, 0.01, normalDiff ), 0.0, 1.0 );
  34407. // Only the shallower pixel should detect the normal edge.
  34408. const depthIndicator = clamp( sign( depthDiff.mul( .25 ).add( .0025 ) ), 0.0, 1.0 );
  34409. return float( 1.0 ).sub( dot( normal, neighborNormal ) ).mul( depthIndicator ).mul( normalIndicator );
  34410. };
  34411. const normalEdgeIndicator = ( depth, normal ) => {
  34412. const indicator = property( 'float', 'indicator' );
  34413. indicator.addAssign( neighborNormalEdgeIndicator( 0, - 1, depth, normal ) );
  34414. indicator.addAssign( neighborNormalEdgeIndicator( 0, 1, depth, normal ) );
  34415. indicator.addAssign( neighborNormalEdgeIndicator( - 1, 0, depth, normal ) );
  34416. indicator.addAssign( neighborNormalEdgeIndicator( 1, 0, depth, normal ) );
  34417. return step( 0.1, indicator );
  34418. };
  34419. const pixelation = Fn( () => {
  34420. const texel = sampleTexture();
  34421. const depth = property( 'float', 'depth' );
  34422. const normal = property( 'vec3', 'normal' );
  34423. If( this.depthEdgeStrength.greaterThan( 0.0 ).or( this.normalEdgeStrength.greaterThan( 0.0 ) ), () => {
  34424. depth.assign( sampleDepth( 0, 0 ) );
  34425. normal.assign( sampleNormal( 0, 0 ) );
  34426. } );
  34427. const dei = property( 'float', 'dei' );
  34428. If( this.depthEdgeStrength.greaterThan( 0.0 ), () => {
  34429. dei.assign( depthEdgeIndicator( depth ) );
  34430. } );
  34431. const nei = property( 'float', 'nei' );
  34432. If( this.normalEdgeStrength.greaterThan( 0.0 ), () => {
  34433. nei.assign( normalEdgeIndicator( depth, normal ) );
  34434. } );
  34435. const strength = dei.greaterThan( 0 ).select( float( 1.0 ).sub( dei.mul( this.depthEdgeStrength ) ), nei.mul( this.normalEdgeStrength ).add( 1 ) );
  34436. return texel.mul( strength );
  34437. } );
  34438. const outputNode = pixelation();
  34439. return outputNode;
  34440. }
  34441. }
  34442. const pixelation = ( node, depthNode, normalNode, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) => nodeObject( new PixelationNode( convertToTexture( node ), convertToTexture( depthNode ), convertToTexture( normalNode ), nodeObject( pixelSize ), nodeObject( normalEdgeStrength ), nodeObject( depthEdgeStrength ) ) );
  34443. class PixelationPassNode extends PassNode {
  34444. static get type() {
  34445. return 'PixelationPassNode';
  34446. }
  34447. constructor( scene, camera, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) {
  34448. super( 'color', scene, camera, { minFilter: NearestFilter, magFilter: NearestFilter } );
  34449. this.pixelSize = pixelSize;
  34450. this.normalEdgeStrength = normalEdgeStrength;
  34451. this.depthEdgeStrength = depthEdgeStrength;
  34452. this.isPixelationPassNode = true;
  34453. this._mrt = mrt( {
  34454. output: output,
  34455. normal: normalView
  34456. } );
  34457. }
  34458. setSize( width, height ) {
  34459. const pixelSize = this.pixelSize.value ? this.pixelSize.value : this.pixelSize;
  34460. const adjustedWidth = Math.floor( width / pixelSize );
  34461. const adjustedHeight = Math.floor( height / pixelSize );
  34462. super.setSize( adjustedWidth, adjustedHeight );
  34463. }
  34464. setup() {
  34465. const color = super.getTextureNode( 'output' );
  34466. const depth = super.getTextureNode( 'depth' );
  34467. const normal = super.getTextureNode( 'normal' );
  34468. return pixelation( color, depth, normal, this.pixelSize, this.normalEdgeStrength, this.depthEdgeStrength );
  34469. }
  34470. }
  34471. const pixelationPass = ( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) => nodeObject( new PixelationPassNode( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) );
  34472. const _size$3 = /*@__PURE__*/ new Vector2();
  34473. /**
  34474. *
  34475. * Supersample Anti-Aliasing Render Pass
  34476. *
  34477. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  34478. *
  34479. * References: https://en.wikipedia.org/wiki/Supersampling
  34480. *
  34481. */
  34482. class SSAAPassNode extends PassNode {
  34483. static get type() {
  34484. return 'SSAAPassNode';
  34485. }
  34486. constructor( scene, camera ) {
  34487. super( PassNode.COLOR, scene, camera );
  34488. this.isSSAAPassNode = true;
  34489. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  34490. this.unbiased = true;
  34491. this.clearColor = new Color( 0x000000 );
  34492. this.clearAlpha = 0;
  34493. this._currentClearColor = new Color();
  34494. this.sampleWeight = uniform( 1 );
  34495. this.sampleRenderTarget = null;
  34496. this._quadMesh = new QuadMesh();
  34497. }
  34498. updateBefore( frame ) {
  34499. const { renderer } = frame;
  34500. const { scene, camera } = this;
  34501. this._pixelRatio = renderer.getPixelRatio();
  34502. const size = renderer.getSize( _size$3 );
  34503. this.setSize( size.width, size.height );
  34504. this.sampleRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
  34505. // save current renderer settings
  34506. renderer.getClearColor( this._currentClearColor );
  34507. const currentClearAlpha = renderer.getClearAlpha();
  34508. const currentRenderTarget = renderer.getRenderTarget();
  34509. const currentMRT = renderer.getMRT();
  34510. const currentAutoClear = renderer.autoClear;
  34511. //
  34512. this._cameraNear.value = camera.near;
  34513. this._cameraFar.value = camera.far;
  34514. renderer.setMRT( this.getMRT() );
  34515. renderer.autoClear = false;
  34516. const jitterOffsets = _JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
  34517. const baseSampleWeight = 1.0 / jitterOffsets.length;
  34518. const roundingRange = 1 / 32;
  34519. const viewOffset = {
  34520. fullWidth: this.renderTarget.width,
  34521. fullHeight: this.renderTarget.height,
  34522. offsetX: 0,
  34523. offsetY: 0,
  34524. width: this.renderTarget.width,
  34525. height: this.renderTarget.height
  34526. };
  34527. const originalViewOffset = Object.assign( {}, camera.view );
  34528. if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );
  34529. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  34530. for ( let i = 0; i < jitterOffsets.length; i ++ ) {
  34531. const jitterOffset = jitterOffsets[ i ];
  34532. if ( camera.setViewOffset ) {
  34533. camera.setViewOffset(
  34534. viewOffset.fullWidth, viewOffset.fullHeight,
  34535. viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
  34536. viewOffset.width, viewOffset.height
  34537. );
  34538. }
  34539. this.sampleWeight.value = baseSampleWeight;
  34540. if ( this.unbiased ) {
  34541. // the theory is that equal weights for each sample lead to an accumulation of rounding errors.
  34542. // The following equation varies the sampleWeight per sample so that it is uniformly distributed
  34543. // across a range of values whose rounding errors cancel each other out.
  34544. const uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
  34545. this.sampleWeight.value += roundingRange * uniformCenteredDistribution;
  34546. }
  34547. renderer.setClearColor( this.clearColor, this.clearAlpha );
  34548. renderer.setRenderTarget( this.sampleRenderTarget );
  34549. renderer.clear();
  34550. renderer.render( scene, camera );
  34551. // accumulation
  34552. renderer.setRenderTarget( this.renderTarget );
  34553. if ( i === 0 ) {
  34554. renderer.setClearColor( 0x000000, 0.0 );
  34555. renderer.clear();
  34556. }
  34557. this._quadMesh.render( renderer );
  34558. }
  34559. renderer.copyTextureToTexture( this.sampleRenderTarget.depthTexture, this.renderTarget.depthTexture );
  34560. // restore
  34561. if ( camera.setViewOffset && originalViewOffset.enabled ) {
  34562. camera.setViewOffset(
  34563. originalViewOffset.fullWidth, originalViewOffset.fullHeight,
  34564. originalViewOffset.offsetX, originalViewOffset.offsetY,
  34565. originalViewOffset.width, originalViewOffset.height
  34566. );
  34567. } else if ( camera.clearViewOffset ) {
  34568. camera.clearViewOffset();
  34569. }
  34570. renderer.setRenderTarget( currentRenderTarget );
  34571. renderer.setMRT( currentMRT );
  34572. renderer.autoClear = currentAutoClear;
  34573. renderer.setClearColor( this._currentClearColor, currentClearAlpha );
  34574. }
  34575. setup( builder ) {
  34576. if ( this.sampleRenderTarget === null ) {
  34577. this.sampleRenderTarget = this.renderTarget.clone();
  34578. }
  34579. let sampleTexture;
  34580. const passMRT = this.getMRT();
  34581. if ( passMRT !== null ) {
  34582. const outputs = {};
  34583. for ( const name in passMRT.outputNodes ) {
  34584. const index = getTextureIndex( this.sampleRenderTarget.textures, name );
  34585. if ( index >= 0 ) {
  34586. outputs[ name ] = texture( this.sampleRenderTarget.textures[ index ] ).mul( this.sampleWeight );
  34587. }
  34588. }
  34589. sampleTexture = mrt( outputs );
  34590. } else {
  34591. sampleTexture = texture( this.sampleRenderTarget.texture ).mul( this.sampleWeight );
  34592. }
  34593. this._quadMesh.material = new NodeMaterial();
  34594. this._quadMesh.material.fragmentNode = sampleTexture;
  34595. this._quadMesh.material.transparent = true;
  34596. this._quadMesh.material.depthTest = false;
  34597. this._quadMesh.material.depthWrite = false;
  34598. this._quadMesh.material.premultipliedAlpha = true;
  34599. this._quadMesh.material.blending = AdditiveBlending;
  34600. this._quadMesh.material.normals = false;
  34601. this._quadMesh.material.name = 'SSAA';
  34602. return super.setup( builder );
  34603. }
  34604. dispose() {
  34605. super.dispose();
  34606. if ( this.sampleRenderTarget !== null ) {
  34607. this.sampleRenderTarget.dispose();
  34608. }
  34609. }
  34610. }
  34611. // These jitter vectors are specified in integers because it is easier.
  34612. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  34613. // before being used, thus these integers need to be scaled by 1/16.
  34614. //
  34615. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  34616. const _JitterVectors = [
  34617. [
  34618. [ 0, 0 ]
  34619. ],
  34620. [
  34621. [ 4, 4 ], [ - 4, - 4 ]
  34622. ],
  34623. [
  34624. [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  34625. ],
  34626. [
  34627. [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
  34628. [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  34629. ],
  34630. [
  34631. [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
  34632. [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
  34633. [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
  34634. [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  34635. ],
  34636. [
  34637. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  34638. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  34639. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  34640. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  34641. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  34642. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  34643. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  34644. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  34645. ]
  34646. ];
  34647. const ssaaPass = ( scene, camera ) => nodeObject( new SSAAPassNode( scene, camera ) );
  34648. const _size$2 = /*@__PURE__*/ new Vector2();
  34649. class StereoPassNode extends PassNode {
  34650. static get type() {
  34651. return 'StereoPassNode';
  34652. }
  34653. constructor( scene, camera ) {
  34654. super( PassNode.COLOR, scene, camera );
  34655. this.isStereoPassNode = true;
  34656. this.stereo = new StereoCamera();
  34657. this.stereo.aspect = 0.5;
  34658. }
  34659. updateBefore( frame ) {
  34660. const { renderer } = frame;
  34661. const { scene, camera, stereo, renderTarget } = this;
  34662. this._pixelRatio = renderer.getPixelRatio();
  34663. stereo.cameraL.coordinateSystem = renderer.coordinateSystem;
  34664. stereo.cameraR.coordinateSystem = renderer.coordinateSystem;
  34665. stereo.update( camera );
  34666. const size = renderer.getSize( _size$2 );
  34667. this.setSize( size.width, size.height );
  34668. const currentAutoClear = renderer.autoClear;
  34669. renderer.autoClear = false;
  34670. const currentRenderTarget = renderer.getRenderTarget();
  34671. const currentMRT = renderer.getMRT();
  34672. this._cameraNear.value = camera.near;
  34673. this._cameraFar.value = camera.far;
  34674. for ( const name in this._previousTextures ) {
  34675. this.toggleTexture( name );
  34676. }
  34677. renderer.setRenderTarget( renderTarget );
  34678. renderer.setMRT( this._mrt );
  34679. renderer.clear();
  34680. renderTarget.scissorTest = true;
  34681. renderTarget.scissor.set( 0, 0, renderTarget.width / 2, renderTarget.height );
  34682. renderTarget.viewport.set( 0, 0, renderTarget.width / 2, renderTarget.height );
  34683. renderer.render( scene, stereo.cameraL );
  34684. renderTarget.scissor.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
  34685. renderTarget.viewport.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
  34686. renderer.render( scene, stereo.cameraR );
  34687. renderTarget.scissorTest = false;
  34688. renderer.setRenderTarget( currentRenderTarget );
  34689. renderer.setMRT( currentMRT );
  34690. renderer.autoClear = currentAutoClear;
  34691. }
  34692. }
  34693. const stereoPass = ( scene, camera ) => nodeObject( new StereoPassNode( scene, camera ) );
  34694. const _size$1 = /*@__PURE__*/ new Vector2();
  34695. const _quadMesh$2 = /*@__PURE__*/ new QuadMesh();
  34696. class StereoCompositePassNode extends PassNode {
  34697. static get type() {
  34698. return 'StereoCompositePassNode';
  34699. }
  34700. constructor( scene, camera ) {
  34701. super( PassNode.COLOR, scene, camera );
  34702. this.isStereoCompositePassNode = true;
  34703. this.stereo = new StereoCamera();
  34704. const _params = { minFilter: LinearFilter, magFilter: NearestFilter, type: HalfFloatType };
  34705. this._renderTargetL = new RenderTarget( 1, 1, _params );
  34706. this._renderTargetR = new RenderTarget( 1, 1, _params );
  34707. this._mapLeft = texture( this._renderTargetL.texture );
  34708. this._mapRight = texture( this._renderTargetR.texture );
  34709. this._material = null;
  34710. }
  34711. updateStereoCamera( coordinateSystem ) {
  34712. this.stereo.cameraL.coordinateSystem = coordinateSystem;
  34713. this.stereo.cameraR.coordinateSystem = coordinateSystem;
  34714. this.stereo.update( this.camera );
  34715. }
  34716. setSize( width, height ) {
  34717. super.setSize( width, height );
  34718. this._renderTargetL.setSize( this.renderTarget.width, this.renderTarget.height );
  34719. this._renderTargetR.setSize( this.renderTarget.width, this.renderTarget.height );
  34720. }
  34721. updateBefore( frame ) {
  34722. const { renderer } = frame;
  34723. const { scene, stereo, renderTarget } = this;
  34724. this._pixelRatio = renderer.getPixelRatio();
  34725. this.updateStereoCamera( renderer.coordinateSystem );
  34726. const size = renderer.getSize( _size$1 );
  34727. this.setSize( size.width, size.height );
  34728. const currentRenderTarget = renderer.getRenderTarget();
  34729. // left
  34730. renderer.setRenderTarget( this._renderTargetL );
  34731. renderer.render( scene, stereo.cameraL );
  34732. // right
  34733. renderer.setRenderTarget( this._renderTargetR );
  34734. renderer.render( scene, stereo.cameraR );
  34735. // composite
  34736. renderer.setRenderTarget( renderTarget );
  34737. _quadMesh$2.material = this._material;
  34738. _quadMesh$2.render( renderer );
  34739. // restore
  34740. renderer.setRenderTarget( currentRenderTarget );
  34741. }
  34742. dispose() {
  34743. super.dispose();
  34744. this._renderTargetL.dispose();
  34745. this._renderTargetR.dispose();
  34746. if ( this._material !== null ) {
  34747. this._material.dispose();
  34748. }
  34749. }
  34750. }
  34751. class AnaglyphPassNode extends StereoCompositePassNode {
  34752. static get type() {
  34753. return 'AnaglyphPassNode';
  34754. }
  34755. constructor( scene, camera ) {
  34756. super( scene, camera );
  34757. this.isAnaglyphPassNode = true;
  34758. // Dubois matrices from https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.7.6968&rep=rep1&type=pdf#page=4
  34759. this._colorMatrixLeft = uniform( new Matrix3().fromArray( [
  34760. 0.456100, - 0.0400822, - 0.0152161,
  34761. 0.500484, - 0.0378246, - 0.0205971,
  34762. 0.176381, - 0.0157589, - 0.00546856
  34763. ] ) );
  34764. this._colorMatrixRight = uniform( new Matrix3().fromArray( [
  34765. - 0.0434706, 0.378476, - 0.0721527,
  34766. - 0.0879388, 0.73364, - 0.112961,
  34767. - 0.00155529, - 0.0184503, 1.2264
  34768. ] ) );
  34769. }
  34770. setup( builder ) {
  34771. const uvNode = uv();
  34772. const anaglyph = Fn( () => {
  34773. const colorL = this._mapLeft.uv( uvNode );
  34774. const colorR = this._mapRight.uv( uvNode );
  34775. const color = clamp( this._colorMatrixLeft.mul( colorL.rgb ).add( this._colorMatrixRight.mul( colorR.rgb ) ) );
  34776. return vec4( color.rgb, max$1( colorL.a, colorR.a ) );
  34777. } );
  34778. const material = this._material || ( this._material = new NodeMaterial() );
  34779. material.fragmentNode = anaglyph().context( builder.getSharedContext() );
  34780. material.name = 'Anaglyph';
  34781. material.needsUpdate = true;
  34782. return super.setup( builder );
  34783. }
  34784. }
  34785. const anaglyphPass = ( scene, camera ) => nodeObject( new AnaglyphPassNode( scene, camera ) );
  34786. class ParallaxBarrierPassNode extends StereoCompositePassNode {
  34787. static get type() {
  34788. return 'ParallaxBarrierPassNode';
  34789. }
  34790. constructor( scene, camera ) {
  34791. super( scene, camera );
  34792. this.isParallaxBarrierPassNode = true;
  34793. }
  34794. setup( builder ) {
  34795. const uvNode = uv();
  34796. const parallaxBarrier = Fn( () => {
  34797. const color = vec4().toVar();
  34798. If( mod( screenCoordinate.y, 2 ).greaterThan( 1 ), () => {
  34799. color.assign( this._mapLeft.uv( uvNode ) );
  34800. } ).Else( () => {
  34801. color.assign( this._mapRight.uv( uvNode ) );
  34802. } );
  34803. return color;
  34804. } );
  34805. const material = this._material || ( this._material = new NodeMaterial() );
  34806. material.fragmentNode = parallaxBarrier().context( builder.getSharedContext() );
  34807. material.needsUpdate = true;
  34808. return super.setup( builder );
  34809. }
  34810. }
  34811. const parallaxBarrierPass = ( scene, camera ) => nodeObject( new ParallaxBarrierPassNode( scene, camera ) );
  34812. class ToonOutlinePassNode extends PassNode {
  34813. static get type() {
  34814. return 'ToonOutlinePassNode';
  34815. }
  34816. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  34817. super( PassNode.COLOR, scene, camera );
  34818. this.colorNode = colorNode;
  34819. this.thicknessNode = thicknessNode;
  34820. this.alphaNode = alphaNode;
  34821. this._materialCache = new WeakMap();
  34822. }
  34823. updateBefore( frame ) {
  34824. const { renderer } = frame;
  34825. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  34826. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => {
  34827. // only render outline for supported materials
  34828. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  34829. if ( material.wireframe === false ) {
  34830. const outlineMaterial = this._getOutlineMaterial( material );
  34831. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode );
  34832. }
  34833. }
  34834. // default
  34835. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode );
  34836. } );
  34837. super.updateBefore( frame );
  34838. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  34839. }
  34840. _createMaterial() {
  34841. const material = new NodeMaterial();
  34842. material.isMeshToonOutlineMaterial = true;
  34843. material.name = 'Toon_Outline';
  34844. material.side = BackSide;
  34845. // vertex node
  34846. const outlineNormal = normalLocal.negate();
  34847. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  34848. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  34849. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  34850. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  34851. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  34852. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  34853. // color node
  34854. material.colorNode = vec4( this.colorNode, this.alphaNode );
  34855. return material;
  34856. }
  34857. _getOutlineMaterial( originalMaterial ) {
  34858. let outlineMaterial = this._materialCache.get( originalMaterial );
  34859. if ( outlineMaterial === undefined ) {
  34860. outlineMaterial = this._createMaterial();
  34861. this._materialCache.set( originalMaterial, outlineMaterial );
  34862. }
  34863. return outlineMaterial;
  34864. }
  34865. }
  34866. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  34867. class ScriptableValueNode extends Node {
  34868. static get type() {
  34869. return 'ScriptableValueNode';
  34870. }
  34871. constructor( value = null ) {
  34872. super();
  34873. this._value = value;
  34874. this._cache = null;
  34875. this.inputType = null;
  34876. this.outpuType = null;
  34877. this.events = new EventDispatcher();
  34878. this.isScriptableValueNode = true;
  34879. }
  34880. get isScriptableOutputNode() {
  34881. return this.outputType !== null;
  34882. }
  34883. set value( val ) {
  34884. if ( this._value === val ) return;
  34885. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  34886. URL.revokeObjectURL( this._cache );
  34887. this._cache = null;
  34888. }
  34889. this._value = val;
  34890. this.events.dispatchEvent( { type: 'change' } );
  34891. this.refresh();
  34892. }
  34893. get value() {
  34894. return this._value;
  34895. }
  34896. refresh() {
  34897. this.events.dispatchEvent( { type: 'refresh' } );
  34898. }
  34899. getValue() {
  34900. const value = this.value;
  34901. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  34902. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  34903. } else if ( value && value.value !== null && value.value !== undefined && (
  34904. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  34905. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  34906. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  34907. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  34908. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  34909. ( this.inputType === 'Color' && value.value.isColor ) ||
  34910. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  34911. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  34912. ) ) {
  34913. return value.value;
  34914. }
  34915. return this._cache || value;
  34916. }
  34917. getNodeType( builder ) {
  34918. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  34919. }
  34920. setup() {
  34921. return this.value && this.value.isNode ? this.value : float();
  34922. }
  34923. serialize( data ) {
  34924. super.serialize( data );
  34925. if ( this.value !== null ) {
  34926. if ( this.inputType === 'ArrayBuffer' ) {
  34927. data.value = arrayBufferToBase64( this.value );
  34928. } else {
  34929. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  34930. }
  34931. } else {
  34932. data.value = null;
  34933. }
  34934. data.inputType = this.inputType;
  34935. data.outputType = this.outputType;
  34936. }
  34937. deserialize( data ) {
  34938. super.deserialize( data );
  34939. let value = null;
  34940. if ( data.value !== null ) {
  34941. if ( data.inputType === 'ArrayBuffer' ) {
  34942. value = base64ToArrayBuffer( data.value );
  34943. } else if ( data.inputType === 'Texture' ) {
  34944. value = data.meta.textures[ data.value ];
  34945. } else {
  34946. value = data.meta.nodes[ data.value ] || null;
  34947. }
  34948. }
  34949. this.value = value;
  34950. this.inputType = data.inputType;
  34951. this.outputType = data.outputType;
  34952. }
  34953. }
  34954. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  34955. class Resources extends Map {
  34956. get( key, callback = null, ...params ) {
  34957. if ( this.has( key ) ) return super.get( key );
  34958. if ( callback !== null ) {
  34959. const value = callback( ...params );
  34960. this.set( key, value );
  34961. return value;
  34962. }
  34963. }
  34964. }
  34965. class Parameters {
  34966. constructor( scriptableNode ) {
  34967. this.scriptableNode = scriptableNode;
  34968. }
  34969. get parameters() {
  34970. return this.scriptableNode.parameters;
  34971. }
  34972. get layout() {
  34973. return this.scriptableNode.getLayout();
  34974. }
  34975. getInputLayout( id ) {
  34976. return this.scriptableNode.getInputLayout( id );
  34977. }
  34978. get( name ) {
  34979. const param = this.parameters[ name ];
  34980. const value = param ? param.getValue() : null;
  34981. return value;
  34982. }
  34983. }
  34984. const global = new Resources();
  34985. class ScriptableNode extends Node {
  34986. static get type() {
  34987. return 'ScriptableNode';
  34988. }
  34989. constructor( codeNode = null, parameters = {} ) {
  34990. super();
  34991. this.codeNode = codeNode;
  34992. this.parameters = parameters;
  34993. this._local = new Resources();
  34994. this._output = scriptableValue();
  34995. this._outputs = {};
  34996. this._source = this.source;
  34997. this._method = null;
  34998. this._object = null;
  34999. this._value = null;
  35000. this._needsOutputUpdate = true;
  35001. this.onRefresh = this.onRefresh.bind( this );
  35002. this.isScriptableNode = true;
  35003. }
  35004. get source() {
  35005. return this.codeNode ? this.codeNode.code : '';
  35006. }
  35007. setLocal( name, value ) {
  35008. return this._local.set( name, value );
  35009. }
  35010. getLocal( name ) {
  35011. return this._local.get( name );
  35012. }
  35013. onRefresh() {
  35014. this._refresh();
  35015. }
  35016. getInputLayout( id ) {
  35017. for ( const element of this.getLayout() ) {
  35018. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  35019. return element;
  35020. }
  35021. }
  35022. }
  35023. getOutputLayout( id ) {
  35024. for ( const element of this.getLayout() ) {
  35025. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  35026. return element;
  35027. }
  35028. }
  35029. }
  35030. setOutput( name, value ) {
  35031. const outputs = this._outputs;
  35032. if ( outputs[ name ] === undefined ) {
  35033. outputs[ name ] = scriptableValue( value );
  35034. } else {
  35035. outputs[ name ].value = value;
  35036. }
  35037. return this;
  35038. }
  35039. getOutput( name ) {
  35040. return this._outputs[ name ];
  35041. }
  35042. getParameter( name ) {
  35043. return this.parameters[ name ];
  35044. }
  35045. setParameter( name, value ) {
  35046. const parameters = this.parameters;
  35047. if ( value && value.isScriptableNode ) {
  35048. this.deleteParameter( name );
  35049. parameters[ name ] = value;
  35050. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  35051. } else if ( value && value.isScriptableValueNode ) {
  35052. this.deleteParameter( name );
  35053. parameters[ name ] = value;
  35054. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  35055. } else if ( parameters[ name ] === undefined ) {
  35056. parameters[ name ] = scriptableValue( value );
  35057. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  35058. } else {
  35059. parameters[ name ].value = value;
  35060. }
  35061. return this;
  35062. }
  35063. getValue() {
  35064. return this.getDefaultOutput().getValue();
  35065. }
  35066. deleteParameter( name ) {
  35067. let valueNode = this.parameters[ name ];
  35068. if ( valueNode ) {
  35069. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  35070. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  35071. }
  35072. return this;
  35073. }
  35074. clearParameters() {
  35075. for ( const name of Object.keys( this.parameters ) ) {
  35076. this.deleteParameter( name );
  35077. }
  35078. this.needsUpdate = true;
  35079. return this;
  35080. }
  35081. call( name, ...params ) {
  35082. const object = this.getObject();
  35083. const method = object[ name ];
  35084. if ( typeof method === 'function' ) {
  35085. return method( ...params );
  35086. }
  35087. }
  35088. async callAsync( name, ...params ) {
  35089. const object = this.getObject();
  35090. const method = object[ name ];
  35091. if ( typeof method === 'function' ) {
  35092. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  35093. }
  35094. }
  35095. getNodeType( builder ) {
  35096. return this.getDefaultOutputNode().getNodeType( builder );
  35097. }
  35098. refresh( output = null ) {
  35099. if ( output !== null ) {
  35100. this.getOutput( output ).refresh();
  35101. } else {
  35102. this._refresh();
  35103. }
  35104. }
  35105. getObject() {
  35106. if ( this.needsUpdate ) this.dispose();
  35107. if ( this._object !== null ) return this._object;
  35108. //
  35109. const refresh = () => this.refresh();
  35110. const setOutput = ( id, value ) => this.setOutput( id, value );
  35111. const parameters = new Parameters( this );
  35112. const THREE = global.get( 'THREE' );
  35113. const TSL = global.get( 'TSL' );
  35114. const method = this.getMethod( this.codeNode );
  35115. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  35116. this._object = method( ...params );
  35117. const layout = this._object.layout;
  35118. if ( layout ) {
  35119. if ( layout.cache === false ) {
  35120. this._local.clear();
  35121. }
  35122. // default output
  35123. this._output.outputType = layout.outputType || null;
  35124. if ( Array.isArray( layout.elements ) ) {
  35125. for ( const element of layout.elements ) {
  35126. const id = element.id || element.name;
  35127. if ( element.inputType ) {
  35128. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  35129. this.getParameter( id ).inputType = element.inputType;
  35130. }
  35131. if ( element.outputType ) {
  35132. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  35133. this.getOutput( id ).outputType = element.outputType;
  35134. }
  35135. }
  35136. }
  35137. }
  35138. return this._object;
  35139. }
  35140. deserialize( data ) {
  35141. super.deserialize( data );
  35142. for ( const name in this.parameters ) {
  35143. let valueNode = this.parameters[ name ];
  35144. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  35145. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  35146. }
  35147. }
  35148. getLayout() {
  35149. return this.getObject().layout;
  35150. }
  35151. getDefaultOutputNode() {
  35152. const output = this.getDefaultOutput().value;
  35153. if ( output && output.isNode ) {
  35154. return output;
  35155. }
  35156. return float();
  35157. }
  35158. getDefaultOutput() {
  35159. return this._exec()._output;
  35160. }
  35161. getMethod() {
  35162. if ( this.needsUpdate ) this.dispose();
  35163. if ( this._method !== null ) return this._method;
  35164. //
  35165. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  35166. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  35167. const properties = interfaceProps.join( ', ' );
  35168. const declarations = 'var ' + properties + '; var output = {};\n';
  35169. const returns = '\nreturn { ...output, ' + properties + ' };';
  35170. const code = declarations + this.codeNode.code + returns;
  35171. //
  35172. this._method = new Function( ...parametersProps, code );
  35173. return this._method;
  35174. }
  35175. dispose() {
  35176. if ( this._method === null ) return;
  35177. if ( this._object && typeof this._object.dispose === 'function' ) {
  35178. this._object.dispose();
  35179. }
  35180. this._method = null;
  35181. this._object = null;
  35182. this._source = null;
  35183. this._value = null;
  35184. this._needsOutputUpdate = true;
  35185. this._output.value = null;
  35186. this._outputs = {};
  35187. }
  35188. setup() {
  35189. return this.getDefaultOutputNode();
  35190. }
  35191. getCacheKey( force ) {
  35192. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  35193. for ( const param in this.parameters ) {
  35194. values.push( this.parameters[ param ].getCacheKey( force ) );
  35195. }
  35196. return hashArray( values );
  35197. }
  35198. set needsUpdate( value ) {
  35199. if ( value === true ) this.dispose();
  35200. }
  35201. get needsUpdate() {
  35202. return this.source !== this._source;
  35203. }
  35204. _exec() {
  35205. if ( this.codeNode === null ) return this;
  35206. if ( this._needsOutputUpdate === true ) {
  35207. this._value = this.call( 'main' );
  35208. this._needsOutputUpdate = false;
  35209. }
  35210. this._output.value = this._value;
  35211. return this;
  35212. }
  35213. _refresh() {
  35214. this.needsUpdate = true;
  35215. this._exec();
  35216. this._output.refresh();
  35217. }
  35218. }
  35219. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  35220. class FogNode extends Node {
  35221. static get type() {
  35222. return 'FogNode';
  35223. }
  35224. constructor( colorNode, factorNode ) {
  35225. super( 'float' );
  35226. this.isFogNode = true;
  35227. this.colorNode = colorNode;
  35228. this.factorNode = factorNode;
  35229. }
  35230. getViewZNode( builder ) {
  35231. let viewZ;
  35232. const getViewZ = builder.context.getViewZ;
  35233. if ( getViewZ !== undefined ) {
  35234. viewZ = getViewZ( this );
  35235. }
  35236. return ( viewZ || positionView.z ).negate();
  35237. }
  35238. setup() {
  35239. return this.factorNode;
  35240. }
  35241. }
  35242. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  35243. class FogRangeNode extends FogNode {
  35244. static get type() {
  35245. return 'FogRangeNode';
  35246. }
  35247. constructor( colorNode, nearNode, farNode ) {
  35248. super( colorNode );
  35249. this.isFogRangeNode = true;
  35250. this.nearNode = nearNode;
  35251. this.farNode = farNode;
  35252. }
  35253. setup( builder ) {
  35254. const viewZ = this.getViewZNode( builder );
  35255. return smoothstep( this.nearNode, this.farNode, viewZ );
  35256. }
  35257. }
  35258. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  35259. class FogExp2Node extends FogNode {
  35260. static get type() {
  35261. return 'FogExp2Node';
  35262. }
  35263. constructor( colorNode, densityNode ) {
  35264. super( colorNode );
  35265. this.isFogExp2Node = true;
  35266. this.densityNode = densityNode;
  35267. }
  35268. setup( builder ) {
  35269. const viewZ = this.getViewZNode( builder );
  35270. const density = this.densityNode;
  35271. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  35272. }
  35273. }
  35274. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  35275. let min = null;
  35276. let max = null;
  35277. class RangeNode extends Node {
  35278. static get type() {
  35279. return 'RangeNode';
  35280. }
  35281. constructor( minNode = float(), maxNode = float() ) {
  35282. super();
  35283. this.minNode = minNode;
  35284. this.maxNode = maxNode;
  35285. }
  35286. getVectorLength( builder ) {
  35287. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  35288. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  35289. return minLength > maxLength ? minLength : maxLength;
  35290. }
  35291. getNodeType( builder ) {
  35292. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  35293. }
  35294. setup( builder ) {
  35295. const object = builder.object;
  35296. let output = null;
  35297. if ( object.count > 1 ) {
  35298. const minValue = this.minNode.value;
  35299. const maxValue = this.maxNode.value;
  35300. const minLength = builder.getTypeLength( getValueType( minValue ) );
  35301. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  35302. min = min || new Vector4();
  35303. max = max || new Vector4();
  35304. min.setScalar( 0 );
  35305. max.setScalar( 0 );
  35306. if ( minLength === 1 ) min.setScalar( minValue );
  35307. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  35308. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  35309. if ( maxLength === 1 ) max.setScalar( maxValue );
  35310. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  35311. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  35312. const stride = 4;
  35313. const length = stride * object.count;
  35314. const array = new Float32Array( length );
  35315. for ( let i = 0; i < length; i ++ ) {
  35316. const index = i % stride;
  35317. const minElementValue = min.getComponent( index );
  35318. const maxElementValue = max.getComponent( index );
  35319. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  35320. }
  35321. const nodeType = this.getNodeType( builder );
  35322. if ( object.count <= 4096 ) {
  35323. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  35324. } else {
  35325. // TODO: Improve anonymous buffer attribute creation removing this part
  35326. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  35327. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  35328. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  35329. }
  35330. } else {
  35331. output = float( 0 );
  35332. }
  35333. return output;
  35334. }
  35335. }
  35336. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  35337. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  35338. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  35339. } );
  35340. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  35341. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  35342. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  35343. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  35344. const texelSize = vec2( 1 ).div( mapSize );
  35345. const dx0 = texelSize.x.negate().mul( radius );
  35346. const dy0 = texelSize.y.negate().mul( radius );
  35347. const dx1 = texelSize.x.mul( radius );
  35348. const dy1 = texelSize.y.mul( radius );
  35349. const dx2 = dx0.div( 2 );
  35350. const dy2 = dy0.div( 2 );
  35351. const dx3 = dx1.div( 2 );
  35352. const dy3 = dy1.div( 2 );
  35353. return add(
  35354. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  35355. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  35356. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  35357. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  35358. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  35359. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  35360. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  35361. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  35362. depthCompare( shadowCoord.xy, shadowCoord.z ),
  35363. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  35364. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  35365. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  35366. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  35367. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  35368. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  35369. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  35370. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  35371. ).mul( 1 / 17 );
  35372. } );
  35373. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  35374. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  35375. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  35376. const texelSize = vec2( 1 ).div( mapSize );
  35377. const dx = texelSize.x;
  35378. const dy = texelSize.y;
  35379. const uv = shadowCoord.xy;
  35380. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  35381. uv.subAssign( f.mul( texelSize ) );
  35382. return add(
  35383. depthCompare( uv, shadowCoord.z ),
  35384. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  35385. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  35386. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  35387. mix(
  35388. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  35389. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  35390. f.x
  35391. ),
  35392. mix(
  35393. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  35394. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  35395. f.x
  35396. ),
  35397. mix(
  35398. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  35399. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  35400. f.y
  35401. ),
  35402. mix(
  35403. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  35404. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  35405. f.y
  35406. ),
  35407. mix(
  35408. mix(
  35409. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  35410. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  35411. f.x
  35412. ),
  35413. mix(
  35414. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  35415. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  35416. f.x
  35417. ),
  35418. f.y
  35419. )
  35420. ).mul( 1 / 9 );
  35421. } );
  35422. // VSM
  35423. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  35424. const occlusion = float( 1 ).toVar();
  35425. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  35426. const hardShadow = step( shadowCoord.z, distribution.x );
  35427. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  35428. const distance = shadowCoord.z.sub( distribution.x );
  35429. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  35430. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  35431. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  35432. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  35433. } );
  35434. return occlusion;
  35435. } );
  35436. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  35437. const mean = float( 0 ).toVar();
  35438. const squaredMean = float( 0 ).toVar();
  35439. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  35440. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  35441. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  35442. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  35443. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  35444. mean.addAssign( depth );
  35445. squaredMean.addAssign( depth.mul( depth ) );
  35446. } );
  35447. mean.divAssign( samples );
  35448. squaredMean.divAssign( samples );
  35449. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  35450. return vec2( mean, std_dev );
  35451. } );
  35452. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  35453. const mean = float( 0 ).toVar();
  35454. const squaredMean = float( 0 ).toVar();
  35455. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  35456. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  35457. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  35458. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  35459. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  35460. mean.addAssign( distribution.x );
  35461. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  35462. } );
  35463. mean.divAssign( samples );
  35464. squaredMean.divAssign( samples );
  35465. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  35466. return vec2( mean, std_dev );
  35467. } );
  35468. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  35469. //
  35470. let _overrideMaterial = null;
  35471. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  35472. class AnalyticLightNode extends LightingNode {
  35473. static get type() {
  35474. return 'AnalyticLightNode';
  35475. }
  35476. constructor( light = null ) {
  35477. super();
  35478. this.updateType = NodeUpdateType.FRAME;
  35479. this.light = light;
  35480. this.color = new Color();
  35481. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  35482. this.baseColorNode = null;
  35483. this.shadowMap = null;
  35484. this.shadowNode = null;
  35485. this.shadowColorNode = null;
  35486. this.vsmShadowMapVertical = null;
  35487. this.vsmShadowMapHorizontal = null;
  35488. this.vsmMaterialVertical = null;
  35489. this.vsmMaterialHorizontal = null;
  35490. this.isAnalyticLightNode = true;
  35491. }
  35492. getCacheKey() {
  35493. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  35494. }
  35495. getHash() {
  35496. return this.light.uuid;
  35497. }
  35498. setupShadow( builder ) {
  35499. const { object, renderer } = builder;
  35500. if ( renderer.shadowMap.enabled === false ) return;
  35501. let shadowColorNode = this.shadowColorNode;
  35502. if ( shadowColorNode === null ) {
  35503. if ( _overrideMaterial === null ) {
  35504. _overrideMaterial = new NodeMaterial();
  35505. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  35506. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  35507. _overrideMaterial.name = 'ShadowMaterial';
  35508. }
  35509. const shadowMapType = renderer.shadowMap.type;
  35510. const shadow = this.light.shadow;
  35511. const depthTexture = new DepthTexture();
  35512. depthTexture.compareFunction = LessCompare;
  35513. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  35514. shadowMap.depthTexture = depthTexture;
  35515. shadow.camera.updateProjectionMatrix();
  35516. // VSM
  35517. if ( shadowMapType === VSMShadowMap ) {
  35518. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  35519. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  35520. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  35521. const shadowPassVertical = texture( depthTexture );
  35522. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  35523. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  35524. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  35525. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  35526. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  35527. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  35528. material.name = 'VSMVertical';
  35529. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  35530. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  35531. material.name = 'VSMHorizontal';
  35532. }
  35533. //
  35534. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  35535. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  35536. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  35537. const position = object.material.shadowPositionNode || positionWorld;
  35538. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( normalWorld.mul( normalBias ) ) );
  35539. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  35540. let coordZ = shadowCoord.z.add( bias );
  35541. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  35542. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  35543. }
  35544. shadowCoord = vec3(
  35545. shadowCoord.x,
  35546. shadowCoord.y.oneMinus(), // follow webgpu standards
  35547. coordZ
  35548. );
  35549. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  35550. .and( shadowCoord.x.lessThanEqual( 1 ) )
  35551. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  35552. .and( shadowCoord.y.lessThanEqual( 1 ) )
  35553. .and( shadowCoord.z.lessThanEqual( 1 ) );
  35554. //
  35555. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  35556. if ( filterFn === null ) {
  35557. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  35558. }
  35559. const shadowColor = texture( shadowMap.texture, shadowCoord );
  35560. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  35561. this.shadowMap = shadowMap;
  35562. this.light.shadow.map = shadowMap;
  35563. this.shadowNode = shadowNode;
  35564. this.shadowColorNode = shadowColorNode = this.colorNode.mul( mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ) );
  35565. this.baseColorNode = this.colorNode;
  35566. }
  35567. //
  35568. this.colorNode = shadowColorNode;
  35569. this.updateBeforeType = NodeUpdateType.RENDER;
  35570. }
  35571. setup( builder ) {
  35572. this.colorNode = this.baseColorNode || this.colorNode;
  35573. if ( this.light.castShadow ) {
  35574. if ( builder.object.receiveShadow ) {
  35575. this.setupShadow( builder );
  35576. }
  35577. } else if ( this.shadowNode !== null ) {
  35578. this.disposeShadow();
  35579. }
  35580. }
  35581. updateShadow( frame ) {
  35582. const { shadowMap, light } = this;
  35583. const { renderer, scene, camera } = frame;
  35584. const shadowType = renderer.shadowMap.type;
  35585. const depthVersion = shadowMap.depthTexture.version;
  35586. this._depthVersionCached = depthVersion;
  35587. const currentOverrideMaterial = scene.overrideMaterial;
  35588. scene.overrideMaterial = _overrideMaterial;
  35589. shadowMap.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  35590. light.shadow.updateMatrices( light );
  35591. light.shadow.camera.layers.mask = camera.layers.mask;
  35592. const currentRenderTarget = renderer.getRenderTarget();
  35593. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  35594. renderer.setRenderObjectFunction( ( object, ...params ) => {
  35595. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  35596. renderer.renderObject( object, ...params );
  35597. }
  35598. } );
  35599. renderer.setRenderTarget( shadowMap );
  35600. renderer.render( scene, light.shadow.camera );
  35601. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  35602. // vsm blur pass
  35603. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  35604. this.vsmPass( frame, light );
  35605. }
  35606. renderer.setRenderTarget( currentRenderTarget );
  35607. scene.overrideMaterial = currentOverrideMaterial;
  35608. }
  35609. vsmPass( frame, light ) {
  35610. const { renderer } = frame;
  35611. this.vsmShadowMapVertical.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  35612. this.vsmShadowMapHorizontal.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  35613. renderer.setRenderTarget( this.vsmShadowMapVertical );
  35614. _quadMesh$1.material = this.vsmMaterialVertical;
  35615. _quadMesh$1.render( renderer );
  35616. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  35617. _quadMesh$1.material = this.vsmMaterialHorizontal;
  35618. _quadMesh$1.render( renderer );
  35619. }
  35620. disposeShadow() {
  35621. this.shadowMap.dispose();
  35622. this.shadowMap = null;
  35623. if ( this.vsmShadowMapVertical !== null ) {
  35624. this.vsmShadowMapVertical.dispose();
  35625. this.vsmShadowMapVertical = null;
  35626. this.vsmMaterialVertical.dispose();
  35627. this.vsmMaterialVertical = null;
  35628. }
  35629. if ( this.vsmShadowMapHorizontal !== null ) {
  35630. this.vsmShadowMapHorizontal.dispose();
  35631. this.vsmShadowMapHorizontal = null;
  35632. this.vsmMaterialHorizontal.dispose();
  35633. this.vsmMaterialHorizontal = null;
  35634. }
  35635. this.shadowNode = null;
  35636. this.shadowColorNode = null;
  35637. this.baseColorNode = null;
  35638. this.updateBeforeType = NodeUpdateType.NONE;
  35639. }
  35640. updateBefore( frame ) {
  35641. const shadow = this.light.shadow;
  35642. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  35643. if ( needsUpdate ) {
  35644. this.updateShadow( frame );
  35645. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  35646. shadow.needsUpdate = false;
  35647. }
  35648. }
  35649. }
  35650. update( /*frame*/ ) {
  35651. const { light } = this;
  35652. this.color.copy( light.color ).multiplyScalar( light.intensity );
  35653. }
  35654. }
  35655. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  35656. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  35657. // based upon Frostbite 3 Moving to Physically-based Rendering
  35658. // page 32, equation 26: E[window1]
  35659. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  35660. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  35661. return cutoffDistance.greaterThan( 0 ).select(
  35662. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  35663. distanceFalloff
  35664. );
  35665. } ); // validated
  35666. let uniformsLib;
  35667. function getLightData( light ) {
  35668. uniformsLib = uniformsLib || new WeakMap();
  35669. let uniforms = uniformsLib.get( light );
  35670. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  35671. return uniforms;
  35672. }
  35673. function lightPosition( light ) {
  35674. const data = getLightData( light );
  35675. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  35676. }
  35677. function lightTargetPosition( light ) {
  35678. const data = getLightData( light );
  35679. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  35680. }
  35681. function lightViewPosition( light ) {
  35682. const data = getLightData( light );
  35683. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  35684. self.value = self.value || new Vector3();
  35685. self.value.setFromMatrixPosition( light.matrixWorld );
  35686. self.value.applyMatrix4( camera.matrixWorldInverse );
  35687. } ) );
  35688. }
  35689. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  35690. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  35691. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  35692. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  35693. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  35694. const result = word.shiftRight( 22 ).bitXor( word );
  35695. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  35696. } );
  35697. // remapping functions https://iquilezles.org/articles/functions/
  35698. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  35699. const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) );
  35700. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  35701. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  35702. // https://github.com/cabbibo/glsl-tri-noise-3d
  35703. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  35704. return x.fract().sub( .5 ).abs();
  35705. } ).setLayout( {
  35706. name: 'tri',
  35707. type: 'float',
  35708. inputs: [
  35709. { name: 'x', type: 'float' }
  35710. ]
  35711. } );
  35712. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  35713. return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) );
  35714. } ).setLayout( {
  35715. name: 'tri3',
  35716. type: 'vec3',
  35717. inputs: [
  35718. { name: 'p', type: 'vec3' }
  35719. ]
  35720. } );
  35721. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  35722. const p = vec3( p_immutable ).toVar();
  35723. const z = float( 1.4 ).toVar();
  35724. const rz = float( 0.0 ).toVar();
  35725. const bp = vec3( p ).toVar();
  35726. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  35727. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  35728. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  35729. bp.mulAssign( 1.8 );
  35730. z.mulAssign( 1.5 );
  35731. p.mulAssign( 1.2 );
  35732. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  35733. rz.addAssign( t.div( z ) );
  35734. bp.addAssign( 0.14 );
  35735. } );
  35736. return rz;
  35737. } ).setLayout( {
  35738. name: 'triNoise3D',
  35739. type: 'float',
  35740. inputs: [
  35741. { name: 'p', type: 'vec3' },
  35742. { name: 'spd', type: 'float' },
  35743. { name: 'time', type: 'float' }
  35744. ]
  35745. } );
  35746. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  35747. return rotate( uv.sub( center ), rotation ).add( center );
  35748. } );
  35749. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  35750. const delta = uv.sub( center );
  35751. const delta2 = delta.dot( delta );
  35752. const delta4 = delta2.mul( delta2 );
  35753. const deltaOffset = delta4.mul( strength );
  35754. return uv.add( delta.mul( deltaOffset ) );
  35755. } );
  35756. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  35757. let worldMatrix;
  35758. if ( position !== null ) {
  35759. worldMatrix = modelWorldMatrix.toVar();
  35760. worldMatrix[ 3 ][ 0 ] = position.x;
  35761. worldMatrix[ 3 ][ 1 ] = position.y;
  35762. worldMatrix[ 3 ][ 2 ] = position.z;
  35763. } else {
  35764. worldMatrix = modelWorldMatrix;
  35765. }
  35766. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  35767. if ( defined( horizontal ) ) {
  35768. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  35769. modelViewMatrix[ 0 ][ 1 ] = 0;
  35770. modelViewMatrix[ 0 ][ 2 ] = 0;
  35771. }
  35772. if ( defined( vertical ) ) {
  35773. modelViewMatrix[ 1 ][ 0 ] = 0;
  35774. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  35775. modelViewMatrix[ 1 ][ 2 ] = 0;
  35776. }
  35777. modelViewMatrix[ 2 ][ 0 ] = 0;
  35778. modelViewMatrix[ 2 ][ 1 ] = 0;
  35779. modelViewMatrix[ 2 ][ 2 ] = 1;
  35780. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  35781. } );
  35782. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  35783. const depth = linearDepth();
  35784. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  35785. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  35786. return finalUV;
  35787. } );
  35788. const _objectData = new WeakMap();
  35789. class VelocityNode extends TempNode {
  35790. static get type() {
  35791. return 'VelocityNode';
  35792. }
  35793. constructor() {
  35794. super( 'vec2' );
  35795. this.updateType = NodeUpdateType.OBJECT;
  35796. this.updateAfterType = NodeUpdateType.OBJECT;
  35797. this.previousModelWorldMatrix = uniform( new Matrix4() );
  35798. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  35799. this.previousCameraViewMatrix = uniform( new Matrix4() );
  35800. }
  35801. update( { frameId, camera, object } ) {
  35802. const previousModelMatrix = getPreviousMatrix( object );
  35803. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  35804. //
  35805. const cameraData = getData( camera );
  35806. if ( cameraData.frameId !== frameId ) {
  35807. cameraData.frameId = frameId;
  35808. if ( cameraData.previousProjectionMatrix === undefined ) {
  35809. cameraData.previousProjectionMatrix = new Matrix4();
  35810. cameraData.previousCameraViewMatrix = new Matrix4();
  35811. cameraData.currentProjectionMatrix = new Matrix4();
  35812. cameraData.currentCameraViewMatrix = new Matrix4();
  35813. cameraData.previousProjectionMatrix.copy( camera.projectionMatrix );
  35814. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  35815. } else {
  35816. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  35817. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  35818. }
  35819. cameraData.currentProjectionMatrix.copy( camera.projectionMatrix );
  35820. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  35821. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  35822. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  35823. }
  35824. }
  35825. updateAfter( { object } ) {
  35826. getPreviousMatrix( object ).copy( object.matrixWorld );
  35827. }
  35828. setup( /*builder*/ ) {
  35829. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  35830. const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  35831. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  35832. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  35833. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  35834. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  35835. return velocity;
  35836. }
  35837. }
  35838. function getData( object ) {
  35839. let objectData = _objectData.get( object );
  35840. if ( objectData === undefined ) {
  35841. objectData = {};
  35842. _objectData.set( object, objectData );
  35843. }
  35844. return objectData;
  35845. }
  35846. function getPreviousMatrix( object, index = 0 ) {
  35847. const objectData = getData( object );
  35848. let matrix = objectData[ index ];
  35849. if ( matrix === undefined ) {
  35850. objectData[ index ] = matrix = new Matrix4();
  35851. }
  35852. return matrix;
  35853. }
  35854. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  35855. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35856. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  35857. } ).setLayout( {
  35858. name: 'burnBlend',
  35859. type: 'vec3',
  35860. inputs: [
  35861. { name: 'base', type: 'vec3' },
  35862. { name: 'blend', type: 'vec3' }
  35863. ]
  35864. } );
  35865. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35866. return min$1( base.div( blend.oneMinus() ), 1.0 );
  35867. } ).setLayout( {
  35868. name: 'dodgeBlend',
  35869. type: 'vec3',
  35870. inputs: [
  35871. { name: 'base', type: 'vec3' },
  35872. { name: 'blend', type: 'vec3' }
  35873. ]
  35874. } );
  35875. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35876. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  35877. } ).setLayout( {
  35878. name: 'screenBlend',
  35879. type: 'vec3',
  35880. inputs: [
  35881. { name: 'base', type: 'vec3' },
  35882. { name: 'blend', type: 'vec3' }
  35883. ]
  35884. } );
  35885. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35886. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  35887. } ).setLayout( {
  35888. name: 'overlayBlend',
  35889. type: 'vec3',
  35890. inputs: [
  35891. { name: 'base', type: 'vec3' },
  35892. { name: 'blend', type: 'vec3' }
  35893. ]
  35894. } );
  35895. const motionBlur = /*@__PURE__*/ Fn( ( [ inputNode, velocity, numSamples = int( 16 ) ] ) => {
  35896. const sampleColor = ( uv ) => inputNode.uv( uv );
  35897. const uvs = uv();
  35898. const colorResult = sampleColor( uvs ).toVar();
  35899. const fSamples = float( numSamples );
  35900. Loop( { start: int( 1 ), end: numSamples, type: 'int', condition: '<=' }, ( { i } ) => {
  35901. const offset = velocity.mul( float( i ).div( fSamples.sub( 1 ) ).sub( 0.5 ) );
  35902. colorResult.addAssign( sampleColor( uvs.add( offset ) ) );
  35903. } );
  35904. colorResult.divAssign( fSamples );
  35905. return colorResult;
  35906. } );
  35907. const bleach = /*@__PURE__*/ Fn( ( [ color, opacity = 1 ] ) => {
  35908. const base = color;
  35909. const lum = luminance( base.rgb );
  35910. const blend = vec3( lum );
  35911. const L = min$1( 1.0, max$1( 0.0, float( 10.0 ).mul( lum.sub( 0.45 ) ) ) );
  35912. const result1 = blend.mul( base.rgb ).mul( 2.0 );
  35913. const result2 = float( 2.0 ).mul( blend.oneMinus() ).mul( base.rgb.oneMinus() ).oneMinus();
  35914. const newColor = mix( result1, result2, L );
  35915. const A2 = base.a.mul( opacity );
  35916. const mixRGB = A2.mul( newColor.rgb );
  35917. mixRGB.addAssign( base.rgb.mul( A2.oneMinus() ) );
  35918. return vec4( mixRGB, base.a );
  35919. } );
  35920. const sepia = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35921. const c = vec3( color );
  35922. // https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/sepia.js
  35923. return vec4(
  35924. dot( c, vec3( 0.393, 0.769, 0.189 ) ),
  35925. dot( c, vec3( 0.349, 0.686, 0.168 ) ),
  35926. dot( c, vec3( 0.272, 0.534, 0.131 ) ),
  35927. color.a
  35928. );
  35929. } );
  35930. const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35931. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  35932. const b = color.mul( 0.0773993808 );
  35933. const factor = color.lessThanEqual( 0.04045 );
  35934. const rgbResult = mix( a, b, factor );
  35935. return rgbResult;
  35936. } ).setLayout( {
  35937. name: 'sRGBToLinearSRGB',
  35938. type: 'vec3',
  35939. inputs: [
  35940. { name: 'color', type: 'vec3' }
  35941. ]
  35942. } );
  35943. const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35944. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  35945. const b = color.mul( 12.92 );
  35946. const factor = color.lessThanEqual( 0.0031308 );
  35947. const rgbResult = mix( a, b, factor );
  35948. return rgbResult;
  35949. } ).setLayout( {
  35950. name: 'linearSRGBTosRGB',
  35951. type: 'vec3',
  35952. inputs: [
  35953. { name: 'color', type: 'vec3' }
  35954. ]
  35955. } );
  35956. // exposure only
  35957. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35958. return color.mul( exposure ).clamp();
  35959. } ).setLayout( {
  35960. name: 'linearToneMapping',
  35961. type: 'vec3',
  35962. inputs: [
  35963. { name: 'color', type: 'vec3' },
  35964. { name: 'exposure', type: 'float' }
  35965. ]
  35966. } );
  35967. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  35968. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35969. color = color.mul( exposure );
  35970. return color.div( color.add( 1.0 ) ).clamp();
  35971. } ).setLayout( {
  35972. name: 'reinhardToneMapping',
  35973. type: 'vec3',
  35974. inputs: [
  35975. { name: 'color', type: 'vec3' },
  35976. { name: 'exposure', type: 'float' }
  35977. ]
  35978. } );
  35979. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  35980. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35981. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  35982. color = color.mul( exposure );
  35983. color = color.sub( 0.004 ).max( 0.0 );
  35984. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  35985. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  35986. return a.div( b ).pow( 2.2 );
  35987. } ).setLayout( {
  35988. name: 'cineonToneMapping',
  35989. type: 'vec3',
  35990. inputs: [
  35991. { name: 'color', type: 'vec3' },
  35992. { name: 'exposure', type: 'float' }
  35993. ]
  35994. } );
  35995. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  35996. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35997. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  35998. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  35999. return a.div( b );
  36000. } );
  36001. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  36002. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36003. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  36004. const ACESInputMat = mat3(
  36005. 0.59719, 0.35458, 0.04823,
  36006. 0.07600, 0.90834, 0.01566,
  36007. 0.02840, 0.13383, 0.83777
  36008. );
  36009. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  36010. const ACESOutputMat = mat3(
  36011. 1.60475, - 0.53108, - 0.07367,
  36012. - 0.10208, 1.10813, - 0.00605,
  36013. - 0.00327, - 0.07276, 1.07602
  36014. );
  36015. color = color.mul( exposure ).div( 0.6 );
  36016. color = ACESInputMat.mul( color );
  36017. // Apply RRT and ODT
  36018. color = RRTAndODTFit( color );
  36019. color = ACESOutputMat.mul( color );
  36020. // Clamp to [0, 1]
  36021. return color.clamp();
  36022. } ).setLayout( {
  36023. name: 'acesFilmicToneMapping',
  36024. type: 'vec3',
  36025. inputs: [
  36026. { name: 'color', type: 'vec3' },
  36027. { name: 'exposure', type: 'float' }
  36028. ]
  36029. } );
  36030. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  36031. const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  36032. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36033. const x = vec3( x_immutable ).toVar();
  36034. const x2 = vec3( x.mul( x ) ).toVar();
  36035. const x4 = vec3( x2.mul( x2 ) ).toVar();
  36036. return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) );
  36037. } );
  36038. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36039. const colortone = vec3( color ).toVar();
  36040. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  36041. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  36042. const AgxMinEv = float( - 12.47393 );
  36043. const AgxMaxEv = float( 4.026069 );
  36044. colortone.mulAssign( exposure );
  36045. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  36046. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  36047. colortone.assign( max$1( colortone, 1e-10 ) );
  36048. colortone.assign( log2( colortone ) );
  36049. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  36050. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  36051. colortone.assign( agxDefaultContrastApprox( colortone ) );
  36052. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  36053. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  36054. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  36055. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  36056. return colortone;
  36057. } ).setLayout( {
  36058. name: 'agxToneMapping',
  36059. type: 'vec3',
  36060. inputs: [
  36061. { name: 'color', type: 'vec3' },
  36062. { name: 'exposure', type: 'float' }
  36063. ]
  36064. } );
  36065. // https://modelviewer.dev/examples/tone-mapping
  36066. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36067. const StartCompression = float( 0.8 - 0.04 );
  36068. const Desaturation = float( 0.15 );
  36069. color = color.mul( exposure );
  36070. const x = min$1( color.r, min$1( color.g, color.b ) );
  36071. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  36072. color.subAssign( offset );
  36073. const peak = max$1( color.r, max$1( color.g, color.b ) );
  36074. If( peak.lessThan( StartCompression ), () => {
  36075. return color;
  36076. } );
  36077. const d = sub( 1, StartCompression );
  36078. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  36079. color.mulAssign( newPeak.div( peak ) );
  36080. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  36081. return mix( color, vec3( newPeak ), g );
  36082. } ).setLayout( {
  36083. name: 'neutralToneMapping',
  36084. type: 'vec3',
  36085. inputs: [
  36086. { name: 'color', type: 'vec3' },
  36087. { name: 'exposure', type: 'float' }
  36088. ]
  36089. } );
  36090. class ComputeBuiltinNode extends Node {
  36091. static get type() {
  36092. return 'ComputeBuiltinNode';
  36093. }
  36094. constructor( builtinName, nodeType ) {
  36095. super( nodeType );
  36096. this._builtinName = builtinName;
  36097. }
  36098. getHash( builder ) {
  36099. return this.getBuiltinName( builder );
  36100. }
  36101. getNodeType( /*builder*/ ) {
  36102. return this.nodeType;
  36103. }
  36104. setBuiltinName( builtinName ) {
  36105. this._builtinName = builtinName;
  36106. return this;
  36107. }
  36108. getBuiltinName( /*builder*/ ) {
  36109. return this._builtinName;
  36110. }
  36111. hasBuiltin( builder ) {
  36112. builder.hasBuiltin( this._builtinName );
  36113. }
  36114. generate( builder, output ) {
  36115. const builtinName = this.getBuiltinName( builder );
  36116. const nodeType = this.getNodeType( builder );
  36117. if ( builder.shaderStage === 'compute' ) {
  36118. return builder.format( builtinName, nodeType, output );
  36119. } else {
  36120. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  36121. return builder.generateConst( nodeType );
  36122. }
  36123. }
  36124. serialize( data ) {
  36125. super.serialize( data );
  36126. data.global = this.global;
  36127. data._builtinName = this._builtinName;
  36128. }
  36129. deserialize( data ) {
  36130. super.deserialize( data );
  36131. this.global = data.global;
  36132. this._builtinName = data._builtinName;
  36133. }
  36134. }
  36135. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  36136. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  36137. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  36138. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  36139. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  36140. class BarrierNode extends Node {
  36141. constructor( scope ) {
  36142. super();
  36143. this.scope = scope;
  36144. }
  36145. generate( builder ) {
  36146. const { scope } = this;
  36147. const { renderer } = builder;
  36148. if ( renderer.backend.isWebGLBackend === true ) {
  36149. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  36150. } else {
  36151. builder.addLineFlowCode( `${scope}Barrier()`, this );
  36152. }
  36153. }
  36154. }
  36155. const barrier = nodeProxy( BarrierNode );
  36156. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  36157. const storageBarrier = () => barrier( 'storage' ).append();
  36158. const textureBarrier = () => barrier( 'texture' ).append();
  36159. class WorkgroupInfoElementNode extends ArrayElementNode {
  36160. constructor( workgroupInfoNode, indexNode ) {
  36161. super( workgroupInfoNode, indexNode );
  36162. this.isWorkgroupInfoElementNode = true;
  36163. }
  36164. generate( builder, output ) {
  36165. let snippet;
  36166. const isAssignContext = builder.context.assign;
  36167. snippet = super.generate( builder );
  36168. if ( isAssignContext !== true ) {
  36169. const type = this.getNodeType( builder );
  36170. snippet = builder.format( snippet, type, output );
  36171. }
  36172. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  36173. return snippet;
  36174. }
  36175. }
  36176. class WorkgroupInfoNode extends Node {
  36177. constructor( scope, bufferType, bufferCount = 0 ) {
  36178. super( bufferType );
  36179. this.bufferType = bufferType;
  36180. this.bufferCount = bufferCount;
  36181. this.isWorkgroupInfoNode = true;
  36182. this.scope = scope;
  36183. }
  36184. label( name ) {
  36185. this.name = name;
  36186. return this;
  36187. }
  36188. getHash() {
  36189. return this.uuid;
  36190. }
  36191. setScope( scope ) {
  36192. this.scope = scope;
  36193. return this;
  36194. }
  36195. getInputType( /*builder*/ ) {
  36196. return `${this.scope}Array`;
  36197. }
  36198. element( indexNode ) {
  36199. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  36200. }
  36201. generate( builder ) {
  36202. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  36203. }
  36204. }
  36205. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  36206. class AtomicFunctionNode extends TempNode {
  36207. static get type() {
  36208. return 'AtomicFunctionNode';
  36209. }
  36210. constructor( method, pointerNode, valueNode, storeNode = null ) {
  36211. super( 'uint' );
  36212. this.method = method;
  36213. this.pointerNode = pointerNode;
  36214. this.valueNode = valueNode;
  36215. this.storeNode = storeNode;
  36216. }
  36217. getInputType( builder ) {
  36218. return this.pointerNode.getNodeType( builder );
  36219. }
  36220. getNodeType( builder ) {
  36221. return this.getInputType( builder );
  36222. }
  36223. generate( builder ) {
  36224. const method = this.method;
  36225. const type = this.getNodeType( builder );
  36226. const inputType = this.getInputType( builder );
  36227. const a = this.pointerNode;
  36228. const b = this.valueNode;
  36229. const params = [];
  36230. params.push( `&${ a.build( builder, inputType ) }` );
  36231. params.push( b.build( builder, inputType ) );
  36232. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  36233. if ( this.storeNode !== null ) {
  36234. const varSnippet = this.storeNode.build( builder, inputType );
  36235. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  36236. } else {
  36237. builder.addLineFlowCode( methodSnippet, this );
  36238. }
  36239. }
  36240. }
  36241. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  36242. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  36243. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  36244. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  36245. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  36246. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  36247. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  36248. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  36249. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  36250. const atomicNode = nodeProxy( AtomicFunctionNode );
  36251. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  36252. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  36253. node.append();
  36254. return node;
  36255. };
  36256. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  36257. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  36258. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  36259. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  36260. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  36261. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  36262. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  36263. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  36264. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  36265. const uv = coord.mul( 2.0 );
  36266. const cx = uv.x.floor();
  36267. const cy = uv.y.floor();
  36268. const result = cx.add( cy ).mod( 2.0 );
  36269. return result.sign();
  36270. } );
  36271. // Three.js Transpiler
  36272. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  36273. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  36274. const f = float( f_immutable ).toVar();
  36275. const t = float( t_immutable ).toVar();
  36276. const b = bool( b_immutable ).toVar();
  36277. return select( b, t, f );
  36278. } ).setLayout( {
  36279. name: 'mx_select',
  36280. type: 'float',
  36281. inputs: [
  36282. { name: 'b', type: 'bool' },
  36283. { name: 't', type: 'float' },
  36284. { name: 'f', type: 'float' }
  36285. ]
  36286. } );
  36287. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  36288. const b = bool( b_immutable ).toVar();
  36289. const val = float( val_immutable ).toVar();
  36290. return select( b, val.negate(), val );
  36291. } ).setLayout( {
  36292. name: 'mx_negate_if',
  36293. type: 'float',
  36294. inputs: [
  36295. { name: 'val', type: 'float' },
  36296. { name: 'b', type: 'bool' }
  36297. ]
  36298. } );
  36299. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36300. const x = float( x_immutable ).toVar();
  36301. return int( floor( x ) );
  36302. } ).setLayout( {
  36303. name: 'mx_floor',
  36304. type: 'int',
  36305. inputs: [
  36306. { name: 'x', type: 'float' }
  36307. ]
  36308. } );
  36309. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  36310. const x = float( x_immutable ).toVar();
  36311. i.assign( mx_floor( x ) );
  36312. return x.sub( float( i ) );
  36313. } );
  36314. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  36315. const t = float( t_immutable ).toVar();
  36316. const s = float( s_immutable ).toVar();
  36317. const v3 = float( v3_immutable ).toVar();
  36318. const v2 = float( v2_immutable ).toVar();
  36319. const v1 = float( v1_immutable ).toVar();
  36320. const v0 = float( v0_immutable ).toVar();
  36321. const s1 = float( sub( 1.0, s ) ).toVar();
  36322. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  36323. } ).setLayout( {
  36324. name: 'mx_bilerp_0',
  36325. type: 'float',
  36326. inputs: [
  36327. { name: 'v0', type: 'float' },
  36328. { name: 'v1', type: 'float' },
  36329. { name: 'v2', type: 'float' },
  36330. { name: 'v3', type: 'float' },
  36331. { name: 's', type: 'float' },
  36332. { name: 't', type: 'float' }
  36333. ]
  36334. } );
  36335. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  36336. const t = float( t_immutable ).toVar();
  36337. const s = float( s_immutable ).toVar();
  36338. const v3 = vec3( v3_immutable ).toVar();
  36339. const v2 = vec3( v2_immutable ).toVar();
  36340. const v1 = vec3( v1_immutable ).toVar();
  36341. const v0 = vec3( v0_immutable ).toVar();
  36342. const s1 = float( sub( 1.0, s ) ).toVar();
  36343. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  36344. } ).setLayout( {
  36345. name: 'mx_bilerp_1',
  36346. type: 'vec3',
  36347. inputs: [
  36348. { name: 'v0', type: 'vec3' },
  36349. { name: 'v1', type: 'vec3' },
  36350. { name: 'v2', type: 'vec3' },
  36351. { name: 'v3', type: 'vec3' },
  36352. { name: 's', type: 'float' },
  36353. { name: 't', type: 'float' }
  36354. ]
  36355. } );
  36356. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  36357. const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  36358. const r = float( r_immutable ).toVar();
  36359. const t = float( t_immutable ).toVar();
  36360. const s = float( s_immutable ).toVar();
  36361. const v7 = float( v7_immutable ).toVar();
  36362. const v6 = float( v6_immutable ).toVar();
  36363. const v5 = float( v5_immutable ).toVar();
  36364. const v4 = float( v4_immutable ).toVar();
  36365. const v3 = float( v3_immutable ).toVar();
  36366. const v2 = float( v2_immutable ).toVar();
  36367. const v1 = float( v1_immutable ).toVar();
  36368. const v0 = float( v0_immutable ).toVar();
  36369. const s1 = float( sub( 1.0, s ) ).toVar();
  36370. const t1 = float( sub( 1.0, t ) ).toVar();
  36371. const r1 = float( sub( 1.0, r ) ).toVar();
  36372. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  36373. } ).setLayout( {
  36374. name: 'mx_trilerp_0',
  36375. type: 'float',
  36376. inputs: [
  36377. { name: 'v0', type: 'float' },
  36378. { name: 'v1', type: 'float' },
  36379. { name: 'v2', type: 'float' },
  36380. { name: 'v3', type: 'float' },
  36381. { name: 'v4', type: 'float' },
  36382. { name: 'v5', type: 'float' },
  36383. { name: 'v6', type: 'float' },
  36384. { name: 'v7', type: 'float' },
  36385. { name: 's', type: 'float' },
  36386. { name: 't', type: 'float' },
  36387. { name: 'r', type: 'float' }
  36388. ]
  36389. } );
  36390. const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  36391. const r = float( r_immutable ).toVar();
  36392. const t = float( t_immutable ).toVar();
  36393. const s = float( s_immutable ).toVar();
  36394. const v7 = vec3( v7_immutable ).toVar();
  36395. const v6 = vec3( v6_immutable ).toVar();
  36396. const v5 = vec3( v5_immutable ).toVar();
  36397. const v4 = vec3( v4_immutable ).toVar();
  36398. const v3 = vec3( v3_immutable ).toVar();
  36399. const v2 = vec3( v2_immutable ).toVar();
  36400. const v1 = vec3( v1_immutable ).toVar();
  36401. const v0 = vec3( v0_immutable ).toVar();
  36402. const s1 = float( sub( 1.0, s ) ).toVar();
  36403. const t1 = float( sub( 1.0, t ) ).toVar();
  36404. const r1 = float( sub( 1.0, r ) ).toVar();
  36405. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  36406. } ).setLayout( {
  36407. name: 'mx_trilerp_1',
  36408. type: 'vec3',
  36409. inputs: [
  36410. { name: 'v0', type: 'vec3' },
  36411. { name: 'v1', type: 'vec3' },
  36412. { name: 'v2', type: 'vec3' },
  36413. { name: 'v3', type: 'vec3' },
  36414. { name: 'v4', type: 'vec3' },
  36415. { name: 'v5', type: 'vec3' },
  36416. { name: 'v6', type: 'vec3' },
  36417. { name: 'v7', type: 'vec3' },
  36418. { name: 's', type: 'float' },
  36419. { name: 't', type: 'float' },
  36420. { name: 'r', type: 'float' }
  36421. ]
  36422. } );
  36423. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  36424. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  36425. const y = float( y_immutable ).toVar();
  36426. const x = float( x_immutable ).toVar();
  36427. const hash = uint( hash_immutable ).toVar();
  36428. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  36429. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  36430. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  36431. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  36432. } ).setLayout( {
  36433. name: 'mx_gradient_float_0',
  36434. type: 'float',
  36435. inputs: [
  36436. { name: 'hash', type: 'uint' },
  36437. { name: 'x', type: 'float' },
  36438. { name: 'y', type: 'float' }
  36439. ]
  36440. } );
  36441. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  36442. const z = float( z_immutable ).toVar();
  36443. const y = float( y_immutable ).toVar();
  36444. const x = float( x_immutable ).toVar();
  36445. const hash = uint( hash_immutable ).toVar();
  36446. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  36447. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  36448. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  36449. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  36450. } ).setLayout( {
  36451. name: 'mx_gradient_float_1',
  36452. type: 'float',
  36453. inputs: [
  36454. { name: 'hash', type: 'uint' },
  36455. { name: 'x', type: 'float' },
  36456. { name: 'y', type: 'float' },
  36457. { name: 'z', type: 'float' }
  36458. ]
  36459. } );
  36460. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  36461. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  36462. const y = float( y_immutable ).toVar();
  36463. const x = float( x_immutable ).toVar();
  36464. const hash = uvec3( hash_immutable ).toVar();
  36465. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  36466. } ).setLayout( {
  36467. name: 'mx_gradient_vec3_0',
  36468. type: 'vec3',
  36469. inputs: [
  36470. { name: 'hash', type: 'uvec3' },
  36471. { name: 'x', type: 'float' },
  36472. { name: 'y', type: 'float' }
  36473. ]
  36474. } );
  36475. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  36476. const z = float( z_immutable ).toVar();
  36477. const y = float( y_immutable ).toVar();
  36478. const x = float( x_immutable ).toVar();
  36479. const hash = uvec3( hash_immutable ).toVar();
  36480. return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) );
  36481. } ).setLayout( {
  36482. name: 'mx_gradient_vec3_1',
  36483. type: 'vec3',
  36484. inputs: [
  36485. { name: 'hash', type: 'uvec3' },
  36486. { name: 'x', type: 'float' },
  36487. { name: 'y', type: 'float' },
  36488. { name: 'z', type: 'float' }
  36489. ]
  36490. } );
  36491. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  36492. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36493. const v = float( v_immutable ).toVar();
  36494. return mul( 0.6616, v );
  36495. } ).setLayout( {
  36496. name: 'mx_gradient_scale2d_0',
  36497. type: 'float',
  36498. inputs: [
  36499. { name: 'v', type: 'float' }
  36500. ]
  36501. } );
  36502. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36503. const v = float( v_immutable ).toVar();
  36504. return mul( 0.9820, v );
  36505. } ).setLayout( {
  36506. name: 'mx_gradient_scale3d_0',
  36507. type: 'float',
  36508. inputs: [
  36509. { name: 'v', type: 'float' }
  36510. ]
  36511. } );
  36512. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36513. const v = vec3( v_immutable ).toVar();
  36514. return mul( 0.6616, v );
  36515. } ).setLayout( {
  36516. name: 'mx_gradient_scale2d_1',
  36517. type: 'vec3',
  36518. inputs: [
  36519. { name: 'v', type: 'vec3' }
  36520. ]
  36521. } );
  36522. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  36523. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36524. const v = vec3( v_immutable ).toVar();
  36525. return mul( 0.9820, v );
  36526. } ).setLayout( {
  36527. name: 'mx_gradient_scale3d_1',
  36528. type: 'vec3',
  36529. inputs: [
  36530. { name: 'v', type: 'vec3' }
  36531. ]
  36532. } );
  36533. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  36534. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  36535. const k = int( k_immutable ).toVar();
  36536. const x = uint( x_immutable ).toVar();
  36537. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  36538. } ).setLayout( {
  36539. name: 'mx_rotl32',
  36540. type: 'uint',
  36541. inputs: [
  36542. { name: 'x', type: 'uint' },
  36543. { name: 'k', type: 'int' }
  36544. ]
  36545. } );
  36546. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  36547. a.subAssign( c );
  36548. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  36549. c.addAssign( b );
  36550. b.subAssign( a );
  36551. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  36552. a.addAssign( c );
  36553. c.subAssign( b );
  36554. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  36555. b.addAssign( a );
  36556. a.subAssign( c );
  36557. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  36558. c.addAssign( b );
  36559. b.subAssign( a );
  36560. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  36561. a.addAssign( c );
  36562. c.subAssign( b );
  36563. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  36564. b.addAssign( a );
  36565. } );
  36566. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  36567. const c = uint( c_immutable ).toVar();
  36568. const b = uint( b_immutable ).toVar();
  36569. const a = uint( a_immutable ).toVar();
  36570. c.bitXorAssign( b );
  36571. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  36572. a.bitXorAssign( c );
  36573. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  36574. b.bitXorAssign( a );
  36575. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  36576. c.bitXorAssign( b );
  36577. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  36578. a.bitXorAssign( c );
  36579. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  36580. b.bitXorAssign( a );
  36581. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  36582. c.bitXorAssign( b );
  36583. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  36584. return c;
  36585. } ).setLayout( {
  36586. name: 'mx_bjfinal',
  36587. type: 'uint',
  36588. inputs: [
  36589. { name: 'a', type: 'uint' },
  36590. { name: 'b', type: 'uint' },
  36591. { name: 'c', type: 'uint' }
  36592. ]
  36593. } );
  36594. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  36595. const bits = uint( bits_immutable ).toVar();
  36596. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  36597. } ).setLayout( {
  36598. name: 'mx_bits_to_01',
  36599. type: 'float',
  36600. inputs: [
  36601. { name: 'bits', type: 'uint' }
  36602. ]
  36603. } );
  36604. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  36605. const t = float( t_immutable ).toVar();
  36606. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  36607. } ).setLayout( {
  36608. name: 'mx_fade',
  36609. type: 'float',
  36610. inputs: [
  36611. { name: 't', type: 'float' }
  36612. ]
  36613. } );
  36614. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36615. const x = int( x_immutable ).toVar();
  36616. const len = uint( uint( 1 ) ).toVar();
  36617. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  36618. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  36619. } ).setLayout( {
  36620. name: 'mx_hash_int_0',
  36621. type: 'uint',
  36622. inputs: [
  36623. { name: 'x', type: 'int' }
  36624. ]
  36625. } );
  36626. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  36627. const y = int( y_immutable ).toVar();
  36628. const x = int( x_immutable ).toVar();
  36629. const len = uint( uint( 2 ) ).toVar();
  36630. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36631. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36632. a.addAssign( uint( x ) );
  36633. b.addAssign( uint( y ) );
  36634. return mx_bjfinal( a, b, c );
  36635. } ).setLayout( {
  36636. name: 'mx_hash_int_1',
  36637. type: 'uint',
  36638. inputs: [
  36639. { name: 'x', type: 'int' },
  36640. { name: 'y', type: 'int' }
  36641. ]
  36642. } );
  36643. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  36644. const z = int( z_immutable ).toVar();
  36645. const y = int( y_immutable ).toVar();
  36646. const x = int( x_immutable ).toVar();
  36647. const len = uint( uint( 3 ) ).toVar();
  36648. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36649. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36650. a.addAssign( uint( x ) );
  36651. b.addAssign( uint( y ) );
  36652. c.addAssign( uint( z ) );
  36653. return mx_bjfinal( a, b, c );
  36654. } ).setLayout( {
  36655. name: 'mx_hash_int_2',
  36656. type: 'uint',
  36657. inputs: [
  36658. { name: 'x', type: 'int' },
  36659. { name: 'y', type: 'int' },
  36660. { name: 'z', type: 'int' }
  36661. ]
  36662. } );
  36663. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  36664. const xx = int( xx_immutable ).toVar();
  36665. const z = int( z_immutable ).toVar();
  36666. const y = int( y_immutable ).toVar();
  36667. const x = int( x_immutable ).toVar();
  36668. const len = uint( uint( 4 ) ).toVar();
  36669. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36670. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36671. a.addAssign( uint( x ) );
  36672. b.addAssign( uint( y ) );
  36673. c.addAssign( uint( z ) );
  36674. mx_bjmix( a, b, c );
  36675. a.addAssign( uint( xx ) );
  36676. return mx_bjfinal( a, b, c );
  36677. } ).setLayout( {
  36678. name: 'mx_hash_int_3',
  36679. type: 'uint',
  36680. inputs: [
  36681. { name: 'x', type: 'int' },
  36682. { name: 'y', type: 'int' },
  36683. { name: 'z', type: 'int' },
  36684. { name: 'xx', type: 'int' }
  36685. ]
  36686. } );
  36687. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  36688. const yy = int( yy_immutable ).toVar();
  36689. const xx = int( xx_immutable ).toVar();
  36690. const z = int( z_immutable ).toVar();
  36691. const y = int( y_immutable ).toVar();
  36692. const x = int( x_immutable ).toVar();
  36693. const len = uint( uint( 5 ) ).toVar();
  36694. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36695. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36696. a.addAssign( uint( x ) );
  36697. b.addAssign( uint( y ) );
  36698. c.addAssign( uint( z ) );
  36699. mx_bjmix( a, b, c );
  36700. a.addAssign( uint( xx ) );
  36701. b.addAssign( uint( yy ) );
  36702. return mx_bjfinal( a, b, c );
  36703. } ).setLayout( {
  36704. name: 'mx_hash_int_4',
  36705. type: 'uint',
  36706. inputs: [
  36707. { name: 'x', type: 'int' },
  36708. { name: 'y', type: 'int' },
  36709. { name: 'z', type: 'int' },
  36710. { name: 'xx', type: 'int' },
  36711. { name: 'yy', type: 'int' }
  36712. ]
  36713. } );
  36714. const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] );
  36715. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  36716. const y = int( y_immutable ).toVar();
  36717. const x = int( x_immutable ).toVar();
  36718. const h = uint( mx_hash_int( x, y ) ).toVar();
  36719. const result = uvec3().toVar();
  36720. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  36721. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  36722. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  36723. return result;
  36724. } ).setLayout( {
  36725. name: 'mx_hash_vec3_0',
  36726. type: 'uvec3',
  36727. inputs: [
  36728. { name: 'x', type: 'int' },
  36729. { name: 'y', type: 'int' }
  36730. ]
  36731. } );
  36732. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  36733. const z = int( z_immutable ).toVar();
  36734. const y = int( y_immutable ).toVar();
  36735. const x = int( x_immutable ).toVar();
  36736. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  36737. const result = uvec3().toVar();
  36738. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  36739. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  36740. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  36741. return result;
  36742. } ).setLayout( {
  36743. name: 'mx_hash_vec3_1',
  36744. type: 'uvec3',
  36745. inputs: [
  36746. { name: 'x', type: 'int' },
  36747. { name: 'y', type: 'int' },
  36748. { name: 'z', type: 'int' }
  36749. ]
  36750. } );
  36751. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  36752. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36753. const p = vec2( p_immutable ).toVar();
  36754. const X = int().toVar(), Y = int().toVar();
  36755. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36756. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36757. const u = float( mx_fade( fx ) ).toVar();
  36758. const v = float( mx_fade( fy ) ).toVar();
  36759. const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  36760. return mx_gradient_scale2d( result );
  36761. } ).setLayout( {
  36762. name: 'mx_perlin_noise_float_0',
  36763. type: 'float',
  36764. inputs: [
  36765. { name: 'p', type: 'vec2' }
  36766. ]
  36767. } );
  36768. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36769. const p = vec3( p_immutable ).toVar();
  36770. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36771. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36772. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36773. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  36774. const u = float( mx_fade( fx ) ).toVar();
  36775. const v = float( mx_fade( fy ) ).toVar();
  36776. const w = float( mx_fade( fz ) ).toVar();
  36777. const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  36778. return mx_gradient_scale3d( result );
  36779. } ).setLayout( {
  36780. name: 'mx_perlin_noise_float_1',
  36781. type: 'float',
  36782. inputs: [
  36783. { name: 'p', type: 'vec3' }
  36784. ]
  36785. } );
  36786. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  36787. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36788. const p = vec2( p_immutable ).toVar();
  36789. const X = int().toVar(), Y = int().toVar();
  36790. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36791. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36792. const u = float( mx_fade( fx ) ).toVar();
  36793. const v = float( mx_fade( fy ) ).toVar();
  36794. const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  36795. return mx_gradient_scale2d( result );
  36796. } ).setLayout( {
  36797. name: 'mx_perlin_noise_vec3_0',
  36798. type: 'vec3',
  36799. inputs: [
  36800. { name: 'p', type: 'vec2' }
  36801. ]
  36802. } );
  36803. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36804. const p = vec3( p_immutable ).toVar();
  36805. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36806. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36807. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36808. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  36809. const u = float( mx_fade( fx ) ).toVar();
  36810. const v = float( mx_fade( fy ) ).toVar();
  36811. const w = float( mx_fade( fz ) ).toVar();
  36812. const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  36813. return mx_gradient_scale3d( result );
  36814. } ).setLayout( {
  36815. name: 'mx_perlin_noise_vec3_1',
  36816. type: 'vec3',
  36817. inputs: [
  36818. { name: 'p', type: 'vec3' }
  36819. ]
  36820. } );
  36821. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  36822. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36823. const p = float( p_immutable ).toVar();
  36824. const ix = int( mx_floor( p ) ).toVar();
  36825. return mx_bits_to_01( mx_hash_int( ix ) );
  36826. } ).setLayout( {
  36827. name: 'mx_cell_noise_float_0',
  36828. type: 'float',
  36829. inputs: [
  36830. { name: 'p', type: 'float' }
  36831. ]
  36832. } );
  36833. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36834. const p = vec2( p_immutable ).toVar();
  36835. const ix = int( mx_floor( p.x ) ).toVar();
  36836. const iy = int( mx_floor( p.y ) ).toVar();
  36837. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  36838. } ).setLayout( {
  36839. name: 'mx_cell_noise_float_1',
  36840. type: 'float',
  36841. inputs: [
  36842. { name: 'p', type: 'vec2' }
  36843. ]
  36844. } );
  36845. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36846. const p = vec3( p_immutable ).toVar();
  36847. const ix = int( mx_floor( p.x ) ).toVar();
  36848. const iy = int( mx_floor( p.y ) ).toVar();
  36849. const iz = int( mx_floor( p.z ) ).toVar();
  36850. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  36851. } ).setLayout( {
  36852. name: 'mx_cell_noise_float_2',
  36853. type: 'float',
  36854. inputs: [
  36855. { name: 'p', type: 'vec3' }
  36856. ]
  36857. } );
  36858. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36859. const p = vec4( p_immutable ).toVar();
  36860. const ix = int( mx_floor( p.x ) ).toVar();
  36861. const iy = int( mx_floor( p.y ) ).toVar();
  36862. const iz = int( mx_floor( p.z ) ).toVar();
  36863. const iw = int( mx_floor( p.w ) ).toVar();
  36864. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  36865. } ).setLayout( {
  36866. name: 'mx_cell_noise_float_3',
  36867. type: 'float',
  36868. inputs: [
  36869. { name: 'p', type: 'vec4' }
  36870. ]
  36871. } );
  36872. const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] );
  36873. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36874. const p = float( p_immutable ).toVar();
  36875. const ix = int( mx_floor( p ) ).toVar();
  36876. return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) );
  36877. } ).setLayout( {
  36878. name: 'mx_cell_noise_vec3_0',
  36879. type: 'vec3',
  36880. inputs: [
  36881. { name: 'p', type: 'float' }
  36882. ]
  36883. } );
  36884. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36885. const p = vec2( p_immutable ).toVar();
  36886. const ix = int( mx_floor( p.x ) ).toVar();
  36887. const iy = int( mx_floor( p.y ) ).toVar();
  36888. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) );
  36889. } ).setLayout( {
  36890. name: 'mx_cell_noise_vec3_1',
  36891. type: 'vec3',
  36892. inputs: [
  36893. { name: 'p', type: 'vec2' }
  36894. ]
  36895. } );
  36896. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36897. const p = vec3( p_immutable ).toVar();
  36898. const ix = int( mx_floor( p.x ) ).toVar();
  36899. const iy = int( mx_floor( p.y ) ).toVar();
  36900. const iz = int( mx_floor( p.z ) ).toVar();
  36901. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) );
  36902. } ).setLayout( {
  36903. name: 'mx_cell_noise_vec3_2',
  36904. type: 'vec3',
  36905. inputs: [
  36906. { name: 'p', type: 'vec3' }
  36907. ]
  36908. } );
  36909. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36910. const p = vec4( p_immutable ).toVar();
  36911. const ix = int( mx_floor( p.x ) ).toVar();
  36912. const iy = int( mx_floor( p.y ) ).toVar();
  36913. const iz = int( mx_floor( p.z ) ).toVar();
  36914. const iw = int( mx_floor( p.w ) ).toVar();
  36915. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) );
  36916. } ).setLayout( {
  36917. name: 'mx_cell_noise_vec3_3',
  36918. type: 'vec3',
  36919. inputs: [
  36920. { name: 'p', type: 'vec4' }
  36921. ]
  36922. } );
  36923. const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] );
  36924. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36925. const diminish = float( diminish_immutable ).toVar();
  36926. const lacunarity = float( lacunarity_immutable ).toVar();
  36927. const octaves = int( octaves_immutable ).toVar();
  36928. const p = vec3( p_immutable ).toVar();
  36929. const result = float( 0.0 ).toVar();
  36930. const amplitude = float( 1.0 ).toVar();
  36931. Loop( octaves, () => {
  36932. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  36933. amplitude.mulAssign( diminish );
  36934. p.mulAssign( lacunarity );
  36935. } );
  36936. return result;
  36937. } ).setLayout( {
  36938. name: 'mx_fractal_noise_float',
  36939. type: 'float',
  36940. inputs: [
  36941. { name: 'p', type: 'vec3' },
  36942. { name: 'octaves', type: 'int' },
  36943. { name: 'lacunarity', type: 'float' },
  36944. { name: 'diminish', type: 'float' }
  36945. ]
  36946. } );
  36947. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36948. const diminish = float( diminish_immutable ).toVar();
  36949. const lacunarity = float( lacunarity_immutable ).toVar();
  36950. const octaves = int( octaves_immutable ).toVar();
  36951. const p = vec3( p_immutable ).toVar();
  36952. const result = vec3( 0.0 ).toVar();
  36953. const amplitude = float( 1.0 ).toVar();
  36954. Loop( octaves, () => {
  36955. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  36956. amplitude.mulAssign( diminish );
  36957. p.mulAssign( lacunarity );
  36958. } );
  36959. return result;
  36960. } ).setLayout( {
  36961. name: 'mx_fractal_noise_vec3',
  36962. type: 'vec3',
  36963. inputs: [
  36964. { name: 'p', type: 'vec3' },
  36965. { name: 'octaves', type: 'int' },
  36966. { name: 'lacunarity', type: 'float' },
  36967. { name: 'diminish', type: 'float' }
  36968. ]
  36969. } );
  36970. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36971. const diminish = float( diminish_immutable ).toVar();
  36972. const lacunarity = float( lacunarity_immutable ).toVar();
  36973. const octaves = int( octaves_immutable ).toVar();
  36974. const p = vec3( p_immutable ).toVar();
  36975. return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) );
  36976. } ).setLayout( {
  36977. name: 'mx_fractal_noise_vec2',
  36978. type: 'vec2',
  36979. inputs: [
  36980. { name: 'p', type: 'vec3' },
  36981. { name: 'octaves', type: 'int' },
  36982. { name: 'lacunarity', type: 'float' },
  36983. { name: 'diminish', type: 'float' }
  36984. ]
  36985. } );
  36986. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36987. const diminish = float( diminish_immutable ).toVar();
  36988. const lacunarity = float( lacunarity_immutable ).toVar();
  36989. const octaves = int( octaves_immutable ).toVar();
  36990. const p = vec3( p_immutable ).toVar();
  36991. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  36992. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  36993. return vec4( c, f );
  36994. } ).setLayout( {
  36995. name: 'mx_fractal_noise_vec4',
  36996. type: 'vec4',
  36997. inputs: [
  36998. { name: 'p', type: 'vec3' },
  36999. { name: 'octaves', type: 'int' },
  37000. { name: 'lacunarity', type: 'float' },
  37001. { name: 'diminish', type: 'float' }
  37002. ]
  37003. } );
  37004. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  37005. const metric = int( metric_immutable ).toVar();
  37006. const jitter = float( jitter_immutable ).toVar();
  37007. const yoff = int( yoff_immutable ).toVar();
  37008. const xoff = int( xoff_immutable ).toVar();
  37009. const y = int( y_immutable ).toVar();
  37010. const x = int( x_immutable ).toVar();
  37011. const p = vec2( p_immutable ).toVar();
  37012. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  37013. const off = vec2( tmp.x, tmp.y ).toVar();
  37014. off.subAssign( 0.5 );
  37015. off.mulAssign( jitter );
  37016. off.addAssign( 0.5 );
  37017. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  37018. const diff = vec2( cellpos.sub( p ) ).toVar();
  37019. If( metric.equal( int( 2 ) ), () => {
  37020. return abs( diff.x ).add( abs( diff.y ) );
  37021. } );
  37022. If( metric.equal( int( 3 ) ), () => {
  37023. return max$1( abs( diff.x ), abs( diff.y ) );
  37024. } );
  37025. return dot( diff, diff );
  37026. } ).setLayout( {
  37027. name: 'mx_worley_distance_0',
  37028. type: 'float',
  37029. inputs: [
  37030. { name: 'p', type: 'vec2' },
  37031. { name: 'x', type: 'int' },
  37032. { name: 'y', type: 'int' },
  37033. { name: 'xoff', type: 'int' },
  37034. { name: 'yoff', type: 'int' },
  37035. { name: 'jitter', type: 'float' },
  37036. { name: 'metric', type: 'int' }
  37037. ]
  37038. } );
  37039. const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  37040. const metric = int( metric_immutable ).toVar();
  37041. const jitter = float( jitter_immutable ).toVar();
  37042. const zoff = int( zoff_immutable ).toVar();
  37043. const yoff = int( yoff_immutable ).toVar();
  37044. const xoff = int( xoff_immutable ).toVar();
  37045. const z = int( z_immutable ).toVar();
  37046. const y = int( y_immutable ).toVar();
  37047. const x = int( x_immutable ).toVar();
  37048. const p = vec3( p_immutable ).toVar();
  37049. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  37050. off.subAssign( 0.5 );
  37051. off.mulAssign( jitter );
  37052. off.addAssign( 0.5 );
  37053. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  37054. const diff = vec3( cellpos.sub( p ) ).toVar();
  37055. If( metric.equal( int( 2 ) ), () => {
  37056. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  37057. } );
  37058. If( metric.equal( int( 3 ) ), () => {
  37059. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  37060. } );
  37061. return dot( diff, diff );
  37062. } ).setLayout( {
  37063. name: 'mx_worley_distance_1',
  37064. type: 'float',
  37065. inputs: [
  37066. { name: 'p', type: 'vec3' },
  37067. { name: 'x', type: 'int' },
  37068. { name: 'y', type: 'int' },
  37069. { name: 'z', type: 'int' },
  37070. { name: 'xoff', type: 'int' },
  37071. { name: 'yoff', type: 'int' },
  37072. { name: 'zoff', type: 'int' },
  37073. { name: 'jitter', type: 'float' },
  37074. { name: 'metric', type: 'int' }
  37075. ]
  37076. } );
  37077. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  37078. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37079. const metric = int( metric_immutable ).toVar();
  37080. const jitter = float( jitter_immutable ).toVar();
  37081. const p = vec2( p_immutable ).toVar();
  37082. const X = int().toVar(), Y = int().toVar();
  37083. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  37084. const sqdist = float( 1e6 ).toVar();
  37085. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37086. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37087. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  37088. sqdist.assign( min$1( sqdist, dist ) );
  37089. } );
  37090. } );
  37091. If( metric.equal( int( 0 ) ), () => {
  37092. sqdist.assign( sqrt( sqdist ) );
  37093. } );
  37094. return sqdist;
  37095. } ).setLayout( {
  37096. name: 'mx_worley_noise_float_0',
  37097. type: 'float',
  37098. inputs: [
  37099. { name: 'p', type: 'vec2' },
  37100. { name: 'jitter', type: 'float' },
  37101. { name: 'metric', type: 'int' }
  37102. ]
  37103. } );
  37104. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37105. const metric = int( metric_immutable ).toVar();
  37106. const jitter = float( jitter_immutable ).toVar();
  37107. const p = vec2( p_immutable ).toVar();
  37108. const X = int().toVar(), Y = int().toVar();
  37109. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  37110. const sqdist = vec2( 1e6, 1e6 ).toVar();
  37111. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37112. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37113. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  37114. If( dist.lessThan( sqdist.x ), () => {
  37115. sqdist.y.assign( sqdist.x );
  37116. sqdist.x.assign( dist );
  37117. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37118. sqdist.y.assign( dist );
  37119. } );
  37120. } );
  37121. } );
  37122. If( metric.equal( int( 0 ) ), () => {
  37123. sqdist.assign( sqrt( sqdist ) );
  37124. } );
  37125. return sqdist;
  37126. } ).setLayout( {
  37127. name: 'mx_worley_noise_vec2_0',
  37128. type: 'vec2',
  37129. inputs: [
  37130. { name: 'p', type: 'vec2' },
  37131. { name: 'jitter', type: 'float' },
  37132. { name: 'metric', type: 'int' }
  37133. ]
  37134. } );
  37135. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37136. const metric = int( metric_immutable ).toVar();
  37137. const jitter = float( jitter_immutable ).toVar();
  37138. const p = vec2( p_immutable ).toVar();
  37139. const X = int().toVar(), Y = int().toVar();
  37140. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  37141. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  37142. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37143. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37144. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  37145. If( dist.lessThan( sqdist.x ), () => {
  37146. sqdist.z.assign( sqdist.y );
  37147. sqdist.y.assign( sqdist.x );
  37148. sqdist.x.assign( dist );
  37149. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37150. sqdist.z.assign( sqdist.y );
  37151. sqdist.y.assign( dist );
  37152. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  37153. sqdist.z.assign( dist );
  37154. } );
  37155. } );
  37156. } );
  37157. If( metric.equal( int( 0 ) ), () => {
  37158. sqdist.assign( sqrt( sqdist ) );
  37159. } );
  37160. return sqdist;
  37161. } ).setLayout( {
  37162. name: 'mx_worley_noise_vec3_0',
  37163. type: 'vec3',
  37164. inputs: [
  37165. { name: 'p', type: 'vec2' },
  37166. { name: 'jitter', type: 'float' },
  37167. { name: 'metric', type: 'int' }
  37168. ]
  37169. } );
  37170. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37171. const metric = int( metric_immutable ).toVar();
  37172. const jitter = float( jitter_immutable ).toVar();
  37173. const p = vec3( p_immutable ).toVar();
  37174. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  37175. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  37176. const sqdist = float( 1e6 ).toVar();
  37177. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37178. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37179. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  37180. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  37181. sqdist.assign( min$1( sqdist, dist ) );
  37182. } );
  37183. } );
  37184. } );
  37185. If( metric.equal( int( 0 ) ), () => {
  37186. sqdist.assign( sqrt( sqdist ) );
  37187. } );
  37188. return sqdist;
  37189. } ).setLayout( {
  37190. name: 'mx_worley_noise_float_1',
  37191. type: 'float',
  37192. inputs: [
  37193. { name: 'p', type: 'vec3' },
  37194. { name: 'jitter', type: 'float' },
  37195. { name: 'metric', type: 'int' }
  37196. ]
  37197. } );
  37198. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  37199. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37200. const metric = int( metric_immutable ).toVar();
  37201. const jitter = float( jitter_immutable ).toVar();
  37202. const p = vec3( p_immutable ).toVar();
  37203. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  37204. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  37205. const sqdist = vec2( 1e6, 1e6 ).toVar();
  37206. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37207. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37208. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  37209. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  37210. If( dist.lessThan( sqdist.x ), () => {
  37211. sqdist.y.assign( sqdist.x );
  37212. sqdist.x.assign( dist );
  37213. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37214. sqdist.y.assign( dist );
  37215. } );
  37216. } );
  37217. } );
  37218. } );
  37219. If( metric.equal( int( 0 ) ), () => {
  37220. sqdist.assign( sqrt( sqdist ) );
  37221. } );
  37222. return sqdist;
  37223. } ).setLayout( {
  37224. name: 'mx_worley_noise_vec2_1',
  37225. type: 'vec2',
  37226. inputs: [
  37227. { name: 'p', type: 'vec3' },
  37228. { name: 'jitter', type: 'float' },
  37229. { name: 'metric', type: 'int' }
  37230. ]
  37231. } );
  37232. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  37233. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37234. const metric = int( metric_immutable ).toVar();
  37235. const jitter = float( jitter_immutable ).toVar();
  37236. const p = vec3( p_immutable ).toVar();
  37237. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  37238. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  37239. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  37240. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37241. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37242. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  37243. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  37244. If( dist.lessThan( sqdist.x ), () => {
  37245. sqdist.z.assign( sqdist.y );
  37246. sqdist.y.assign( sqdist.x );
  37247. sqdist.x.assign( dist );
  37248. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37249. sqdist.z.assign( sqdist.y );
  37250. sqdist.y.assign( dist );
  37251. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  37252. sqdist.z.assign( dist );
  37253. } );
  37254. } );
  37255. } );
  37256. } );
  37257. If( metric.equal( int( 0 ) ), () => {
  37258. sqdist.assign( sqrt( sqdist ) );
  37259. } );
  37260. return sqdist;
  37261. } ).setLayout( {
  37262. name: 'mx_worley_noise_vec3_1',
  37263. type: 'vec3',
  37264. inputs: [
  37265. { name: 'p', type: 'vec3' },
  37266. { name: 'jitter', type: 'float' },
  37267. { name: 'metric', type: 'int' }
  37268. ]
  37269. } );
  37270. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  37271. // Three.js Transpiler
  37272. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  37273. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  37274. const s = hsv.y;
  37275. const v = hsv.z;
  37276. const result = vec3().toVar();
  37277. If( s.lessThan( 0.0001 ), () => {
  37278. result.assign( vec3( v, v, v ) );
  37279. } ).Else( () => {
  37280. let h = hsv.x;
  37281. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  37282. const hi = int( trunc( h ) );
  37283. const f = h.sub( float( hi ) );
  37284. const p = v.mul( s.oneMinus() );
  37285. const q = v.mul( s.mul( f ).oneMinus() );
  37286. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  37287. If( hi.equal( int( 0 ) ), () => {
  37288. result.assign( vec3( v, t, p ) );
  37289. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  37290. result.assign( vec3( q, v, p ) );
  37291. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  37292. result.assign( vec3( p, v, t ) );
  37293. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  37294. result.assign( vec3( p, q, v ) );
  37295. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  37296. result.assign( vec3( t, p, v ) );
  37297. } ).Else( () => {
  37298. result.assign( vec3( v, p, q ) );
  37299. } );
  37300. } );
  37301. return result;
  37302. } ).setLayout( {
  37303. name: 'mx_hsvtorgb',
  37304. type: 'vec3',
  37305. inputs: [
  37306. { name: 'hsv', type: 'vec3' }
  37307. ]
  37308. } );
  37309. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  37310. const c = vec3( c_immutable ).toVar();
  37311. const r = float( c.x ).toVar();
  37312. const g = float( c.y ).toVar();
  37313. const b = float( c.z ).toVar();
  37314. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  37315. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  37316. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  37317. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  37318. v.assign( maxcomp );
  37319. If( maxcomp.greaterThan( 0.0 ), () => {
  37320. s.assign( delta.div( maxcomp ) );
  37321. } ).Else( () => {
  37322. s.assign( 0.0 );
  37323. } );
  37324. If( s.lessThanEqual( 0.0 ), () => {
  37325. h.assign( 0.0 );
  37326. } ).Else( () => {
  37327. If( r.greaterThanEqual( maxcomp ), () => {
  37328. h.assign( g.sub( b ).div( delta ) );
  37329. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  37330. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  37331. } ).Else( () => {
  37332. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  37333. } );
  37334. h.mulAssign( 1.0 / 6.0 );
  37335. If( h.lessThan( 0.0 ), () => {
  37336. h.addAssign( 1.0 );
  37337. } );
  37338. } );
  37339. return vec3( h, s, v );
  37340. } ).setLayout( {
  37341. name: 'mx_rgbtohsv',
  37342. type: 'vec3',
  37343. inputs: [
  37344. { name: 'c', type: 'vec3' }
  37345. ]
  37346. } );
  37347. // Three.js Transpiler
  37348. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  37349. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  37350. const color = vec3( color_immutable ).toVar();
  37351. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  37352. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  37353. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  37354. return mix( linSeg, powSeg, isAbove );
  37355. } ).setLayout( {
  37356. name: 'mx_srgb_texture_to_lin_rec709',
  37357. type: 'vec3',
  37358. inputs: [
  37359. { name: 'color', type: 'vec3' }
  37360. ]
  37361. } );
  37362. const mx_aastep = ( threshold, value ) => {
  37363. threshold = float( threshold );
  37364. value = float( value );
  37365. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  37366. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  37367. };
  37368. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  37369. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  37370. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  37371. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  37372. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  37373. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  37374. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  37375. const mx_safepower = ( in1, in2 = 1 ) => {
  37376. in1 = float( in1 );
  37377. return in1.abs().pow( in2 ).mul( in1.sign() );
  37378. };
  37379. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  37380. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37381. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37382. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37383. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  37384. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  37385. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  37386. return noise_vec4.mul( amplitude ).add( pivot );
  37387. };
  37388. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37389. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37390. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37391. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  37392. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  37393. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  37394. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  37395. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  37396. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  37397. // normal is assumed to have unit length
  37398. const x = normal.x, y = normal.y, z = normal.z;
  37399. // band 0
  37400. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  37401. // band 1
  37402. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  37403. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  37404. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  37405. // band 2
  37406. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  37407. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  37408. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  37409. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  37410. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  37411. return result;
  37412. } );
  37413. class PointLightNode extends AnalyticLightNode {
  37414. static get type() {
  37415. return 'PointLightNode';
  37416. }
  37417. constructor( light = null ) {
  37418. super( light );
  37419. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37420. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37421. }
  37422. update( frame ) {
  37423. const { light } = this;
  37424. super.update( frame );
  37425. this.cutoffDistanceNode.value = light.distance;
  37426. this.decayExponentNode.value = light.decay;
  37427. }
  37428. setup( builder ) {
  37429. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37430. const lightingModel = builder.context.lightingModel;
  37431. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  37432. const lightDirection = lVector.normalize();
  37433. const lightDistance = lVector.length();
  37434. const lightAttenuation = getDistanceAttenuation( {
  37435. lightDistance,
  37436. cutoffDistance: cutoffDistanceNode,
  37437. decayExponent: decayExponentNode
  37438. } );
  37439. const lightColor = colorNode.mul( lightAttenuation );
  37440. const reflectedLight = builder.context.reflectedLight;
  37441. lightingModel.direct( {
  37442. lightDirection,
  37443. lightColor,
  37444. reflectedLight
  37445. }, builder.stack, builder );
  37446. }
  37447. }
  37448. class DirectionalLightNode extends AnalyticLightNode {
  37449. static get type() {
  37450. return 'DirectionalLightNode';
  37451. }
  37452. constructor( light = null ) {
  37453. super( light );
  37454. }
  37455. setup( builder ) {
  37456. super.setup( builder );
  37457. const lightingModel = builder.context.lightingModel;
  37458. const lightColor = this.colorNode;
  37459. const lightDirection = lightTargetDirection( this.light );
  37460. const reflectedLight = builder.context.reflectedLight;
  37461. lightingModel.direct( {
  37462. lightDirection,
  37463. lightColor,
  37464. reflectedLight
  37465. }, builder.stack, builder );
  37466. }
  37467. }
  37468. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37469. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37470. let ltcLib = null;
  37471. class RectAreaLightNode extends AnalyticLightNode {
  37472. static get type() {
  37473. return 'RectAreaLightNode';
  37474. }
  37475. constructor( light = null ) {
  37476. super( light );
  37477. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37478. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37479. }
  37480. update( frame ) {
  37481. super.update( frame );
  37482. const { light } = this;
  37483. const viewMatrix = frame.camera.matrixWorldInverse;
  37484. _matrix42.identity();
  37485. _matrix41.copy( light.matrixWorld );
  37486. _matrix41.premultiply( viewMatrix );
  37487. _matrix42.extractRotation( _matrix41 );
  37488. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37489. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37490. this.halfWidth.value.applyMatrix4( _matrix42 );
  37491. this.halfHeight.value.applyMatrix4( _matrix42 );
  37492. }
  37493. setup( builder ) {
  37494. super.setup( builder );
  37495. let ltc_1, ltc_2;
  37496. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37497. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  37498. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  37499. } else {
  37500. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  37501. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  37502. }
  37503. const { colorNode, light } = this;
  37504. const lightingModel = builder.context.lightingModel;
  37505. const lightPosition = lightViewPosition( light );
  37506. const reflectedLight = builder.context.reflectedLight;
  37507. lightingModel.directRectArea( {
  37508. lightColor: colorNode,
  37509. lightPosition,
  37510. halfWidth: this.halfWidth,
  37511. halfHeight: this.halfHeight,
  37512. reflectedLight,
  37513. ltc_1,
  37514. ltc_2
  37515. }, builder.stack, builder );
  37516. }
  37517. static setLTC( ltc ) {
  37518. ltcLib = ltc;
  37519. }
  37520. }
  37521. class SpotLightNode extends AnalyticLightNode {
  37522. static get type() {
  37523. return 'SpotLightNode';
  37524. }
  37525. constructor( light = null ) {
  37526. super( light );
  37527. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37528. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37529. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37530. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37531. }
  37532. update( frame ) {
  37533. super.update( frame );
  37534. const { light } = this;
  37535. this.coneCosNode.value = Math.cos( light.angle );
  37536. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  37537. this.cutoffDistanceNode.value = light.distance;
  37538. this.decayExponentNode.value = light.decay;
  37539. }
  37540. getSpotAttenuation( angleCosine ) {
  37541. const { coneCosNode, penumbraCosNode } = this;
  37542. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  37543. }
  37544. setup( builder ) {
  37545. super.setup( builder );
  37546. const lightingModel = builder.context.lightingModel;
  37547. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37548. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  37549. const lightDirection = lVector.normalize();
  37550. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  37551. const spotAttenuation = this.getSpotAttenuation( angleCos );
  37552. const lightDistance = lVector.length();
  37553. const lightAttenuation = getDistanceAttenuation( {
  37554. lightDistance,
  37555. cutoffDistance: cutoffDistanceNode,
  37556. decayExponent: decayExponentNode
  37557. } );
  37558. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  37559. const reflectedLight = builder.context.reflectedLight;
  37560. lightingModel.direct( {
  37561. lightDirection,
  37562. lightColor,
  37563. reflectedLight
  37564. }, builder.stack, builder );
  37565. }
  37566. }
  37567. class IESSpotLightNode extends SpotLightNode {
  37568. static get type() {
  37569. return 'IESSpotLightNode';
  37570. }
  37571. getSpotAttenuation( angleCosine ) {
  37572. const iesMap = this.light.iesMap;
  37573. let spotAttenuation = null;
  37574. if ( iesMap && iesMap.isTexture === true ) {
  37575. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  37576. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  37577. } else {
  37578. spotAttenuation = super.getSpotAttenuation( angleCosine );
  37579. }
  37580. return spotAttenuation;
  37581. }
  37582. }
  37583. class AmbientLightNode extends AnalyticLightNode {
  37584. static get type() {
  37585. return 'AmbientLightNode';
  37586. }
  37587. constructor( light = null ) {
  37588. super( light );
  37589. }
  37590. setup( { context } ) {
  37591. context.irradiance.addAssign( this.colorNode );
  37592. }
  37593. }
  37594. class HemisphereLightNode extends AnalyticLightNode {
  37595. static get type() {
  37596. return 'HemisphereLightNode';
  37597. }
  37598. constructor( light = null ) {
  37599. super( light );
  37600. this.lightPositionNode = lightPosition( light );
  37601. this.lightDirectionNode = this.lightPositionNode.normalize();
  37602. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  37603. }
  37604. update( frame ) {
  37605. const { light } = this;
  37606. super.update( frame );
  37607. this.lightPositionNode.object3d = light;
  37608. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  37609. }
  37610. setup( builder ) {
  37611. const { colorNode, groundColorNode, lightDirectionNode } = this;
  37612. const dotNL = normalView.dot( lightDirectionNode );
  37613. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  37614. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  37615. builder.context.irradiance.addAssign( irradiance );
  37616. }
  37617. }
  37618. class LightProbeNode extends AnalyticLightNode {
  37619. static get type() {
  37620. return 'LightProbeNode';
  37621. }
  37622. constructor( light = null ) {
  37623. super( light );
  37624. const array = [];
  37625. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  37626. this.lightProbe = uniformArray( array );
  37627. }
  37628. update( frame ) {
  37629. const { light } = this;
  37630. super.update( frame );
  37631. //
  37632. for ( let i = 0; i < 9; i ++ ) {
  37633. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  37634. }
  37635. }
  37636. setup( builder ) {
  37637. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37638. builder.context.irradiance.addAssign( irradiance );
  37639. }
  37640. }
  37641. class NodeParser {
  37642. parseFunction( /*source*/ ) {
  37643. console.warn( 'Abstract function.' );
  37644. }
  37645. }
  37646. class NodeFunction {
  37647. constructor( type, inputs, name = '', precision = '' ) {
  37648. this.type = type;
  37649. this.inputs = inputs;
  37650. this.name = name;
  37651. this.precision = precision;
  37652. }
  37653. getCode( /*name = this.name*/ ) {
  37654. console.warn( 'Abstract function.' );
  37655. }
  37656. }
  37657. NodeFunction.isNodeFunction = true;
  37658. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  37659. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  37660. const pragmaMain = '#pragma main';
  37661. const parse$1 = ( source ) => {
  37662. source = source.trim();
  37663. const pragmaMainIndex = source.indexOf( pragmaMain );
  37664. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  37665. const declaration = mainCode.match( declarationRegexp$1 );
  37666. if ( declaration !== null && declaration.length === 5 ) {
  37667. // tokenizer
  37668. const inputsCode = declaration[ 4 ];
  37669. const propsMatches = [];
  37670. let nameMatch = null;
  37671. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  37672. propsMatches.push( nameMatch );
  37673. }
  37674. // parser
  37675. const inputs = [];
  37676. let i = 0;
  37677. while ( i < propsMatches.length ) {
  37678. const isConst = propsMatches[ i ][ 0 ] === 'const';
  37679. if ( isConst === true ) {
  37680. i ++;
  37681. }
  37682. let qualifier = propsMatches[ i ][ 0 ];
  37683. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  37684. i ++;
  37685. } else {
  37686. qualifier = '';
  37687. }
  37688. const type = propsMatches[ i ++ ][ 0 ];
  37689. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  37690. if ( Number.isNaN( count ) === false ) i ++;
  37691. else count = null;
  37692. const name = propsMatches[ i ++ ][ 0 ];
  37693. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  37694. }
  37695. //
  37696. const blockCode = mainCode.substring( declaration[ 0 ].length );
  37697. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  37698. const type = declaration[ 2 ];
  37699. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  37700. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  37701. return {
  37702. type,
  37703. inputs,
  37704. name,
  37705. precision,
  37706. inputsCode,
  37707. blockCode,
  37708. headerCode
  37709. };
  37710. } else {
  37711. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  37712. }
  37713. };
  37714. class GLSLNodeFunction extends NodeFunction {
  37715. constructor( source ) {
  37716. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  37717. super( type, inputs, name, precision );
  37718. this.inputsCode = inputsCode;
  37719. this.blockCode = blockCode;
  37720. this.headerCode = headerCode;
  37721. }
  37722. getCode( name = this.name ) {
  37723. let code;
  37724. const blockCode = this.blockCode;
  37725. if ( blockCode !== '' ) {
  37726. const { type, inputsCode, headerCode, precision } = this;
  37727. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  37728. if ( precision !== '' ) {
  37729. declarationCode = `${ precision } ${ declarationCode }`;
  37730. }
  37731. code = headerCode + declarationCode + blockCode;
  37732. } else {
  37733. // interface function
  37734. code = '';
  37735. }
  37736. return code;
  37737. }
  37738. }
  37739. class GLSLNodeParser extends NodeParser {
  37740. parseFunction( source ) {
  37741. return new GLSLNodeFunction( source );
  37742. }
  37743. }
  37744. function painterSortStable( a, b ) {
  37745. if ( a.groupOrder !== b.groupOrder ) {
  37746. return a.groupOrder - b.groupOrder;
  37747. } else if ( a.renderOrder !== b.renderOrder ) {
  37748. return a.renderOrder - b.renderOrder;
  37749. } else if ( a.material.id !== b.material.id ) {
  37750. return a.material.id - b.material.id;
  37751. } else if ( a.z !== b.z ) {
  37752. return a.z - b.z;
  37753. } else {
  37754. return a.id - b.id;
  37755. }
  37756. }
  37757. function reversePainterSortStable( a, b ) {
  37758. if ( a.groupOrder !== b.groupOrder ) {
  37759. return a.groupOrder - b.groupOrder;
  37760. } else if ( a.renderOrder !== b.renderOrder ) {
  37761. return a.renderOrder - b.renderOrder;
  37762. } else if ( a.z !== b.z ) {
  37763. return b.z - a.z;
  37764. } else {
  37765. return a.id - b.id;
  37766. }
  37767. }
  37768. class RenderList {
  37769. constructor() {
  37770. this.renderItems = [];
  37771. this.renderItemsIndex = 0;
  37772. this.opaque = [];
  37773. this.transparent = [];
  37774. this.bundles = [];
  37775. this.lightsNode = new LightsNode( [] );
  37776. this.lightsArray = [];
  37777. this.occlusionQueryCount = 0;
  37778. }
  37779. begin() {
  37780. this.renderItemsIndex = 0;
  37781. this.opaque.length = 0;
  37782. this.transparent.length = 0;
  37783. this.bundles.length = 0;
  37784. this.lightsArray.length = 0;
  37785. this.occlusionQueryCount = 0;
  37786. return this;
  37787. }
  37788. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  37789. let renderItem = this.renderItems[ this.renderItemsIndex ];
  37790. if ( renderItem === undefined ) {
  37791. renderItem = {
  37792. id: object.id,
  37793. object: object,
  37794. geometry: geometry,
  37795. material: material,
  37796. groupOrder: groupOrder,
  37797. renderOrder: object.renderOrder,
  37798. z: z,
  37799. group: group
  37800. };
  37801. this.renderItems[ this.renderItemsIndex ] = renderItem;
  37802. } else {
  37803. renderItem.id = object.id;
  37804. renderItem.object = object;
  37805. renderItem.geometry = geometry;
  37806. renderItem.material = material;
  37807. renderItem.groupOrder = groupOrder;
  37808. renderItem.renderOrder = object.renderOrder;
  37809. renderItem.z = z;
  37810. renderItem.group = group;
  37811. }
  37812. this.renderItemsIndex ++;
  37813. return renderItem;
  37814. }
  37815. push( object, geometry, material, groupOrder, z, group ) {
  37816. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  37817. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  37818. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  37819. }
  37820. unshift( object, geometry, material, groupOrder, z, group ) {
  37821. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  37822. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  37823. }
  37824. pushBundle( group ) {
  37825. this.bundles.push( group );
  37826. }
  37827. pushLight( light ) {
  37828. this.lightsArray.push( light );
  37829. }
  37830. getLightsNode() {
  37831. return this.lightsNode.fromLights( this.lightsArray );
  37832. }
  37833. sort( customOpaqueSort, customTransparentSort ) {
  37834. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  37835. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  37836. }
  37837. finish() {
  37838. // update lights
  37839. this.lightsNode.setLights( this.lightsArray );
  37840. // Clear references from inactive renderItems in the list
  37841. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  37842. const renderItem = this.renderItems[ i ];
  37843. if ( renderItem.id === null ) break;
  37844. renderItem.id = null;
  37845. renderItem.object = null;
  37846. renderItem.geometry = null;
  37847. renderItem.material = null;
  37848. renderItem.groupOrder = null;
  37849. renderItem.renderOrder = null;
  37850. renderItem.z = null;
  37851. renderItem.group = null;
  37852. }
  37853. }
  37854. }
  37855. class RenderLists {
  37856. constructor() {
  37857. this.lists = new ChainMap();
  37858. }
  37859. get( scene, camera ) {
  37860. const lists = this.lists;
  37861. const keys = [ scene, camera ];
  37862. let list = lists.get( keys );
  37863. if ( list === undefined ) {
  37864. list = new RenderList();
  37865. lists.set( keys, list );
  37866. }
  37867. return list;
  37868. }
  37869. dispose() {
  37870. this.lists = new ChainMap();
  37871. }
  37872. }
  37873. let id = 0;
  37874. class RenderContext {
  37875. constructor() {
  37876. this.id = id ++;
  37877. this.color = true;
  37878. this.clearColor = true;
  37879. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  37880. this.depth = true;
  37881. this.clearDepth = true;
  37882. this.clearDepthValue = 1;
  37883. this.stencil = false;
  37884. this.clearStencil = true;
  37885. this.clearStencilValue = 1;
  37886. this.viewport = false;
  37887. this.viewportValue = new Vector4();
  37888. this.scissor = false;
  37889. this.scissorValue = new Vector4();
  37890. this.textures = null;
  37891. this.depthTexture = null;
  37892. this.activeCubeFace = 0;
  37893. this.sampleCount = 1;
  37894. this.width = 0;
  37895. this.height = 0;
  37896. this.isRenderContext = true;
  37897. }
  37898. getCacheKey() {
  37899. return getCacheKey( this );
  37900. }
  37901. }
  37902. function getCacheKey( renderContext ) {
  37903. const { textures, activeCubeFace } = renderContext;
  37904. const values = [ activeCubeFace ];
  37905. for ( const texture of textures ) {
  37906. values.push( texture.id );
  37907. }
  37908. return hashArray( values );
  37909. }
  37910. class RenderContexts {
  37911. constructor() {
  37912. this.chainMaps = {};
  37913. }
  37914. get( scene, camera, renderTarget = null ) {
  37915. const chainKey = [ scene, camera ];
  37916. let attachmentState;
  37917. if ( renderTarget === null ) {
  37918. attachmentState = 'default';
  37919. } else {
  37920. const format = renderTarget.texture.format;
  37921. const count = renderTarget.textures.length;
  37922. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  37923. }
  37924. const chainMap = this.getChainMap( attachmentState );
  37925. let renderState = chainMap.get( chainKey );
  37926. if ( renderState === undefined ) {
  37927. renderState = new RenderContext();
  37928. chainMap.set( chainKey, renderState );
  37929. }
  37930. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  37931. return renderState;
  37932. }
  37933. getChainMap( attachmentState ) {
  37934. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  37935. }
  37936. dispose() {
  37937. this.chainMaps = {};
  37938. }
  37939. }
  37940. const _size = /*@__PURE__*/ new Vector3();
  37941. class Textures extends DataMap {
  37942. constructor( renderer, backend, info ) {
  37943. super();
  37944. this.renderer = renderer;
  37945. this.backend = backend;
  37946. this.info = info;
  37947. }
  37948. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  37949. const renderTargetData = this.get( renderTarget );
  37950. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  37951. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  37952. const textures = renderTarget.textures;
  37953. const size = this.getSize( textures[ 0 ] );
  37954. const mipWidth = size.width >> activeMipmapLevel;
  37955. const mipHeight = size.height >> activeMipmapLevel;
  37956. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  37957. let textureNeedsUpdate = false;
  37958. if ( depthTexture === undefined ) {
  37959. depthTexture = new DepthTexture();
  37960. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  37961. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  37962. depthTexture.image.width = mipWidth;
  37963. depthTexture.image.height = mipHeight;
  37964. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  37965. }
  37966. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  37967. textureNeedsUpdate = true;
  37968. depthTexture.needsUpdate = true;
  37969. depthTexture.image.width = mipWidth;
  37970. depthTexture.image.height = mipHeight;
  37971. }
  37972. renderTargetData.width = size.width;
  37973. renderTargetData.height = size.height;
  37974. renderTargetData.textures = textures;
  37975. renderTargetData.depthTexture = depthTexture;
  37976. renderTargetData.depth = renderTarget.depthBuffer;
  37977. renderTargetData.stencil = renderTarget.stencilBuffer;
  37978. renderTargetData.renderTarget = renderTarget;
  37979. if ( renderTargetData.sampleCount !== sampleCount ) {
  37980. textureNeedsUpdate = true;
  37981. depthTexture.needsUpdate = true;
  37982. renderTargetData.sampleCount = sampleCount;
  37983. }
  37984. //
  37985. const options = { sampleCount };
  37986. for ( let i = 0; i < textures.length; i ++ ) {
  37987. const texture = textures[ i ];
  37988. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  37989. this.updateTexture( texture, options );
  37990. }
  37991. this.updateTexture( depthTexture, options );
  37992. // dispose handler
  37993. if ( renderTargetData.initialized !== true ) {
  37994. renderTargetData.initialized = true;
  37995. // dispose
  37996. const onDispose = () => {
  37997. renderTarget.removeEventListener( 'dispose', onDispose );
  37998. for ( let i = 0; i < textures.length; i ++ ) {
  37999. this._destroyTexture( textures[ i ] );
  38000. }
  38001. this._destroyTexture( depthTexture );
  38002. this.delete( renderTarget );
  38003. };
  38004. renderTarget.addEventListener( 'dispose', onDispose );
  38005. }
  38006. }
  38007. updateTexture( texture, options = {} ) {
  38008. const textureData = this.get( texture );
  38009. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  38010. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  38011. const backend = this.backend;
  38012. if ( isRenderTarget && textureData.initialized === true ) {
  38013. // it's an update
  38014. backend.destroySampler( texture );
  38015. backend.destroyTexture( texture );
  38016. }
  38017. //
  38018. if ( texture.isFramebufferTexture ) {
  38019. const renderer = this.renderer;
  38020. const renderTarget = renderer.getRenderTarget();
  38021. if ( renderTarget ) {
  38022. texture.type = renderTarget.texture.type;
  38023. } else {
  38024. texture.type = UnsignedByteType;
  38025. }
  38026. }
  38027. //
  38028. const { width, height, depth } = this.getSize( texture );
  38029. options.width = width;
  38030. options.height = height;
  38031. options.depth = depth;
  38032. options.needsMipmaps = this.needsMipmaps( texture );
  38033. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  38034. //
  38035. if ( isRenderTarget || texture.isStorageTexture === true ) {
  38036. backend.createSampler( texture );
  38037. backend.createTexture( texture, options );
  38038. textureData.generation = texture.version;
  38039. } else {
  38040. const needsCreate = textureData.initialized !== true;
  38041. if ( needsCreate ) backend.createSampler( texture );
  38042. if ( texture.version > 0 ) {
  38043. const image = texture.image;
  38044. if ( image === undefined ) {
  38045. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  38046. } else if ( image.complete === false ) {
  38047. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  38048. } else {
  38049. if ( texture.images ) {
  38050. const images = [];
  38051. for ( const image of texture.images ) {
  38052. images.push( image );
  38053. }
  38054. options.images = images;
  38055. } else {
  38056. options.image = image;
  38057. }
  38058. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  38059. backend.createTexture( texture, options );
  38060. textureData.isDefaultTexture = false;
  38061. textureData.generation = texture.version;
  38062. }
  38063. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  38064. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  38065. }
  38066. } else {
  38067. // async update
  38068. backend.createDefaultTexture( texture );
  38069. textureData.isDefaultTexture = true;
  38070. textureData.generation = texture.version;
  38071. }
  38072. }
  38073. // dispose handler
  38074. if ( textureData.initialized !== true ) {
  38075. textureData.initialized = true;
  38076. textureData.generation = texture.version;
  38077. //
  38078. this.info.memory.textures ++;
  38079. // dispose
  38080. const onDispose = () => {
  38081. texture.removeEventListener( 'dispose', onDispose );
  38082. this._destroyTexture( texture );
  38083. this.info.memory.textures --;
  38084. };
  38085. texture.addEventListener( 'dispose', onDispose );
  38086. }
  38087. //
  38088. textureData.version = texture.version;
  38089. }
  38090. getSize( texture, target = _size ) {
  38091. let image = texture.images ? texture.images[ 0 ] : texture.image;
  38092. if ( image ) {
  38093. if ( image.image !== undefined ) image = image.image;
  38094. target.width = image.width;
  38095. target.height = image.height;
  38096. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  38097. } else {
  38098. target.width = target.height = target.depth = 1;
  38099. }
  38100. return target;
  38101. }
  38102. getMipLevels( texture, width, height ) {
  38103. let mipLevelCount;
  38104. if ( texture.isCompressedTexture ) {
  38105. mipLevelCount = texture.mipmaps.length;
  38106. } else {
  38107. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  38108. }
  38109. return mipLevelCount;
  38110. }
  38111. needsMipmaps( texture ) {
  38112. if ( this.isEnvironmentTexture( texture ) ) return true;
  38113. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  38114. }
  38115. isEnvironmentTexture( texture ) {
  38116. const mapping = texture.mapping;
  38117. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  38118. }
  38119. _destroyTexture( texture ) {
  38120. this.backend.destroySampler( texture );
  38121. this.backend.destroyTexture( texture );
  38122. this.delete( texture );
  38123. }
  38124. }
  38125. class Color4 extends Color {
  38126. constructor( r, g, b, a = 1 ) {
  38127. super( r, g, b );
  38128. this.a = a;
  38129. }
  38130. set( r, g, b, a = 1 ) {
  38131. this.a = a;
  38132. return super.set( r, g, b );
  38133. }
  38134. copy( color ) {
  38135. if ( color.a !== undefined ) this.a = color.a;
  38136. return super.copy( color );
  38137. }
  38138. clone() {
  38139. return new this.constructor( this.r, this.g, this.b, this.a );
  38140. }
  38141. }
  38142. const _clearColor = /*@__PURE__*/ new Color4();
  38143. class Background extends DataMap {
  38144. constructor( renderer, nodes ) {
  38145. super();
  38146. this.renderer = renderer;
  38147. this.nodes = nodes;
  38148. }
  38149. update( scene, renderList, renderContext ) {
  38150. const renderer = this.renderer;
  38151. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  38152. let forceClear = false;
  38153. if ( background === null ) {
  38154. // no background settings, use clear color configuration from the renderer
  38155. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  38156. _clearColor.a = renderer._clearColor.a;
  38157. } else if ( background.isColor === true ) {
  38158. // background is an opaque color
  38159. background.getRGB( _clearColor, LinearSRGBColorSpace );
  38160. _clearColor.a = 1;
  38161. forceClear = true;
  38162. } else if ( background.isNode === true ) {
  38163. const sceneData = this.get( scene );
  38164. const backgroundNode = background;
  38165. _clearColor.copy( renderer._clearColor );
  38166. let backgroundMesh = sceneData.backgroundMesh;
  38167. if ( backgroundMesh === undefined ) {
  38168. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  38169. // @TODO: Add Texture2D support using node context
  38170. getUV: () => normalWorld,
  38171. getTextureLevel: () => backgroundBlurriness
  38172. } );
  38173. let viewProj = modelViewProjection();
  38174. viewProj = viewProj.setZ( viewProj.w );
  38175. const nodeMaterial = new NodeMaterial();
  38176. nodeMaterial.name = 'Background.material';
  38177. nodeMaterial.side = BackSide;
  38178. nodeMaterial.depthTest = false;
  38179. nodeMaterial.depthWrite = false;
  38180. nodeMaterial.fog = false;
  38181. nodeMaterial.lights = false;
  38182. nodeMaterial.vertexNode = viewProj;
  38183. nodeMaterial.colorNode = backgroundMeshNode;
  38184. sceneData.backgroundMeshNode = backgroundMeshNode;
  38185. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  38186. backgroundMesh.frustumCulled = false;
  38187. backgroundMesh.name = 'Background.mesh';
  38188. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  38189. this.matrixWorld.copyPosition( camera.matrixWorld );
  38190. };
  38191. }
  38192. const backgroundCacheKey = backgroundNode.getCacheKey();
  38193. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  38194. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  38195. sceneData.backgroundMeshNode.needsUpdate = true;
  38196. backgroundMesh.material.needsUpdate = true;
  38197. sceneData.backgroundCacheKey = backgroundCacheKey;
  38198. }
  38199. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  38200. } else {
  38201. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  38202. }
  38203. //
  38204. if ( renderer.autoClear === true || forceClear === true ) {
  38205. _clearColor.multiplyScalar( _clearColor.a );
  38206. const clearColorValue = renderContext.clearColorValue;
  38207. clearColorValue.r = _clearColor.r;
  38208. clearColorValue.g = _clearColor.g;
  38209. clearColorValue.b = _clearColor.b;
  38210. clearColorValue.a = _clearColor.a;
  38211. renderContext.depthClearValue = renderer._clearDepth;
  38212. renderContext.stencilClearValue = renderer._clearStencil;
  38213. renderContext.clearColor = renderer.autoClearColor === true;
  38214. renderContext.clearDepth = renderer.autoClearDepth === true;
  38215. renderContext.clearStencil = renderer.autoClearStencil === true;
  38216. } else {
  38217. renderContext.clearColor = false;
  38218. renderContext.clearDepth = false;
  38219. renderContext.clearStencil = false;
  38220. }
  38221. }
  38222. }
  38223. class NodeBuilderState {
  38224. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  38225. this.vertexShader = vertexShader;
  38226. this.fragmentShader = fragmentShader;
  38227. this.computeShader = computeShader;
  38228. this.transforms = transforms;
  38229. this.nodeAttributes = nodeAttributes;
  38230. this.bindings = bindings;
  38231. this.updateNodes = updateNodes;
  38232. this.updateBeforeNodes = updateBeforeNodes;
  38233. this.updateAfterNodes = updateAfterNodes;
  38234. this.monitor = monitor;
  38235. this.usedTimes = 0;
  38236. }
  38237. createBindings() {
  38238. const bindings = [];
  38239. for ( const instanceGroup of this.bindings ) {
  38240. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  38241. if ( shared !== true ) {
  38242. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  38243. bindings.push( bindingsGroup );
  38244. for ( const instanceBinding of instanceGroup.bindings ) {
  38245. bindingsGroup.bindings.push( instanceBinding.clone() );
  38246. }
  38247. } else {
  38248. bindings.push( instanceGroup );
  38249. }
  38250. }
  38251. return bindings;
  38252. }
  38253. }
  38254. const outputNodeMap = new WeakMap();
  38255. class Nodes extends DataMap {
  38256. constructor( renderer, backend ) {
  38257. super();
  38258. this.renderer = renderer;
  38259. this.backend = backend;
  38260. this.nodeFrame = new NodeFrame();
  38261. this.nodeBuilderCache = new Map();
  38262. this.callHashCache = new ChainMap();
  38263. this.groupsData = new ChainMap();
  38264. }
  38265. updateGroup( nodeUniformsGroup ) {
  38266. const groupNode = nodeUniformsGroup.groupNode;
  38267. const name = groupNode.name;
  38268. // objectGroup is every updated
  38269. if ( name === objectGroup.name ) return true;
  38270. // renderGroup is updated once per render/compute call
  38271. if ( name === renderGroup.name ) {
  38272. const uniformsGroupData = this.get( nodeUniformsGroup );
  38273. const renderId = this.nodeFrame.renderId;
  38274. if ( uniformsGroupData.renderId !== renderId ) {
  38275. uniformsGroupData.renderId = renderId;
  38276. return true;
  38277. }
  38278. return false;
  38279. }
  38280. // frameGroup is updated once per frame
  38281. if ( name === frameGroup.name ) {
  38282. const uniformsGroupData = this.get( nodeUniformsGroup );
  38283. const frameId = this.nodeFrame.frameId;
  38284. if ( uniformsGroupData.frameId !== frameId ) {
  38285. uniformsGroupData.frameId = frameId;
  38286. return true;
  38287. }
  38288. return false;
  38289. }
  38290. // other groups are updated just when groupNode.needsUpdate is true
  38291. const groupChain = [ groupNode, nodeUniformsGroup ];
  38292. let groupData = this.groupsData.get( groupChain );
  38293. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  38294. if ( groupData.version !== groupNode.version ) {
  38295. groupData.version = groupNode.version;
  38296. return true;
  38297. }
  38298. return false;
  38299. }
  38300. getForRenderCacheKey( renderObject ) {
  38301. return renderObject.initialCacheKey;
  38302. }
  38303. getForRender( renderObject ) {
  38304. const renderObjectData = this.get( renderObject );
  38305. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38306. if ( nodeBuilderState === undefined ) {
  38307. const { nodeBuilderCache } = this;
  38308. const cacheKey = this.getForRenderCacheKey( renderObject );
  38309. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38310. if ( nodeBuilderState === undefined ) {
  38311. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38312. nodeBuilder.scene = renderObject.scene;
  38313. nodeBuilder.material = renderObject.material;
  38314. nodeBuilder.camera = renderObject.camera;
  38315. nodeBuilder.context.material = renderObject.material;
  38316. nodeBuilder.lightsNode = renderObject.lightsNode;
  38317. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38318. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38319. nodeBuilder.clippingContext = renderObject.clippingContext;
  38320. nodeBuilder.build();
  38321. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38322. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38323. }
  38324. nodeBuilderState.usedTimes ++;
  38325. renderObjectData.nodeBuilderState = nodeBuilderState;
  38326. }
  38327. return nodeBuilderState;
  38328. }
  38329. delete( object ) {
  38330. if ( object.isRenderObject ) {
  38331. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38332. nodeBuilderState.usedTimes --;
  38333. if ( nodeBuilderState.usedTimes === 0 ) {
  38334. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38335. }
  38336. }
  38337. return super.delete( object );
  38338. }
  38339. getForCompute( computeNode ) {
  38340. const computeData = this.get( computeNode );
  38341. let nodeBuilderState = computeData.nodeBuilderState;
  38342. if ( nodeBuilderState === undefined ) {
  38343. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38344. nodeBuilder.build();
  38345. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38346. computeData.nodeBuilderState = nodeBuilderState;
  38347. }
  38348. return nodeBuilderState;
  38349. }
  38350. _createNodeBuilderState( nodeBuilder ) {
  38351. return new NodeBuilderState(
  38352. nodeBuilder.vertexShader,
  38353. nodeBuilder.fragmentShader,
  38354. nodeBuilder.computeShader,
  38355. nodeBuilder.getAttributesArray(),
  38356. nodeBuilder.getBindings(),
  38357. nodeBuilder.updateNodes,
  38358. nodeBuilder.updateBeforeNodes,
  38359. nodeBuilder.updateAfterNodes,
  38360. nodeBuilder.monitor,
  38361. nodeBuilder.transforms
  38362. );
  38363. }
  38364. getEnvironmentNode( scene ) {
  38365. return scene.environmentNode || this.get( scene ).environmentNode || null;
  38366. }
  38367. getBackgroundNode( scene ) {
  38368. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  38369. }
  38370. getFogNode( scene ) {
  38371. return scene.fogNode || this.get( scene ).fogNode || null;
  38372. }
  38373. getCacheKey( scene, lightsNode ) {
  38374. const chain = [ scene, lightsNode ];
  38375. const callId = this.renderer.info.calls;
  38376. let cacheKeyData = this.callHashCache.get( chain );
  38377. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  38378. const environmentNode = this.getEnvironmentNode( scene );
  38379. const fogNode = this.getFogNode( scene );
  38380. const values = [];
  38381. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  38382. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  38383. if ( fogNode ) values.push( fogNode.getCacheKey() );
  38384. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38385. cacheKeyData = {
  38386. callId,
  38387. cacheKey: hashArray( values )
  38388. };
  38389. this.callHashCache.set( chain, cacheKeyData );
  38390. }
  38391. return cacheKeyData.cacheKey;
  38392. }
  38393. updateScene( scene ) {
  38394. this.updateEnvironment( scene );
  38395. this.updateFog( scene );
  38396. this.updateBackground( scene );
  38397. }
  38398. get isToneMappingState() {
  38399. return this.renderer.getRenderTarget() ? false : true;
  38400. }
  38401. updateBackground( scene ) {
  38402. const sceneData = this.get( scene );
  38403. const background = scene.background;
  38404. if ( background ) {
  38405. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38406. if ( sceneData.background !== background || forceUpdate ) {
  38407. let backgroundNode = null;
  38408. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38409. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38410. backgroundNode = pmremTexture( background, normalWorld );
  38411. } else {
  38412. let envMap;
  38413. if ( background.isCubeTexture === true ) {
  38414. envMap = cubeTexture( background );
  38415. } else {
  38416. envMap = texture( background );
  38417. }
  38418. backgroundNode = cubeMapNode( envMap );
  38419. }
  38420. } else if ( background.isTexture === true ) {
  38421. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38422. } else if ( background.isColor !== true ) {
  38423. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  38424. }
  38425. sceneData.backgroundNode = backgroundNode;
  38426. sceneData.background = background;
  38427. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38428. }
  38429. } else if ( sceneData.backgroundNode ) {
  38430. delete sceneData.backgroundNode;
  38431. delete sceneData.background;
  38432. }
  38433. }
  38434. updateFog( scene ) {
  38435. const sceneData = this.get( scene );
  38436. const fog = scene.fog;
  38437. if ( fog ) {
  38438. if ( sceneData.fog !== fog ) {
  38439. let fogNode = null;
  38440. if ( fog.isFogExp2 ) {
  38441. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  38442. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  38443. fogNode = densityFog( color, density );
  38444. } else if ( fog.isFog ) {
  38445. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  38446. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  38447. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  38448. fogNode = rangeFog( color, near, far );
  38449. } else {
  38450. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  38451. }
  38452. sceneData.fogNode = fogNode;
  38453. sceneData.fog = fog;
  38454. }
  38455. } else {
  38456. delete sceneData.fogNode;
  38457. delete sceneData.fog;
  38458. }
  38459. }
  38460. updateEnvironment( scene ) {
  38461. const sceneData = this.get( scene );
  38462. const environment = scene.environment;
  38463. if ( environment ) {
  38464. if ( sceneData.environment !== environment ) {
  38465. let environmentNode = null;
  38466. if ( environment.isCubeTexture === true ) {
  38467. environmentNode = cubeTexture( environment );
  38468. } else if ( environment.isTexture === true ) {
  38469. environmentNode = texture( environment );
  38470. } else {
  38471. console.error( 'Nodes: Unsupported environment configuration.', environment );
  38472. }
  38473. sceneData.environmentNode = environmentNode;
  38474. sceneData.environment = environment;
  38475. }
  38476. } else if ( sceneData.environmentNode ) {
  38477. delete sceneData.environmentNode;
  38478. delete sceneData.environment;
  38479. }
  38480. }
  38481. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38482. const nodeFrame = this.nodeFrame;
  38483. nodeFrame.renderer = renderer;
  38484. nodeFrame.scene = scene;
  38485. nodeFrame.object = object;
  38486. nodeFrame.camera = camera;
  38487. nodeFrame.material = material;
  38488. return nodeFrame;
  38489. }
  38490. getNodeFrameForRender( renderObject ) {
  38491. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38492. }
  38493. getOutputCacheKey() {
  38494. const renderer = this.renderer;
  38495. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  38496. }
  38497. hasOutputChange( outputTarget ) {
  38498. const cacheKey = outputNodeMap.get( outputTarget );
  38499. return cacheKey !== this.getOutputCacheKey();
  38500. }
  38501. getOutputNode( outputTexture ) {
  38502. const renderer = this.renderer;
  38503. const cacheKey = this.getOutputCacheKey();
  38504. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38505. outputNodeMap.set( outputTexture, cacheKey );
  38506. return output;
  38507. }
  38508. updateBefore( renderObject ) {
  38509. const nodeBuilder = renderObject.getNodeBuilderState();
  38510. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38511. // update frame state for each node
  38512. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38513. }
  38514. }
  38515. updateAfter( renderObject ) {
  38516. const nodeBuilder = renderObject.getNodeBuilderState();
  38517. for ( const node of nodeBuilder.updateAfterNodes ) {
  38518. // update frame state for each node
  38519. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38520. }
  38521. }
  38522. updateForCompute( computeNode ) {
  38523. const nodeFrame = this.getNodeFrame();
  38524. const nodeBuilder = this.getForCompute( computeNode );
  38525. for ( const node of nodeBuilder.updateNodes ) {
  38526. nodeFrame.updateNode( node );
  38527. }
  38528. }
  38529. updateForRender( renderObject ) {
  38530. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38531. const nodeBuilder = renderObject.getNodeBuilderState();
  38532. for ( const node of nodeBuilder.updateNodes ) {
  38533. nodeFrame.updateNode( node );
  38534. }
  38535. }
  38536. needsRefresh( renderObject ) {
  38537. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38538. const monitor = renderObject.getMonitor();
  38539. return monitor.needsRefresh( renderObject, nodeFrame );
  38540. }
  38541. dispose() {
  38542. super.dispose();
  38543. this.nodeFrame = new NodeFrame();
  38544. this.nodeBuilderCache = new Map();
  38545. }
  38546. }
  38547. class RenderBundle {
  38548. constructor( scene, camera ) {
  38549. this.scene = scene;
  38550. this.camera = camera;
  38551. }
  38552. clone() {
  38553. return Object.assign( new this.constructor(), this );
  38554. }
  38555. }
  38556. class RenderBundles {
  38557. constructor() {
  38558. this.lists = new ChainMap();
  38559. }
  38560. get( scene, camera ) {
  38561. const lists = this.lists;
  38562. const keys = [ scene, camera ];
  38563. let list = lists.get( keys );
  38564. if ( list === undefined ) {
  38565. list = new RenderBundle( scene, camera );
  38566. lists.set( keys, list );
  38567. }
  38568. return list;
  38569. }
  38570. dispose() {
  38571. this.lists = new ChainMap();
  38572. }
  38573. }
  38574. class NodeLibrary {
  38575. constructor() {
  38576. this.lightNodes = new WeakMap();
  38577. this.materialNodes = new Map();
  38578. this.toneMappingNodes = new Map();
  38579. this.colorSpaceNodes = new Map();
  38580. }
  38581. fromMaterial( material ) {
  38582. if ( material.isNodeMaterial ) return material;
  38583. let nodeMaterial = null;
  38584. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  38585. if ( nodeMaterialClass !== null ) {
  38586. nodeMaterial = new nodeMaterialClass();
  38587. for ( const key in material ) {
  38588. nodeMaterial[ key ] = material[ key ];
  38589. }
  38590. }
  38591. return nodeMaterial;
  38592. }
  38593. addColorSpace( colorSpaceNode, colorSpace ) {
  38594. this.addType( colorSpaceNode, colorSpace, this.colorSpaceNodes );
  38595. }
  38596. getColorSpaceFunction( colorSpace ) {
  38597. return this.colorSpaceNodes.get( colorSpace ) || null;
  38598. }
  38599. addToneMapping( toneMappingNode, toneMapping ) {
  38600. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  38601. }
  38602. getToneMappingFunction( toneMapping ) {
  38603. return this.toneMappingNodes.get( toneMapping ) || null;
  38604. }
  38605. getMaterialNodeClass( materialType ) {
  38606. return this.materialNodes.get( materialType ) || null;
  38607. }
  38608. addMaterial( materialNodeClass, materialClass ) {
  38609. this.addType( materialNodeClass, materialClass.name, this.materialNodes );
  38610. }
  38611. getLightNodeClass( light ) {
  38612. return this.lightNodes.get( light ) || null;
  38613. }
  38614. addLight( lightNodeClass, lightClass ) {
  38615. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  38616. }
  38617. addType( nodeClass, type, library ) {
  38618. if ( library.has( type ) ) {
  38619. console.warn( `Redefinition of node ${ type }` );
  38620. return;
  38621. }
  38622. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38623. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  38624. library.set( type, nodeClass );
  38625. }
  38626. addClass( nodeClass, baseClass, library ) {
  38627. if ( library.has( baseClass ) ) {
  38628. console.warn( `Redefinition of node ${ baseClass.name }` );
  38629. return;
  38630. }
  38631. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38632. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  38633. library.set( baseClass, nodeClass );
  38634. }
  38635. }
  38636. const _scene = /*@__PURE__*/ new Scene();
  38637. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  38638. const _screen = /*@__PURE__*/ new Vector4();
  38639. const _frustum = /*@__PURE__*/ new Frustum();
  38640. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  38641. const _vector4 = /*@__PURE__*/ new Vector4();
  38642. class Renderer {
  38643. constructor( backend, parameters = {} ) {
  38644. this.isRenderer = true;
  38645. //
  38646. const {
  38647. logarithmicDepthBuffer = false,
  38648. alpha = true,
  38649. depth = true,
  38650. stencil = false,
  38651. antialias = false,
  38652. samples = 0,
  38653. getFallback = null
  38654. } = parameters;
  38655. // public
  38656. this.domElement = backend.getDomElement();
  38657. this.backend = backend;
  38658. this.samples = samples || ( antialias === true ) ? 4 : 0;
  38659. this.autoClear = true;
  38660. this.autoClearColor = true;
  38661. this.autoClearDepth = true;
  38662. this.autoClearStencil = true;
  38663. this.alpha = alpha;
  38664. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  38665. this.outputColorSpace = SRGBColorSpace;
  38666. this.toneMapping = NoToneMapping;
  38667. this.toneMappingExposure = 1.0;
  38668. this.sortObjects = true;
  38669. this.depth = depth;
  38670. this.stencil = stencil;
  38671. this.clippingPlanes = [];
  38672. this.info = new Info();
  38673. this.nodes = {
  38674. library: new NodeLibrary(),
  38675. modelViewMatrix: null,
  38676. modelNormalViewMatrix: null
  38677. };
  38678. // internals
  38679. this._getFallback = getFallback;
  38680. this._pixelRatio = 1;
  38681. this._width = this.domElement.width;
  38682. this._height = this.domElement.height;
  38683. this._viewport = new Vector4( 0, 0, this._width, this._height );
  38684. this._scissor = new Vector4( 0, 0, this._width, this._height );
  38685. this._scissorTest = false;
  38686. this._attributes = null;
  38687. this._geometries = null;
  38688. this._nodes = null;
  38689. this._animation = null;
  38690. this._bindings = null;
  38691. this._objects = null;
  38692. this._pipelines = null;
  38693. this._bundles = null;
  38694. this._renderLists = null;
  38695. this._renderContexts = null;
  38696. this._textures = null;
  38697. this._background = null;
  38698. this._quad = new QuadMesh( new NodeMaterial() );
  38699. this._quad.material.type = 'Renderer_output';
  38700. this._currentRenderContext = null;
  38701. this._opaqueSort = null;
  38702. this._transparentSort = null;
  38703. this._frameBufferTarget = null;
  38704. const alphaClear = this.alpha === true ? 0 : 1;
  38705. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  38706. this._clearDepth = 1;
  38707. this._clearStencil = 0;
  38708. this._renderTarget = null;
  38709. this._activeCubeFace = 0;
  38710. this._activeMipmapLevel = 0;
  38711. this._mrt = null;
  38712. this._renderObjectFunction = null;
  38713. this._currentRenderObjectFunction = null;
  38714. this._currentRenderBundle = null;
  38715. this._handleObjectFunction = this._renderObjectDirect;
  38716. this._initialized = false;
  38717. this._initPromise = null;
  38718. this._compilationPromises = null;
  38719. this.transparent = true;
  38720. this.opaque = true;
  38721. this.shadowMap = {
  38722. enabled: false,
  38723. type: PCFShadowMap$1
  38724. };
  38725. this.xr = {
  38726. enabled: false
  38727. };
  38728. this.debug = {
  38729. checkShaderErrors: true,
  38730. onShaderError: null,
  38731. getShaderAsync: async ( scene, camera, object ) => {
  38732. await this.compileAsync( scene, camera );
  38733. const renderList = this._renderLists.get( scene, camera );
  38734. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  38735. const material = scene.overrideMaterial || object.material;
  38736. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  38737. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  38738. return { fragmentShader, vertexShader };
  38739. }
  38740. };
  38741. }
  38742. async init() {
  38743. if ( this._initialized ) {
  38744. throw new Error( 'Renderer: Backend has already been initialized.' );
  38745. }
  38746. if ( this._initPromise !== null ) {
  38747. return this._initPromise;
  38748. }
  38749. this._initPromise = new Promise( async ( resolve, reject ) => {
  38750. let backend = this.backend;
  38751. try {
  38752. await backend.init( this );
  38753. } catch ( error ) {
  38754. if ( this._getFallback !== null ) {
  38755. // try the fallback
  38756. try {
  38757. this.backend = backend = this._getFallback( error );
  38758. await backend.init( this );
  38759. } catch ( error ) {
  38760. reject( error );
  38761. return;
  38762. }
  38763. } else {
  38764. reject( error );
  38765. return;
  38766. }
  38767. }
  38768. this._nodes = new Nodes( this, backend );
  38769. this._animation = new Animation( this._nodes, this.info );
  38770. this._attributes = new Attributes( backend );
  38771. this._background = new Background( this, this._nodes );
  38772. this._geometries = new Geometries( this._attributes, this.info );
  38773. this._textures = new Textures( this, backend, this.info );
  38774. this._pipelines = new Pipelines( backend, this._nodes );
  38775. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  38776. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  38777. this._renderLists = new RenderLists();
  38778. this._bundles = new RenderBundles();
  38779. this._renderContexts = new RenderContexts();
  38780. //
  38781. this._initialized = true;
  38782. resolve();
  38783. } );
  38784. return this._initPromise;
  38785. }
  38786. get coordinateSystem() {
  38787. return this.backend.coordinateSystem;
  38788. }
  38789. async compileAsync( scene, camera, targetScene = null ) {
  38790. if ( this._initialized === false ) await this.init();
  38791. // preserve render tree
  38792. const nodeFrame = this._nodes.nodeFrame;
  38793. const previousRenderId = nodeFrame.renderId;
  38794. const previousRenderContext = this._currentRenderContext;
  38795. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38796. const previousCompilationPromises = this._compilationPromises;
  38797. //
  38798. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38799. if ( targetScene === null ) targetScene = scene;
  38800. const renderTarget = this._renderTarget;
  38801. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  38802. const activeMipmapLevel = this._activeMipmapLevel;
  38803. const compilationPromises = [];
  38804. this._currentRenderContext = renderContext;
  38805. this._currentRenderObjectFunction = this.renderObject;
  38806. this._handleObjectFunction = this._createObjectPipeline;
  38807. this._compilationPromises = compilationPromises;
  38808. nodeFrame.renderId ++;
  38809. //
  38810. nodeFrame.update();
  38811. //
  38812. renderContext.depth = this.depth;
  38813. renderContext.stencil = this.stencil;
  38814. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38815. renderContext.clippingContext.updateGlobal( this, camera );
  38816. //
  38817. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38818. //
  38819. const renderList = this._renderLists.get( scene, camera );
  38820. renderList.begin();
  38821. this._projectObject( scene, camera, 0, renderList );
  38822. // include lights from target scene
  38823. if ( targetScene !== scene ) {
  38824. targetScene.traverseVisible( function ( object ) {
  38825. if ( object.isLight && object.layers.test( camera.layers ) ) {
  38826. renderList.pushLight( object );
  38827. }
  38828. } );
  38829. }
  38830. renderList.finish();
  38831. //
  38832. if ( renderTarget !== null ) {
  38833. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38834. const renderTargetData = this._textures.get( renderTarget );
  38835. renderContext.textures = renderTargetData.textures;
  38836. renderContext.depthTexture = renderTargetData.depthTexture;
  38837. } else {
  38838. renderContext.textures = null;
  38839. renderContext.depthTexture = null;
  38840. }
  38841. //
  38842. this._nodes.updateScene( sceneRef );
  38843. //
  38844. this._background.update( sceneRef, renderList, renderContext );
  38845. // process render lists
  38846. const opaqueObjects = renderList.opaque;
  38847. const transparentObjects = renderList.transparent;
  38848. const lightsNode = renderList.lightsNode;
  38849. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38850. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  38851. // restore render tree
  38852. nodeFrame.renderId = previousRenderId;
  38853. this._currentRenderContext = previousRenderContext;
  38854. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38855. this._compilationPromises = previousCompilationPromises;
  38856. this._handleObjectFunction = this._renderObjectDirect;
  38857. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  38858. await Promise.all( compilationPromises );
  38859. }
  38860. async renderAsync( scene, camera ) {
  38861. if ( this._initialized === false ) await this.init();
  38862. const renderContext = this._renderScene( scene, camera );
  38863. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  38864. }
  38865. setMRT( mrt ) {
  38866. this._mrt = mrt;
  38867. return this;
  38868. }
  38869. getMRT() {
  38870. return this._mrt;
  38871. }
  38872. _renderBundle( bundle, sceneRef, lightsNode ) {
  38873. const { bundleGroup, camera, renderList } = bundle;
  38874. const renderContext = this._currentRenderContext;
  38875. //
  38876. const renderBundle = this._bundles.get( bundleGroup, camera );
  38877. const renderBundleData = this.backend.get( renderBundle );
  38878. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  38879. //
  38880. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  38881. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  38882. renderBundleData.renderContexts.add( renderContext );
  38883. if ( renderBundleNeedsUpdate ) {
  38884. this.backend.beginBundle( renderContext );
  38885. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  38886. renderBundleData.renderObjects = [];
  38887. }
  38888. this._currentRenderBundle = renderBundle;
  38889. const opaqueObjects = renderList.opaque;
  38890. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38891. this._currentRenderBundle = null;
  38892. //
  38893. this.backend.finishBundle( renderContext, renderBundle );
  38894. renderBundleData.version = bundleGroup.version;
  38895. } else {
  38896. const { renderObjects } = renderBundleData;
  38897. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  38898. const renderObject = renderObjects[ i ];
  38899. if ( this._nodes.needsRefresh( renderObject ) ) {
  38900. this._nodes.updateBefore( renderObject );
  38901. this._nodes.updateForRender( renderObject );
  38902. this._bindings.updateForRender( renderObject );
  38903. this._nodes.updateAfter( renderObject );
  38904. }
  38905. }
  38906. }
  38907. this.backend.addBundle( renderContext, renderBundle );
  38908. }
  38909. render( scene, camera ) {
  38910. if ( this._initialized === false ) {
  38911. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  38912. return this.renderAsync( scene, camera );
  38913. }
  38914. this._renderScene( scene, camera );
  38915. }
  38916. _getFrameBufferTarget() {
  38917. const { currentToneMapping, currentColorSpace } = this;
  38918. const useToneMapping = currentToneMapping !== NoToneMapping;
  38919. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  38920. if ( useToneMapping === false && useColorSpace === false ) return null;
  38921. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  38922. const { depth, stencil } = this;
  38923. let frameBufferTarget = this._frameBufferTarget;
  38924. if ( frameBufferTarget === null ) {
  38925. frameBufferTarget = new RenderTarget( width, height, {
  38926. depthBuffer: depth,
  38927. stencilBuffer: stencil,
  38928. type: HalfFloatType, // FloatType
  38929. format: RGBAFormat,
  38930. colorSpace: LinearSRGBColorSpace,
  38931. generateMipmaps: false,
  38932. minFilter: LinearFilter,
  38933. magFilter: LinearFilter,
  38934. samples: this.samples
  38935. } );
  38936. frameBufferTarget.isPostProcessingRenderTarget = true;
  38937. this._frameBufferTarget = frameBufferTarget;
  38938. }
  38939. frameBufferTarget.depthBuffer = depth;
  38940. frameBufferTarget.stencilBuffer = stencil;
  38941. frameBufferTarget.setSize( width, height );
  38942. frameBufferTarget.viewport.copy( this._viewport );
  38943. frameBufferTarget.scissor.copy( this._scissor );
  38944. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  38945. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  38946. frameBufferTarget.scissorTest = this._scissorTest;
  38947. return frameBufferTarget;
  38948. }
  38949. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  38950. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  38951. // preserve render tree
  38952. const nodeFrame = this._nodes.nodeFrame;
  38953. const previousRenderId = nodeFrame.renderId;
  38954. const previousRenderContext = this._currentRenderContext;
  38955. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38956. //
  38957. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38958. const outputRenderTarget = this._renderTarget;
  38959. const activeCubeFace = this._activeCubeFace;
  38960. const activeMipmapLevel = this._activeMipmapLevel;
  38961. //
  38962. let renderTarget;
  38963. if ( frameBufferTarget !== null ) {
  38964. renderTarget = frameBufferTarget;
  38965. this.setRenderTarget( renderTarget );
  38966. } else {
  38967. renderTarget = outputRenderTarget;
  38968. }
  38969. //
  38970. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  38971. this._currentRenderContext = renderContext;
  38972. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  38973. //
  38974. this.info.calls ++;
  38975. this.info.render.calls ++;
  38976. this.info.render.frameCalls ++;
  38977. nodeFrame.renderId = this.info.calls;
  38978. //
  38979. const coordinateSystem = this.coordinateSystem;
  38980. if ( camera.coordinateSystem !== coordinateSystem ) {
  38981. camera.coordinateSystem = coordinateSystem;
  38982. camera.updateProjectionMatrix();
  38983. }
  38984. //
  38985. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  38986. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  38987. //
  38988. let viewport = this._viewport;
  38989. let scissor = this._scissor;
  38990. let pixelRatio = this._pixelRatio;
  38991. if ( renderTarget !== null ) {
  38992. viewport = renderTarget.viewport;
  38993. scissor = renderTarget.scissor;
  38994. pixelRatio = 1;
  38995. }
  38996. this.getDrawingBufferSize( _drawingBufferSize );
  38997. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  38998. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  38999. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  39000. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  39001. renderContext.viewportValue.width >>= activeMipmapLevel;
  39002. renderContext.viewportValue.height >>= activeMipmapLevel;
  39003. renderContext.viewportValue.minDepth = minDepth;
  39004. renderContext.viewportValue.maxDepth = maxDepth;
  39005. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  39006. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  39007. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  39008. renderContext.scissorValue.width >>= activeMipmapLevel;
  39009. renderContext.scissorValue.height >>= activeMipmapLevel;
  39010. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39011. renderContext.clippingContext.updateGlobal( this, camera );
  39012. //
  39013. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39014. //
  39015. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  39016. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  39017. const renderList = this._renderLists.get( scene, camera );
  39018. renderList.begin();
  39019. this._projectObject( scene, camera, 0, renderList );
  39020. renderList.finish();
  39021. if ( this.sortObjects === true ) {
  39022. renderList.sort( this._opaqueSort, this._transparentSort );
  39023. }
  39024. //
  39025. if ( renderTarget !== null ) {
  39026. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39027. const renderTargetData = this._textures.get( renderTarget );
  39028. renderContext.textures = renderTargetData.textures;
  39029. renderContext.depthTexture = renderTargetData.depthTexture;
  39030. renderContext.width = renderTargetData.width;
  39031. renderContext.height = renderTargetData.height;
  39032. renderContext.renderTarget = renderTarget;
  39033. renderContext.depth = renderTarget.depthBuffer;
  39034. renderContext.stencil = renderTarget.stencilBuffer;
  39035. } else {
  39036. renderContext.textures = null;
  39037. renderContext.depthTexture = null;
  39038. renderContext.width = this.domElement.width;
  39039. renderContext.height = this.domElement.height;
  39040. renderContext.depth = this.depth;
  39041. renderContext.stencil = this.stencil;
  39042. }
  39043. renderContext.width >>= activeMipmapLevel;
  39044. renderContext.height >>= activeMipmapLevel;
  39045. renderContext.activeCubeFace = activeCubeFace;
  39046. renderContext.activeMipmapLevel = activeMipmapLevel;
  39047. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  39048. //
  39049. this._nodes.updateScene( sceneRef );
  39050. //
  39051. this._background.update( sceneRef, renderList, renderContext );
  39052. //
  39053. this.backend.beginRender( renderContext );
  39054. // process render lists
  39055. const {
  39056. bundles,
  39057. lightsNode,
  39058. transparent: transparentObjects,
  39059. opaque: opaqueObjects
  39060. } = renderList;
  39061. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  39062. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39063. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  39064. // finish render pass
  39065. this.backend.finishRender( renderContext );
  39066. // restore render tree
  39067. nodeFrame.renderId = previousRenderId;
  39068. this._currentRenderContext = previousRenderContext;
  39069. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39070. //
  39071. if ( frameBufferTarget !== null ) {
  39072. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  39073. const quad = this._quad;
  39074. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  39075. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  39076. quad.material.needsUpdate = true;
  39077. }
  39078. this._renderScene( quad, quad.camera, false );
  39079. }
  39080. //
  39081. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  39082. //
  39083. return renderContext;
  39084. }
  39085. getMaxAnisotropy() {
  39086. return this.backend.getMaxAnisotropy();
  39087. }
  39088. getActiveCubeFace() {
  39089. return this._activeCubeFace;
  39090. }
  39091. getActiveMipmapLevel() {
  39092. return this._activeMipmapLevel;
  39093. }
  39094. async setAnimationLoop( callback ) {
  39095. if ( this._initialized === false ) await this.init();
  39096. this._animation.setAnimationLoop( callback );
  39097. }
  39098. async getArrayBufferAsync( attribute ) {
  39099. return await this.backend.getArrayBufferAsync( attribute );
  39100. }
  39101. getContext() {
  39102. return this.backend.getContext();
  39103. }
  39104. getPixelRatio() {
  39105. return this._pixelRatio;
  39106. }
  39107. getDrawingBufferSize( target ) {
  39108. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39109. }
  39110. getSize( target ) {
  39111. return target.set( this._width, this._height );
  39112. }
  39113. setPixelRatio( value = 1 ) {
  39114. this._pixelRatio = value;
  39115. this.setSize( this._width, this._height, false );
  39116. }
  39117. setDrawingBufferSize( width, height, pixelRatio ) {
  39118. this._width = width;
  39119. this._height = height;
  39120. this._pixelRatio = pixelRatio;
  39121. this.domElement.width = Math.floor( width * pixelRatio );
  39122. this.domElement.height = Math.floor( height * pixelRatio );
  39123. this.setViewport( 0, 0, width, height );
  39124. if ( this._initialized ) this.backend.updateSize();
  39125. }
  39126. setSize( width, height, updateStyle = true ) {
  39127. this._width = width;
  39128. this._height = height;
  39129. this.domElement.width = Math.floor( width * this._pixelRatio );
  39130. this.domElement.height = Math.floor( height * this._pixelRatio );
  39131. if ( updateStyle === true ) {
  39132. this.domElement.style.width = width + 'px';
  39133. this.domElement.style.height = height + 'px';
  39134. }
  39135. this.setViewport( 0, 0, width, height );
  39136. if ( this._initialized ) this.backend.updateSize();
  39137. }
  39138. setOpaqueSort( method ) {
  39139. this._opaqueSort = method;
  39140. }
  39141. setTransparentSort( method ) {
  39142. this._transparentSort = method;
  39143. }
  39144. getScissor( target ) {
  39145. const scissor = this._scissor;
  39146. target.x = scissor.x;
  39147. target.y = scissor.y;
  39148. target.width = scissor.width;
  39149. target.height = scissor.height;
  39150. return target;
  39151. }
  39152. setScissor( x, y, width, height ) {
  39153. const scissor = this._scissor;
  39154. if ( x.isVector4 ) {
  39155. scissor.copy( x );
  39156. } else {
  39157. scissor.set( x, y, width, height );
  39158. }
  39159. }
  39160. getScissorTest() {
  39161. return this._scissorTest;
  39162. }
  39163. setScissorTest( boolean ) {
  39164. this._scissorTest = boolean;
  39165. this.backend.setScissorTest( boolean );
  39166. }
  39167. getViewport( target ) {
  39168. return target.copy( this._viewport );
  39169. }
  39170. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39171. const viewport = this._viewport;
  39172. if ( x.isVector4 ) {
  39173. viewport.copy( x );
  39174. } else {
  39175. viewport.set( x, y, width, height );
  39176. }
  39177. viewport.minDepth = minDepth;
  39178. viewport.maxDepth = maxDepth;
  39179. }
  39180. getClearColor( target ) {
  39181. return target.copy( this._clearColor );
  39182. }
  39183. setClearColor( color, alpha = 1 ) {
  39184. this._clearColor.set( color );
  39185. this._clearColor.a = alpha;
  39186. }
  39187. getClearAlpha() {
  39188. return this._clearColor.a;
  39189. }
  39190. setClearAlpha( alpha ) {
  39191. this._clearColor.a = alpha;
  39192. }
  39193. getClearDepth() {
  39194. return this._clearDepth;
  39195. }
  39196. setClearDepth( depth ) {
  39197. this._clearDepth = depth;
  39198. }
  39199. getClearStencil() {
  39200. return this._clearStencil;
  39201. }
  39202. setClearStencil( stencil ) {
  39203. this._clearStencil = stencil;
  39204. }
  39205. isOccluded( object ) {
  39206. const renderContext = this._currentRenderContext;
  39207. return renderContext && this.backend.isOccluded( renderContext, object );
  39208. }
  39209. clear( color = true, depth = true, stencil = true ) {
  39210. if ( this._initialized === false ) {
  39211. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  39212. return this.clearAsync( color, depth, stencil );
  39213. }
  39214. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  39215. let renderTargetData = null;
  39216. if ( renderTarget !== null ) {
  39217. this._textures.updateRenderTarget( renderTarget );
  39218. renderTargetData = this._textures.get( renderTarget );
  39219. }
  39220. this.backend.clear( color, depth, stencil, renderTargetData );
  39221. if ( renderTarget !== null && this._renderTarget === null ) {
  39222. // If a color space transform or tone mapping is required,
  39223. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  39224. const quad = this._quad;
  39225. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  39226. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  39227. quad.material.needsUpdate = true;
  39228. }
  39229. this._renderScene( quad, quad.camera, false );
  39230. }
  39231. }
  39232. clearColor() {
  39233. return this.clear( true, false, false );
  39234. }
  39235. clearDepth() {
  39236. return this.clear( false, true, false );
  39237. }
  39238. clearStencil() {
  39239. return this.clear( false, false, true );
  39240. }
  39241. async clearAsync( color = true, depth = true, stencil = true ) {
  39242. if ( this._initialized === false ) await this.init();
  39243. this.clear( color, depth, stencil );
  39244. }
  39245. clearColorAsync() {
  39246. return this.clearAsync( true, false, false );
  39247. }
  39248. clearDepthAsync() {
  39249. return this.clearAsync( false, true, false );
  39250. }
  39251. clearStencilAsync() {
  39252. return this.clearAsync( false, false, true );
  39253. }
  39254. get currentToneMapping() {
  39255. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  39256. }
  39257. get currentColorSpace() {
  39258. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  39259. }
  39260. dispose() {
  39261. this.info.dispose();
  39262. this._animation.dispose();
  39263. this._objects.dispose();
  39264. this._pipelines.dispose();
  39265. this._nodes.dispose();
  39266. this._bindings.dispose();
  39267. this._renderLists.dispose();
  39268. this._renderContexts.dispose();
  39269. this._textures.dispose();
  39270. this.setRenderTarget( null );
  39271. this.setAnimationLoop( null );
  39272. }
  39273. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  39274. this._renderTarget = renderTarget;
  39275. this._activeCubeFace = activeCubeFace;
  39276. this._activeMipmapLevel = activeMipmapLevel;
  39277. }
  39278. getRenderTarget() {
  39279. return this._renderTarget;
  39280. }
  39281. setRenderObjectFunction( renderObjectFunction ) {
  39282. this._renderObjectFunction = renderObjectFunction;
  39283. }
  39284. getRenderObjectFunction() {
  39285. return this._renderObjectFunction;
  39286. }
  39287. async computeAsync( computeNodes ) {
  39288. if ( this._initialized === false ) await this.init();
  39289. const nodeFrame = this._nodes.nodeFrame;
  39290. const previousRenderId = nodeFrame.renderId;
  39291. //
  39292. this.info.calls ++;
  39293. this.info.compute.calls ++;
  39294. this.info.compute.frameCalls ++;
  39295. nodeFrame.renderId = this.info.calls;
  39296. //
  39297. const backend = this.backend;
  39298. const pipelines = this._pipelines;
  39299. const bindings = this._bindings;
  39300. const nodes = this._nodes;
  39301. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  39302. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  39303. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  39304. }
  39305. backend.beginCompute( computeNodes );
  39306. for ( const computeNode of computeList ) {
  39307. // onInit
  39308. if ( pipelines.has( computeNode ) === false ) {
  39309. const dispose = () => {
  39310. computeNode.removeEventListener( 'dispose', dispose );
  39311. pipelines.delete( computeNode );
  39312. bindings.delete( computeNode );
  39313. nodes.delete( computeNode );
  39314. };
  39315. computeNode.addEventListener( 'dispose', dispose );
  39316. //
  39317. computeNode.onInit( { renderer: this } );
  39318. }
  39319. nodes.updateForCompute( computeNode );
  39320. bindings.updateForCompute( computeNode );
  39321. const computeBindings = bindings.getForCompute( computeNode );
  39322. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  39323. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  39324. }
  39325. backend.finishCompute( computeNodes );
  39326. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  39327. //
  39328. nodeFrame.renderId = previousRenderId;
  39329. }
  39330. async hasFeatureAsync( name ) {
  39331. if ( this._initialized === false ) await this.init();
  39332. return this.backend.hasFeature( name );
  39333. }
  39334. hasFeature( name ) {
  39335. if ( this._initialized === false ) {
  39336. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  39337. return false;
  39338. }
  39339. return this.backend.hasFeature( name );
  39340. }
  39341. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  39342. const renderContext = this._currentRenderContext;
  39343. this._textures.updateTexture( framebufferTexture );
  39344. rectangle = rectangle === null ? _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height ) : rectangle;
  39345. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  39346. }
  39347. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39348. this._textures.updateTexture( srcTexture );
  39349. this._textures.updateTexture( dstTexture );
  39350. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  39351. }
  39352. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  39353. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  39354. }
  39355. _projectObject( object, camera, groupOrder, renderList ) {
  39356. if ( object.visible === false ) return;
  39357. const visible = object.layers.test( camera.layers );
  39358. if ( visible ) {
  39359. if ( object.isGroup ) {
  39360. groupOrder = object.renderOrder;
  39361. } else if ( object.isLOD ) {
  39362. if ( object.autoUpdate === true ) object.update( camera );
  39363. } else if ( object.isLight ) {
  39364. renderList.pushLight( object );
  39365. } else if ( object.isSprite ) {
  39366. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  39367. if ( this.sortObjects === true ) {
  39368. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  39369. }
  39370. const { geometry, material } = object;
  39371. if ( material.visible ) {
  39372. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  39373. }
  39374. }
  39375. } else if ( object.isLineLoop ) {
  39376. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  39377. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  39378. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  39379. const { geometry, material } = object;
  39380. if ( this.sortObjects === true ) {
  39381. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  39382. _vector4
  39383. .copy( geometry.boundingSphere.center )
  39384. .applyMatrix4( object.matrixWorld )
  39385. .applyMatrix4( _projScreenMatrix );
  39386. }
  39387. if ( Array.isArray( material ) ) {
  39388. const groups = geometry.groups;
  39389. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  39390. const group = groups[ i ];
  39391. const groupMaterial = material[ group.materialIndex ];
  39392. if ( groupMaterial && groupMaterial.visible ) {
  39393. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  39394. }
  39395. }
  39396. } else if ( material.visible ) {
  39397. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  39398. }
  39399. }
  39400. }
  39401. }
  39402. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  39403. const baseRenderList = renderList;
  39404. // replace render list
  39405. renderList = this._renderLists.get( object, camera );
  39406. renderList.begin();
  39407. baseRenderList.pushBundle( {
  39408. bundleGroup: object,
  39409. camera,
  39410. renderList,
  39411. } );
  39412. renderList.finish();
  39413. }
  39414. const children = object.children;
  39415. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39416. this._projectObject( children[ i ], camera, groupOrder, renderList );
  39417. }
  39418. }
  39419. _renderBundles( bundles, sceneRef, lightsNode ) {
  39420. for ( const bundle of bundles ) {
  39421. this._renderBundle( bundle, sceneRef, lightsNode );
  39422. }
  39423. }
  39424. _renderObjects( renderList, camera, scene, lightsNode ) {
  39425. // process renderable objects
  39426. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  39427. const renderItem = renderList[ i ];
  39428. // @TODO: Add support for multiple materials per object. This will require to extract
  39429. // the material from the renderItem object and pass it with its group data to renderObject().
  39430. const { object, geometry, material, group } = renderItem;
  39431. if ( camera.isArrayCamera ) {
  39432. const cameras = camera.cameras;
  39433. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  39434. const camera2 = cameras[ j ];
  39435. if ( object.layers.test( camera2.layers ) ) {
  39436. const vp = camera2.viewport;
  39437. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  39438. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  39439. const viewportValue = this._currentRenderContext.viewportValue;
  39440. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  39441. viewportValue.minDepth = minDepth;
  39442. viewportValue.maxDepth = maxDepth;
  39443. this.backend.updateViewport( this._currentRenderContext );
  39444. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  39445. }
  39446. }
  39447. } else {
  39448. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  39449. }
  39450. }
  39451. }
  39452. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  39453. let overridePositionNode;
  39454. let overrideFragmentNode;
  39455. let overrideDepthNode;
  39456. //
  39457. object.onBeforeRender( this, scene, camera, geometry, material, group );
  39458. //
  39459. if ( scene.overrideMaterial !== null ) {
  39460. const overrideMaterial = scene.overrideMaterial;
  39461. if ( material.positionNode && material.positionNode.isNode ) {
  39462. overridePositionNode = overrideMaterial.positionNode;
  39463. overrideMaterial.positionNode = material.positionNode;
  39464. }
  39465. if ( overrideMaterial.isShadowNodeMaterial ) {
  39466. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  39467. if ( material.depthNode && material.depthNode.isNode ) {
  39468. overrideDepthNode = overrideMaterial.depthNode;
  39469. overrideMaterial.depthNode = material.depthNode;
  39470. }
  39471. if ( material.shadowNode && material.shadowNode.isNode ) {
  39472. overrideFragmentNode = overrideMaterial.fragmentNode;
  39473. overrideMaterial.fragmentNode = material.shadowNode;
  39474. }
  39475. if ( this.localClippingEnabled ) {
  39476. if ( material.clipShadows ) {
  39477. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  39478. overrideMaterial.clippingPlanes = material.clippingPlanes;
  39479. overrideMaterial.needsUpdate = true;
  39480. }
  39481. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  39482. overrideMaterial.clipIntersection = material.clipIntersection;
  39483. }
  39484. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  39485. overrideMaterial.clippingPlanes = null;
  39486. overrideMaterial.needsUpdate = true;
  39487. }
  39488. }
  39489. }
  39490. material = overrideMaterial;
  39491. }
  39492. //
  39493. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  39494. material.side = BackSide;
  39495. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  39496. material.side = FrontSide;
  39497. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  39498. material.side = DoubleSide;
  39499. } else {
  39500. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  39501. }
  39502. //
  39503. if ( overridePositionNode !== undefined ) {
  39504. scene.overrideMaterial.positionNode = overridePositionNode;
  39505. }
  39506. if ( overrideDepthNode !== undefined ) {
  39507. scene.overrideMaterial.depthNode = overrideDepthNode;
  39508. }
  39509. if ( overrideFragmentNode !== undefined ) {
  39510. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  39511. }
  39512. //
  39513. object.onAfterRender( this, scene, camera, geometry, material, group );
  39514. }
  39515. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  39516. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  39517. renderObject.drawRange = object.geometry.drawRange;
  39518. renderObject.group = group;
  39519. //
  39520. const needsRefresh = this._nodes.needsRefresh( renderObject );
  39521. if ( needsRefresh ) {
  39522. this._nodes.updateBefore( renderObject );
  39523. this._geometries.updateForRender( renderObject );
  39524. this._nodes.updateForRender( renderObject );
  39525. this._bindings.updateForRender( renderObject );
  39526. }
  39527. this._pipelines.updateForRender( renderObject );
  39528. //
  39529. if ( this._currentRenderBundle !== null ) {
  39530. const renderBundleData = this.backend.get( this._currentRenderBundle );
  39531. renderBundleData.renderObjects.push( renderObject );
  39532. renderObject.bundle = this._currentRenderBundle.scene;
  39533. }
  39534. this.backend.draw( renderObject, this.info );
  39535. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  39536. }
  39537. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  39538. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  39539. //
  39540. this._nodes.updateBefore( renderObject );
  39541. this._geometries.updateForRender( renderObject );
  39542. this._nodes.updateForRender( renderObject );
  39543. this._bindings.updateForRender( renderObject );
  39544. this._pipelines.getForRender( renderObject, this._compilationPromises );
  39545. this._nodes.updateAfter( renderObject );
  39546. }
  39547. get compute() {
  39548. return this.computeAsync;
  39549. }
  39550. get compile() {
  39551. return this.compileAsync;
  39552. }
  39553. }
  39554. class Binding {
  39555. constructor( name = '' ) {
  39556. this.name = name;
  39557. this.visibility = 0;
  39558. }
  39559. setVisibility( visibility ) {
  39560. this.visibility |= visibility;
  39561. }
  39562. clone() {
  39563. return Object.assign( new this.constructor(), this );
  39564. }
  39565. }
  39566. function getFloatLength( floatLength ) {
  39567. // ensure chunk size alignment (STD140 layout)
  39568. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  39569. }
  39570. class Buffer extends Binding {
  39571. constructor( name, buffer = null ) {
  39572. super( name );
  39573. this.isBuffer = true;
  39574. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  39575. this._buffer = buffer;
  39576. }
  39577. get byteLength() {
  39578. return getFloatLength( this._buffer.byteLength );
  39579. }
  39580. get buffer() {
  39581. return this._buffer;
  39582. }
  39583. update() {
  39584. return true;
  39585. }
  39586. }
  39587. class UniformBuffer extends Buffer {
  39588. constructor( name, buffer = null ) {
  39589. super( name, buffer );
  39590. this.isUniformBuffer = true;
  39591. }
  39592. }
  39593. let _id$4 = 0;
  39594. class NodeUniformBuffer extends UniformBuffer {
  39595. constructor( nodeUniform, groupNode ) {
  39596. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  39597. this.nodeUniform = nodeUniform;
  39598. this.groupNode = groupNode;
  39599. }
  39600. get buffer() {
  39601. return this.nodeUniform.value;
  39602. }
  39603. }
  39604. class UniformsGroup extends UniformBuffer {
  39605. constructor( name ) {
  39606. super( name );
  39607. this.isUniformsGroup = true;
  39608. this._values = null;
  39609. // the order of uniforms in this array must match the order of uniforms in the shader
  39610. this.uniforms = [];
  39611. }
  39612. addUniform( uniform ) {
  39613. this.uniforms.push( uniform );
  39614. return this;
  39615. }
  39616. removeUniform( uniform ) {
  39617. const index = this.uniforms.indexOf( uniform );
  39618. if ( index !== - 1 ) {
  39619. this.uniforms.splice( index, 1 );
  39620. }
  39621. return this;
  39622. }
  39623. get values() {
  39624. if ( this._values === null ) {
  39625. this._values = Array.from( this.buffer );
  39626. }
  39627. return this._values;
  39628. }
  39629. get buffer() {
  39630. let buffer = this._buffer;
  39631. if ( buffer === null ) {
  39632. const byteLength = this.byteLength;
  39633. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  39634. this._buffer = buffer;
  39635. }
  39636. return buffer;
  39637. }
  39638. get byteLength() {
  39639. let offset = 0; // global buffer offset in bytes
  39640. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  39641. const uniform = this.uniforms[ i ];
  39642. const { boundary, itemSize } = uniform;
  39643. // offset within a single chunk in bytes
  39644. const chunkOffset = offset % GPU_CHUNK_BYTES;
  39645. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  39646. // conformance tests
  39647. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  39648. // check for chunk overflow
  39649. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  39650. } else if ( chunkOffset % boundary !== 0 ) {
  39651. // check for correct alignment
  39652. offset += ( chunkOffset % boundary );
  39653. }
  39654. uniform.offset = ( offset / this.bytesPerElement );
  39655. offset += ( itemSize * this.bytesPerElement );
  39656. }
  39657. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  39658. }
  39659. update() {
  39660. let updated = false;
  39661. for ( const uniform of this.uniforms ) {
  39662. if ( this.updateByType( uniform ) === true ) {
  39663. updated = true;
  39664. }
  39665. }
  39666. return updated;
  39667. }
  39668. updateByType( uniform ) {
  39669. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  39670. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  39671. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  39672. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  39673. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  39674. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  39675. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  39676. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  39677. }
  39678. updateNumber( uniform ) {
  39679. let updated = false;
  39680. const a = this.values;
  39681. const v = uniform.getValue();
  39682. const offset = uniform.offset;
  39683. if ( a[ offset ] !== v ) {
  39684. const b = this.buffer;
  39685. b[ offset ] = a[ offset ] = v;
  39686. updated = true;
  39687. }
  39688. return updated;
  39689. }
  39690. updateVector2( uniform ) {
  39691. let updated = false;
  39692. const a = this.values;
  39693. const v = uniform.getValue();
  39694. const offset = uniform.offset;
  39695. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  39696. const b = this.buffer;
  39697. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39698. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39699. updated = true;
  39700. }
  39701. return updated;
  39702. }
  39703. updateVector3( uniform ) {
  39704. let updated = false;
  39705. const a = this.values;
  39706. const v = uniform.getValue();
  39707. const offset = uniform.offset;
  39708. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  39709. const b = this.buffer;
  39710. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39711. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39712. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39713. updated = true;
  39714. }
  39715. return updated;
  39716. }
  39717. updateVector4( uniform ) {
  39718. let updated = false;
  39719. const a = this.values;
  39720. const v = uniform.getValue();
  39721. const offset = uniform.offset;
  39722. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  39723. const b = this.buffer;
  39724. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39725. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39726. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39727. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  39728. updated = true;
  39729. }
  39730. return updated;
  39731. }
  39732. updateColor( uniform ) {
  39733. let updated = false;
  39734. const a = this.values;
  39735. const c = uniform.getValue();
  39736. const offset = uniform.offset;
  39737. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  39738. const b = this.buffer;
  39739. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  39740. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  39741. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  39742. updated = true;
  39743. }
  39744. return updated;
  39745. }
  39746. updateMatrix3( uniform ) {
  39747. let updated = false;
  39748. const a = this.values;
  39749. const e = uniform.getValue().elements;
  39750. const offset = uniform.offset;
  39751. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  39752. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  39753. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  39754. const b = this.buffer;
  39755. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  39756. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  39757. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  39758. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  39759. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  39760. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  39761. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  39762. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  39763. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  39764. updated = true;
  39765. }
  39766. return updated;
  39767. }
  39768. updateMatrix4( uniform ) {
  39769. let updated = false;
  39770. const a = this.values;
  39771. const e = uniform.getValue().elements;
  39772. const offset = uniform.offset;
  39773. if ( arraysEqual( a, e, offset ) === false ) {
  39774. const b = this.buffer;
  39775. b.set( e, offset );
  39776. setArray( a, e, offset );
  39777. updated = true;
  39778. }
  39779. return updated;
  39780. }
  39781. }
  39782. function setArray( a, b, offset ) {
  39783. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39784. a[ offset + i ] = b[ i ];
  39785. }
  39786. }
  39787. function arraysEqual( a, b, offset ) {
  39788. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39789. if ( a[ offset + i ] !== b[ i ] ) return false;
  39790. }
  39791. return true;
  39792. }
  39793. let _id$3 = 0;
  39794. class NodeUniformsGroup extends UniformsGroup {
  39795. constructor( name, groupNode ) {
  39796. super( name );
  39797. this.id = _id$3 ++;
  39798. this.groupNode = groupNode;
  39799. this.isNodeUniformsGroup = true;
  39800. }
  39801. getNodes() {
  39802. const nodes = [];
  39803. for ( const uniform of this.uniforms ) {
  39804. const node = uniform.nodeUniform.node;
  39805. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  39806. nodes.push( node );
  39807. }
  39808. return nodes;
  39809. }
  39810. }
  39811. let _id$2 = 0;
  39812. class SampledTexture extends Binding {
  39813. constructor( name, texture ) {
  39814. super( name );
  39815. this.id = _id$2 ++;
  39816. this.texture = texture;
  39817. this.version = texture ? texture.version : 0;
  39818. this.store = false;
  39819. this.generation = null;
  39820. this.isSampledTexture = true;
  39821. }
  39822. needsBindingsUpdate( generation ) {
  39823. const { texture } = this;
  39824. if ( generation !== this.generation ) {
  39825. this.generation = generation;
  39826. return true;
  39827. }
  39828. return texture.isVideoTexture;
  39829. }
  39830. update() {
  39831. const { texture, version } = this;
  39832. if ( version !== texture.version ) {
  39833. this.version = texture.version;
  39834. return true;
  39835. }
  39836. return false;
  39837. }
  39838. }
  39839. class NodeSampledTexture extends SampledTexture {
  39840. constructor( name, textureNode, groupNode, access = null ) {
  39841. super( name, textureNode ? textureNode.value : null );
  39842. this.textureNode = textureNode;
  39843. this.groupNode = groupNode;
  39844. this.access = access;
  39845. }
  39846. needsBindingsUpdate( generation ) {
  39847. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39848. }
  39849. update() {
  39850. const { textureNode } = this;
  39851. if ( this.texture !== textureNode.value ) {
  39852. this.texture = textureNode.value;
  39853. return true;
  39854. }
  39855. return super.update();
  39856. }
  39857. }
  39858. class NodeSampledCubeTexture extends NodeSampledTexture {
  39859. constructor( name, textureNode, groupNode, access ) {
  39860. super( name, textureNode, groupNode, access );
  39861. this.isSampledCubeTexture = true;
  39862. }
  39863. }
  39864. class NodeSampledTexture3D extends NodeSampledTexture {
  39865. constructor( name, textureNode, groupNode, access ) {
  39866. super( name, textureNode, groupNode, access );
  39867. this.isSampledTexture3D = true;
  39868. }
  39869. }
  39870. const glslMethods = {
  39871. atan2: 'atan',
  39872. textureDimensions: 'textureSize',
  39873. equals: 'equal'
  39874. };
  39875. const precisionLib = {
  39876. low: 'lowp',
  39877. medium: 'mediump',
  39878. high: 'highp'
  39879. };
  39880. const supports$1 = {
  39881. swizzleAssign: true,
  39882. storageBuffer: false
  39883. };
  39884. const defaultPrecisions = `
  39885. precision highp float;
  39886. precision highp int;
  39887. precision highp sampler2D;
  39888. precision highp sampler3D;
  39889. precision highp samplerCube;
  39890. precision highp sampler2DArray;
  39891. precision highp usampler2D;
  39892. precision highp usampler3D;
  39893. precision highp usamplerCube;
  39894. precision highp usampler2DArray;
  39895. precision highp isampler2D;
  39896. precision highp isampler3D;
  39897. precision highp isamplerCube;
  39898. precision highp isampler2DArray;
  39899. precision lowp sampler2DShadow;
  39900. `;
  39901. class GLSLNodeBuilder extends NodeBuilder {
  39902. constructor( object, renderer ) {
  39903. super( object, renderer, new GLSLNodeParser() );
  39904. this.uniformGroups = {};
  39905. this.transforms = [];
  39906. this.extensions = {};
  39907. this.useComparisonMethod = true;
  39908. }
  39909. needsColorSpaceToLinearSRGB( texture ) {
  39910. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39911. }
  39912. getMethod( method ) {
  39913. return glslMethods[ method ] || method;
  39914. }
  39915. getOutputStructName() {
  39916. return '';
  39917. }
  39918. buildFunctionCode( shaderNode ) {
  39919. const layout = shaderNode.layout;
  39920. const flowData = this.flowShaderNode( shaderNode );
  39921. const parameters = [];
  39922. for ( const input of layout.inputs ) {
  39923. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39924. }
  39925. //
  39926. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39927. ${ flowData.vars }
  39928. ${ flowData.code }
  39929. return ${ flowData.result };
  39930. }`;
  39931. //
  39932. return code;
  39933. }
  39934. setupPBO( storageBufferNode ) {
  39935. const attribute = storageBufferNode.value;
  39936. if ( attribute.pbo === undefined ) {
  39937. const originalArray = attribute.array;
  39938. const numElements = attribute.count * attribute.itemSize;
  39939. const { itemSize } = attribute;
  39940. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39941. let format = isInteger ? RedIntegerFormat : RedFormat;
  39942. if ( itemSize === 2 ) {
  39943. format = isInteger ? RGIntegerFormat : RGFormat;
  39944. } else if ( itemSize === 3 ) {
  39945. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39946. } else if ( itemSize === 4 ) {
  39947. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39948. }
  39949. const typeMap = {
  39950. Float32Array: FloatType,
  39951. Uint8Array: UnsignedByteType,
  39952. Uint16Array: UnsignedShortType,
  39953. Uint32Array: UnsignedIntType,
  39954. Int8Array: ByteType,
  39955. Int16Array: ShortType,
  39956. Int32Array: IntType,
  39957. Uint8ClampedArray: UnsignedByteType,
  39958. };
  39959. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39960. let height = Math.ceil( ( numElements / itemSize ) / width );
  39961. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39962. const newSize = width * height * itemSize;
  39963. const newArray = new originalArray.constructor( newSize );
  39964. newArray.set( originalArray, 0 );
  39965. attribute.array = newArray;
  39966. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39967. pboTexture.needsUpdate = true;
  39968. pboTexture.isPBOTexture = true;
  39969. const pbo = new TextureNode( pboTexture, null, null );
  39970. pbo.setPrecision( 'high' );
  39971. attribute.pboNode = pbo;
  39972. attribute.pbo = pbo.value;
  39973. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39974. }
  39975. }
  39976. getPropertyName( node, shaderStage = this.shaderStage ) {
  39977. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39978. return shaderStage.charAt( 0 ) + '_' + node.name;
  39979. }
  39980. return super.getPropertyName( node, shaderStage );
  39981. }
  39982. generatePBO( storageArrayElementNode ) {
  39983. const { node, indexNode } = storageArrayElementNode;
  39984. const attribute = node.value;
  39985. if ( this.renderer.backend.has( attribute ) ) {
  39986. const attributeData = this.renderer.backend.get( attribute );
  39987. attributeData.pbo = attribute.pbo;
  39988. }
  39989. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39990. const textureName = this.getPropertyName( nodeUniform );
  39991. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39992. const indexSnippet = indexNode.build( this, 'uint' );
  39993. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39994. let propertyName = elementNodeData.propertyName;
  39995. if ( propertyName === undefined ) {
  39996. // property element
  39997. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39998. propertyName = this.getPropertyName( nodeVar );
  39999. // property size
  40000. const bufferNodeData = this.getDataFromNode( node );
  40001. let propertySizeName = bufferNodeData.propertySizeName;
  40002. if ( propertySizeName === undefined ) {
  40003. propertySizeName = propertyName + 'Size';
  40004. this.getVarFromNode( node, propertySizeName, 'uint' );
  40005. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  40006. bufferNodeData.propertySizeName = propertySizeName;
  40007. }
  40008. //
  40009. const { itemSize } = attribute;
  40010. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  40011. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  40012. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  40013. //
  40014. let prefix = 'vec4';
  40015. if ( attribute.pbo.type === UnsignedIntType ) {
  40016. prefix = 'uvec4';
  40017. } else if ( attribute.pbo.type === IntType ) {
  40018. prefix = 'ivec4';
  40019. }
  40020. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  40021. elementNodeData.propertyName = propertyName;
  40022. }
  40023. return propertyName;
  40024. }
  40025. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  40026. if ( depthSnippet ) {
  40027. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  40028. } else {
  40029. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40030. }
  40031. }
  40032. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  40033. if ( texture.isDepthTexture ) {
  40034. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  40035. } else {
  40036. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  40037. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  40038. }
  40039. }
  40040. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  40041. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  40042. }
  40043. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  40044. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  40045. }
  40046. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  40047. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  40048. }
  40049. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40050. if ( shaderStage === 'fragment' ) {
  40051. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  40052. } else {
  40053. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  40054. }
  40055. }
  40056. getVars( shaderStage ) {
  40057. const snippets = [];
  40058. const vars = this.vars[ shaderStage ];
  40059. if ( vars !== undefined ) {
  40060. for ( const variable of vars ) {
  40061. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  40062. }
  40063. }
  40064. return snippets.join( '\n\t' );
  40065. }
  40066. getUniforms( shaderStage ) {
  40067. const uniforms = this.uniforms[ shaderStage ];
  40068. const bindingSnippets = [];
  40069. const uniformGroups = {};
  40070. for ( const uniform of uniforms ) {
  40071. let snippet = null;
  40072. let group = false;
  40073. if ( uniform.type === 'texture' ) {
  40074. const texture = uniform.node.value;
  40075. let typePrefix = '';
  40076. if ( texture.isDataTexture === true ) {
  40077. if ( texture.type === UnsignedIntType ) {
  40078. typePrefix = 'u';
  40079. } else if ( texture.type === IntType ) {
  40080. typePrefix = 'i';
  40081. }
  40082. }
  40083. if ( texture.compareFunction ) {
  40084. snippet = `sampler2DShadow ${ uniform.name };`;
  40085. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40086. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  40087. } else {
  40088. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  40089. }
  40090. } else if ( uniform.type === 'cubeTexture' ) {
  40091. snippet = `samplerCube ${ uniform.name };`;
  40092. } else if ( uniform.type === 'texture3D' ) {
  40093. snippet = `sampler3D ${ uniform.name };`;
  40094. } else if ( uniform.type === 'buffer' ) {
  40095. const bufferNode = uniform.node;
  40096. const bufferType = this.getType( bufferNode.bufferType );
  40097. const bufferCount = bufferNode.bufferCount;
  40098. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  40099. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  40100. } else {
  40101. const vectorType = this.getVectorType( uniform.type );
  40102. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  40103. group = true;
  40104. }
  40105. const precision = uniform.node.precision;
  40106. if ( precision !== null ) {
  40107. snippet = precisionLib[ precision ] + ' ' + snippet;
  40108. }
  40109. if ( group ) {
  40110. snippet = '\t' + snippet;
  40111. const groupName = uniform.groupNode.name;
  40112. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  40113. groupSnippets.push( snippet );
  40114. } else {
  40115. snippet = 'uniform ' + snippet;
  40116. bindingSnippets.push( snippet );
  40117. }
  40118. }
  40119. let output = '';
  40120. for ( const name in uniformGroups ) {
  40121. const groupSnippets = uniformGroups[ name ];
  40122. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  40123. }
  40124. output += bindingSnippets.join( '\n' );
  40125. return output;
  40126. }
  40127. getTypeFromAttribute( attribute ) {
  40128. let nodeType = super.getTypeFromAttribute( attribute );
  40129. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  40130. let dataAttribute = attribute;
  40131. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  40132. const array = dataAttribute.array;
  40133. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  40134. nodeType = nodeType.slice( 1 );
  40135. }
  40136. }
  40137. return nodeType;
  40138. }
  40139. getAttributes( shaderStage ) {
  40140. let snippet = '';
  40141. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40142. const attributes = this.getAttributesArray();
  40143. let location = 0;
  40144. for ( const attribute of attributes ) {
  40145. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  40146. }
  40147. }
  40148. return snippet;
  40149. }
  40150. getStructMembers( struct ) {
  40151. const snippets = [];
  40152. const members = struct.getMemberTypes();
  40153. for ( let i = 0; i < members.length; i ++ ) {
  40154. const member = members[ i ];
  40155. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  40156. }
  40157. return snippets.join( '\n' );
  40158. }
  40159. getStructs( shaderStage ) {
  40160. const snippets = [];
  40161. const structs = this.structs[ shaderStage ];
  40162. if ( structs.length === 0 ) {
  40163. return 'layout( location = 0 ) out vec4 fragColor;\n';
  40164. }
  40165. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  40166. const struct = structs[ index ];
  40167. let snippet = '\n';
  40168. snippet += this.getStructMembers( struct );
  40169. snippet += '\n';
  40170. snippets.push( snippet );
  40171. }
  40172. return snippets.join( '\n\n' );
  40173. }
  40174. getVaryings( shaderStage ) {
  40175. let snippet = '';
  40176. const varyings = this.varyings;
  40177. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40178. for ( const varying of varyings ) {
  40179. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  40180. const type = varying.type;
  40181. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40182. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  40183. }
  40184. } else if ( shaderStage === 'fragment' ) {
  40185. for ( const varying of varyings ) {
  40186. if ( varying.needsInterpolation ) {
  40187. const type = varying.type;
  40188. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40189. snippet += `${flat}in ${type} ${varying.name};\n`;
  40190. }
  40191. }
  40192. }
  40193. return snippet;
  40194. }
  40195. getVertexIndex() {
  40196. return 'uint( gl_VertexID )';
  40197. }
  40198. getInstanceIndex() {
  40199. return 'uint( gl_InstanceID )';
  40200. }
  40201. getInvocationLocalIndex() {
  40202. const workgroupSize = this.object.workgroupSize;
  40203. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  40204. return `uint( gl_InstanceID ) % ${size}u`;
  40205. }
  40206. getDrawIndex() {
  40207. const extensions = this.renderer.backend.extensions;
  40208. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  40209. return 'uint( gl_DrawID )';
  40210. }
  40211. return null;
  40212. }
  40213. getFrontFacing() {
  40214. return 'gl_FrontFacing';
  40215. }
  40216. getFragCoord() {
  40217. return 'gl_FragCoord.xy';
  40218. }
  40219. getFragDepth() {
  40220. return 'gl_FragDepth';
  40221. }
  40222. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  40223. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  40224. if ( map.has( name ) === false ) {
  40225. map.set( name, {
  40226. name,
  40227. behavior
  40228. } );
  40229. }
  40230. }
  40231. getExtensions( shaderStage ) {
  40232. const snippets = [];
  40233. if ( shaderStage === 'vertex' ) {
  40234. const ext = this.renderer.backend.extensions;
  40235. const isBatchedMesh = this.object.isBatchedMesh;
  40236. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  40237. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  40238. }
  40239. }
  40240. const extensions = this.extensions[ shaderStage ];
  40241. if ( extensions !== undefined ) {
  40242. for ( const { name, behavior } of extensions.values() ) {
  40243. snippets.push( `#extension ${name} : ${behavior}` );
  40244. }
  40245. }
  40246. return snippets.join( '\n' );
  40247. }
  40248. isAvailable( name ) {
  40249. let result = supports$1[ name ];
  40250. if ( result === undefined ) {
  40251. if ( name === 'float32Filterable' ) {
  40252. const extensions = this.renderer.backend.extensions;
  40253. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  40254. extensions.get( 'OES_texture_float_linear' );
  40255. result = true;
  40256. } else {
  40257. result = false;
  40258. }
  40259. }
  40260. supports$1[ name ] = result;
  40261. }
  40262. return result;
  40263. }
  40264. isFlipY() {
  40265. return true;
  40266. }
  40267. registerTransform( varyingName, attributeNode ) {
  40268. this.transforms.push( { varyingName, attributeNode } );
  40269. }
  40270. getTransforms( /* shaderStage */ ) {
  40271. const transforms = this.transforms;
  40272. let snippet = '';
  40273. for ( let i = 0; i < transforms.length; i ++ ) {
  40274. const transform = transforms[ i ];
  40275. const attributeName = this.getPropertyName( transform.attributeNode );
  40276. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  40277. }
  40278. return snippet;
  40279. }
  40280. _getGLSLUniformStruct( name, vars ) {
  40281. return `
  40282. layout( std140 ) uniform ${name} {
  40283. ${vars}
  40284. };`;
  40285. }
  40286. _getGLSLVertexCode( shaderData ) {
  40287. return `#version 300 es
  40288. ${ this.getSignature() }
  40289. // extensions
  40290. ${shaderData.extensions}
  40291. // precision
  40292. ${ defaultPrecisions }
  40293. // uniforms
  40294. ${shaderData.uniforms}
  40295. // varyings
  40296. ${shaderData.varyings}
  40297. // attributes
  40298. ${shaderData.attributes}
  40299. // codes
  40300. ${shaderData.codes}
  40301. void main() {
  40302. // vars
  40303. ${shaderData.vars}
  40304. // transforms
  40305. ${shaderData.transforms}
  40306. // flow
  40307. ${shaderData.flow}
  40308. gl_PointSize = 1.0;
  40309. }
  40310. `;
  40311. }
  40312. _getGLSLFragmentCode( shaderData ) {
  40313. return `#version 300 es
  40314. ${ this.getSignature() }
  40315. // precision
  40316. ${ defaultPrecisions }
  40317. // uniforms
  40318. ${shaderData.uniforms}
  40319. // varyings
  40320. ${shaderData.varyings}
  40321. // codes
  40322. ${shaderData.codes}
  40323. ${shaderData.structs}
  40324. void main() {
  40325. // vars
  40326. ${shaderData.vars}
  40327. // flow
  40328. ${shaderData.flow}
  40329. }
  40330. `;
  40331. }
  40332. buildCode() {
  40333. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  40334. this.sortBindingGroups();
  40335. for ( const shaderStage in shadersData ) {
  40336. let flow = '// code\n\n';
  40337. flow += this.flowCode[ shaderStage ];
  40338. const flowNodes = this.flowNodes[ shaderStage ];
  40339. const mainNode = flowNodes[ flowNodes.length - 1 ];
  40340. for ( const node of flowNodes ) {
  40341. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  40342. const slotName = node.name;
  40343. if ( slotName ) {
  40344. if ( flow.length > 0 ) flow += '\n';
  40345. flow += `\t// flow -> ${ slotName }\n\t`;
  40346. }
  40347. flow += `${ flowSlotData.code }\n\t`;
  40348. if ( node === mainNode && shaderStage !== 'compute' ) {
  40349. flow += '// result\n\t';
  40350. if ( shaderStage === 'vertex' ) {
  40351. flow += 'gl_Position = ';
  40352. flow += `${ flowSlotData.result };`;
  40353. } else if ( shaderStage === 'fragment' ) {
  40354. if ( ! node.outputNode.isOutputStructNode ) {
  40355. flow += 'fragColor = ';
  40356. flow += `${ flowSlotData.result };`;
  40357. }
  40358. }
  40359. }
  40360. }
  40361. const stageData = shadersData[ shaderStage ];
  40362. stageData.extensions = this.getExtensions( shaderStage );
  40363. stageData.uniforms = this.getUniforms( shaderStage );
  40364. stageData.attributes = this.getAttributes( shaderStage );
  40365. stageData.varyings = this.getVaryings( shaderStage );
  40366. stageData.vars = this.getVars( shaderStage );
  40367. stageData.structs = this.getStructs( shaderStage );
  40368. stageData.codes = this.getCodes( shaderStage );
  40369. stageData.transforms = this.getTransforms( shaderStage );
  40370. stageData.flow = flow;
  40371. }
  40372. if ( this.material !== null ) {
  40373. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  40374. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  40375. } else {
  40376. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  40377. }
  40378. }
  40379. getUniformFromNode( node, type, shaderStage, name = null ) {
  40380. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40381. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40382. let uniformGPU = nodeData.uniformGPU;
  40383. if ( uniformGPU === undefined ) {
  40384. const group = node.groupNode;
  40385. const groupName = group.name;
  40386. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40387. if ( type === 'texture' ) {
  40388. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  40389. bindings.push( uniformGPU );
  40390. } else if ( type === 'cubeTexture' ) {
  40391. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  40392. bindings.push( uniformGPU );
  40393. } else if ( type === 'texture3D' ) {
  40394. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  40395. bindings.push( uniformGPU );
  40396. } else if ( type === 'buffer' ) {
  40397. node.name = `NodeBuffer_${ node.id }`;
  40398. uniformNode.name = `buffer${ node.id }`;
  40399. const buffer = new NodeUniformBuffer( node, group );
  40400. buffer.name = node.name;
  40401. bindings.push( buffer );
  40402. uniformGPU = buffer;
  40403. } else {
  40404. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40405. let uniformsGroup = uniformsStage[ groupName ];
  40406. if ( uniformsGroup === undefined ) {
  40407. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  40408. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40409. uniformsStage[ groupName ] = uniformsGroup;
  40410. bindings.push( uniformsGroup );
  40411. }
  40412. uniformGPU = this.getNodeUniform( uniformNode, type );
  40413. uniformsGroup.addUniform( uniformGPU );
  40414. }
  40415. nodeData.uniformGPU = uniformGPU;
  40416. }
  40417. return uniformNode;
  40418. }
  40419. }
  40420. let vector2 = null;
  40421. let vector4 = null;
  40422. let color4 = null;
  40423. class Backend {
  40424. constructor( parameters = {} ) {
  40425. this.parameters = Object.assign( {}, parameters );
  40426. this.data = new WeakMap();
  40427. this.renderer = null;
  40428. this.domElement = null;
  40429. }
  40430. async init( renderer ) {
  40431. this.renderer = renderer;
  40432. }
  40433. // render context
  40434. begin( /*renderContext*/ ) { }
  40435. finish( /*renderContext*/ ) { }
  40436. // render object
  40437. draw( /*renderObject, info*/ ) { }
  40438. // program
  40439. createProgram( /*program*/ ) { }
  40440. destroyProgram( /*program*/ ) { }
  40441. // bindings
  40442. createBindings( /*bingGroup, bindings*/ ) { }
  40443. updateBindings( /*bingGroup, bindings*/ ) { }
  40444. // pipeline
  40445. createRenderPipeline( /*renderObject*/ ) { }
  40446. createComputePipeline( /*computeNode, pipeline*/ ) { }
  40447. destroyPipeline( /*pipeline*/ ) { }
  40448. // cache key
  40449. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  40450. getRenderCacheKey( /*renderObject*/ ) { } // return String
  40451. // node builder
  40452. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  40453. // textures
  40454. createSampler( /*texture*/ ) { }
  40455. createDefaultTexture( /*texture*/ ) { }
  40456. createTexture( /*texture*/ ) { }
  40457. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  40458. // attributes
  40459. createAttribute( /*attribute*/ ) { }
  40460. createIndexAttribute( /*attribute*/ ) { }
  40461. updateAttribute( /*attribute*/ ) { }
  40462. destroyAttribute( /*attribute*/ ) { }
  40463. // canvas
  40464. getContext() { }
  40465. updateSize() { }
  40466. // utils
  40467. resolveTimestampAsync( /*renderContext, type*/ ) { }
  40468. hasFeatureAsync( /*name*/ ) { } // return Boolean
  40469. hasFeature( /*name*/ ) { } // return Boolean
  40470. getInstanceCount( renderObject ) {
  40471. const { object, geometry } = renderObject;
  40472. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  40473. }
  40474. getDrawingBufferSize() {
  40475. vector2 = vector2 || new Vector2();
  40476. return this.renderer.getDrawingBufferSize( vector2 );
  40477. }
  40478. getScissor() {
  40479. vector4 = vector4 || new Vector4();
  40480. return this.renderer.getScissor( vector4 );
  40481. }
  40482. setScissorTest( /*boolean*/ ) { }
  40483. getClearColor() {
  40484. const renderer = this.renderer;
  40485. color4 = color4 || new Color4();
  40486. renderer.getClearColor( color4 );
  40487. color4.getRGB( color4, this.renderer.currentColorSpace );
  40488. return color4;
  40489. }
  40490. getDomElement() {
  40491. let domElement = this.domElement;
  40492. if ( domElement === null ) {
  40493. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  40494. // OffscreenCanvas does not have setAttribute, see #22811
  40495. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  40496. this.domElement = domElement;
  40497. }
  40498. return domElement;
  40499. }
  40500. // resource properties
  40501. set( object, value ) {
  40502. this.data.set( object, value );
  40503. }
  40504. get( object ) {
  40505. let map = this.data.get( object );
  40506. if ( map === undefined ) {
  40507. map = {};
  40508. this.data.set( object, map );
  40509. }
  40510. return map;
  40511. }
  40512. has( object ) {
  40513. return this.data.has( object );
  40514. }
  40515. delete( object ) {
  40516. this.data.delete( object );
  40517. }
  40518. }
  40519. let _id$1 = 0;
  40520. class DualAttributeData {
  40521. constructor( attributeData, dualBuffer ) {
  40522. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  40523. this.type = attributeData.type;
  40524. this.bufferType = attributeData.bufferType;
  40525. this.pbo = attributeData.pbo;
  40526. this.byteLength = attributeData.byteLength;
  40527. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  40528. this.version = attributeData.version;
  40529. this.isInteger = attributeData.isInteger;
  40530. this.activeBufferIndex = 0;
  40531. this.baseId = attributeData.id;
  40532. }
  40533. get id() {
  40534. return `${ this.baseId }|${ this.activeBufferIndex }`;
  40535. }
  40536. get bufferGPU() {
  40537. return this.buffers[ this.activeBufferIndex ];
  40538. }
  40539. get transformBuffer() {
  40540. return this.buffers[ this.activeBufferIndex ^ 1 ];
  40541. }
  40542. switchBuffers() {
  40543. this.activeBufferIndex ^= 1;
  40544. }
  40545. }
  40546. class WebGLAttributeUtils {
  40547. constructor( backend ) {
  40548. this.backend = backend;
  40549. }
  40550. createAttribute( attribute, bufferType ) {
  40551. const backend = this.backend;
  40552. const { gl } = backend;
  40553. const array = attribute.array;
  40554. const usage = attribute.usage || gl.STATIC_DRAW;
  40555. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40556. const bufferData = backend.get( bufferAttribute );
  40557. let bufferGPU = bufferData.bufferGPU;
  40558. if ( bufferGPU === undefined ) {
  40559. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  40560. bufferData.bufferGPU = bufferGPU;
  40561. bufferData.bufferType = bufferType;
  40562. bufferData.version = bufferAttribute.version;
  40563. }
  40564. //attribute.onUploadCallback();
  40565. let type;
  40566. if ( array instanceof Float32Array ) {
  40567. type = gl.FLOAT;
  40568. } else if ( array instanceof Uint16Array ) {
  40569. if ( attribute.isFloat16BufferAttribute ) {
  40570. type = gl.HALF_FLOAT;
  40571. } else {
  40572. type = gl.UNSIGNED_SHORT;
  40573. }
  40574. } else if ( array instanceof Int16Array ) {
  40575. type = gl.SHORT;
  40576. } else if ( array instanceof Uint32Array ) {
  40577. type = gl.UNSIGNED_INT;
  40578. } else if ( array instanceof Int32Array ) {
  40579. type = gl.INT;
  40580. } else if ( array instanceof Int8Array ) {
  40581. type = gl.BYTE;
  40582. } else if ( array instanceof Uint8Array ) {
  40583. type = gl.UNSIGNED_BYTE;
  40584. } else if ( array instanceof Uint8ClampedArray ) {
  40585. type = gl.UNSIGNED_BYTE;
  40586. } else {
  40587. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  40588. }
  40589. let attributeData = {
  40590. bufferGPU,
  40591. bufferType,
  40592. type,
  40593. byteLength: array.byteLength,
  40594. bytesPerElement: array.BYTES_PER_ELEMENT,
  40595. version: attribute.version,
  40596. pbo: attribute.pbo,
  40597. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  40598. id: _id$1 ++
  40599. };
  40600. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  40601. // create buffer for tranform feedback use
  40602. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  40603. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  40604. }
  40605. backend.set( attribute, attributeData );
  40606. }
  40607. updateAttribute( attribute ) {
  40608. const backend = this.backend;
  40609. const { gl } = backend;
  40610. const array = attribute.array;
  40611. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40612. const bufferData = backend.get( bufferAttribute );
  40613. const bufferType = bufferData.bufferType;
  40614. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  40615. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  40616. if ( updateRanges.length === 0 ) {
  40617. // Not using update ranges
  40618. gl.bufferSubData( bufferType, 0, array );
  40619. } else {
  40620. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  40621. const range = updateRanges[ i ];
  40622. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  40623. array, range.start, range.count );
  40624. }
  40625. bufferAttribute.clearUpdateRanges();
  40626. }
  40627. gl.bindBuffer( bufferType, null );
  40628. bufferData.version = bufferAttribute.version;
  40629. }
  40630. destroyAttribute( attribute ) {
  40631. const backend = this.backend;
  40632. const { gl } = backend;
  40633. if ( attribute.isInterleavedBufferAttribute ) {
  40634. backend.delete( attribute.data );
  40635. }
  40636. const attributeData = backend.get( attribute );
  40637. gl.deleteBuffer( attributeData.bufferGPU );
  40638. backend.delete( attribute );
  40639. }
  40640. async getArrayBufferAsync( attribute ) {
  40641. const backend = this.backend;
  40642. const { gl } = backend;
  40643. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40644. const { bufferGPU } = backend.get( bufferAttribute );
  40645. const array = attribute.array;
  40646. const byteLength = array.byteLength;
  40647. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  40648. const writeBuffer = gl.createBuffer();
  40649. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40650. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  40651. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  40652. await backend.utils._clientWaitAsync();
  40653. const dstBuffer = new attribute.array.constructor( array.length );
  40654. // Ensure the buffer is bound before reading
  40655. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40656. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  40657. gl.deleteBuffer( writeBuffer );
  40658. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  40659. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  40660. return dstBuffer.buffer;
  40661. }
  40662. _createBuffer( gl, bufferType, array, usage ) {
  40663. const bufferGPU = gl.createBuffer();
  40664. gl.bindBuffer( bufferType, bufferGPU );
  40665. gl.bufferData( bufferType, array, usage );
  40666. gl.bindBuffer( bufferType, null );
  40667. return bufferGPU;
  40668. }
  40669. }
  40670. let initialized$1 = false, equationToGL, factorToGL;
  40671. class WebGLState {
  40672. constructor( backend ) {
  40673. this.backend = backend;
  40674. this.gl = this.backend.gl;
  40675. this.enabled = {};
  40676. this.currentFlipSided = null;
  40677. this.currentCullFace = null;
  40678. this.currentProgram = null;
  40679. this.currentBlendingEnabled = false;
  40680. this.currentBlending = null;
  40681. this.currentBlendSrc = null;
  40682. this.currentBlendDst = null;
  40683. this.currentBlendSrcAlpha = null;
  40684. this.currentBlendDstAlpha = null;
  40685. this.currentPremultipledAlpha = null;
  40686. this.currentPolygonOffsetFactor = null;
  40687. this.currentPolygonOffsetUnits = null;
  40688. this.currentColorMask = null;
  40689. this.currentDepthFunc = null;
  40690. this.currentDepthMask = null;
  40691. this.currentStencilFunc = null;
  40692. this.currentStencilRef = null;
  40693. this.currentStencilFuncMask = null;
  40694. this.currentStencilFail = null;
  40695. this.currentStencilZFail = null;
  40696. this.currentStencilZPass = null;
  40697. this.currentStencilMask = null;
  40698. this.currentLineWidth = null;
  40699. this.currentBoundFramebuffers = {};
  40700. this.currentDrawbuffers = new WeakMap();
  40701. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  40702. this.currentTextureSlot = null;
  40703. this.currentBoundTextures = {};
  40704. this.currentBoundBufferBases = {};
  40705. if ( initialized$1 === false ) {
  40706. this._init( this.gl );
  40707. initialized$1 = true;
  40708. }
  40709. }
  40710. _init( gl ) {
  40711. // Store only WebGL constants here.
  40712. equationToGL = {
  40713. [ AddEquation ]: gl.FUNC_ADD,
  40714. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  40715. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  40716. };
  40717. factorToGL = {
  40718. [ ZeroFactor ]: gl.ZERO,
  40719. [ OneFactor ]: gl.ONE,
  40720. [ SrcColorFactor ]: gl.SRC_COLOR,
  40721. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  40722. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  40723. [ DstColorFactor ]: gl.DST_COLOR,
  40724. [ DstAlphaFactor ]: gl.DST_ALPHA,
  40725. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  40726. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  40727. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  40728. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  40729. };
  40730. }
  40731. enable( id ) {
  40732. const { enabled } = this;
  40733. if ( enabled[ id ] !== true ) {
  40734. this.gl.enable( id );
  40735. enabled[ id ] = true;
  40736. }
  40737. }
  40738. disable( id ) {
  40739. const { enabled } = this;
  40740. if ( enabled[ id ] !== false ) {
  40741. this.gl.disable( id );
  40742. enabled[ id ] = false;
  40743. }
  40744. }
  40745. setFlipSided( flipSided ) {
  40746. if ( this.currentFlipSided !== flipSided ) {
  40747. const { gl } = this;
  40748. if ( flipSided ) {
  40749. gl.frontFace( gl.CW );
  40750. } else {
  40751. gl.frontFace( gl.CCW );
  40752. }
  40753. this.currentFlipSided = flipSided;
  40754. }
  40755. }
  40756. setCullFace( cullFace ) {
  40757. const { gl } = this;
  40758. if ( cullFace !== CullFaceNone ) {
  40759. this.enable( gl.CULL_FACE );
  40760. if ( cullFace !== this.currentCullFace ) {
  40761. if ( cullFace === CullFaceBack ) {
  40762. gl.cullFace( gl.BACK );
  40763. } else if ( cullFace === CullFaceFront ) {
  40764. gl.cullFace( gl.FRONT );
  40765. } else {
  40766. gl.cullFace( gl.FRONT_AND_BACK );
  40767. }
  40768. }
  40769. } else {
  40770. this.disable( gl.CULL_FACE );
  40771. }
  40772. this.currentCullFace = cullFace;
  40773. }
  40774. setLineWidth( width ) {
  40775. const { currentLineWidth, gl } = this;
  40776. if ( width !== currentLineWidth ) {
  40777. gl.lineWidth( width );
  40778. this.currentLineWidth = width;
  40779. }
  40780. }
  40781. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  40782. const { gl } = this;
  40783. if ( blending === NoBlending ) {
  40784. if ( this.currentBlendingEnabled === true ) {
  40785. this.disable( gl.BLEND );
  40786. this.currentBlendingEnabled = false;
  40787. }
  40788. return;
  40789. }
  40790. if ( this.currentBlendingEnabled === false ) {
  40791. this.enable( gl.BLEND );
  40792. this.currentBlendingEnabled = true;
  40793. }
  40794. if ( blending !== CustomBlending ) {
  40795. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  40796. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  40797. gl.blendEquation( gl.FUNC_ADD );
  40798. this.currentBlendEquation = AddEquation;
  40799. this.currentBlendEquationAlpha = AddEquation;
  40800. }
  40801. if ( premultipliedAlpha ) {
  40802. switch ( blending ) {
  40803. case NormalBlending:
  40804. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40805. break;
  40806. case AdditiveBlending:
  40807. gl.blendFunc( gl.ONE, gl.ONE );
  40808. break;
  40809. case SubtractiveBlending:
  40810. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40811. break;
  40812. case MultiplyBlending:
  40813. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  40814. break;
  40815. default:
  40816. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40817. break;
  40818. }
  40819. } else {
  40820. switch ( blending ) {
  40821. case NormalBlending:
  40822. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40823. break;
  40824. case AdditiveBlending:
  40825. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  40826. break;
  40827. case SubtractiveBlending:
  40828. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40829. break;
  40830. case MultiplyBlending:
  40831. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  40832. break;
  40833. default:
  40834. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40835. break;
  40836. }
  40837. }
  40838. this.currentBlendSrc = null;
  40839. this.currentBlendDst = null;
  40840. this.currentBlendSrcAlpha = null;
  40841. this.currentBlendDstAlpha = null;
  40842. this.currentBlending = blending;
  40843. this.currentPremultipledAlpha = premultipliedAlpha;
  40844. }
  40845. return;
  40846. }
  40847. // custom blending
  40848. blendEquationAlpha = blendEquationAlpha || blendEquation;
  40849. blendSrcAlpha = blendSrcAlpha || blendSrc;
  40850. blendDstAlpha = blendDstAlpha || blendDst;
  40851. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  40852. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  40853. this.currentBlendEquation = blendEquation;
  40854. this.currentBlendEquationAlpha = blendEquationAlpha;
  40855. }
  40856. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  40857. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  40858. this.currentBlendSrc = blendSrc;
  40859. this.currentBlendDst = blendDst;
  40860. this.currentBlendSrcAlpha = blendSrcAlpha;
  40861. this.currentBlendDstAlpha = blendDstAlpha;
  40862. }
  40863. this.currentBlending = blending;
  40864. this.currentPremultipledAlpha = false;
  40865. }
  40866. setColorMask( colorMask ) {
  40867. if ( this.currentColorMask !== colorMask ) {
  40868. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  40869. this.currentColorMask = colorMask;
  40870. }
  40871. }
  40872. setDepthTest( depthTest ) {
  40873. const { gl } = this;
  40874. if ( depthTest ) {
  40875. this.enable( gl.DEPTH_TEST );
  40876. } else {
  40877. this.disable( gl.DEPTH_TEST );
  40878. }
  40879. }
  40880. setDepthMask( depthMask ) {
  40881. if ( this.currentDepthMask !== depthMask ) {
  40882. this.gl.depthMask( depthMask );
  40883. this.currentDepthMask = depthMask;
  40884. }
  40885. }
  40886. setDepthFunc( depthFunc ) {
  40887. if ( this.currentDepthFunc !== depthFunc ) {
  40888. const { gl } = this;
  40889. switch ( depthFunc ) {
  40890. case NeverDepth:
  40891. gl.depthFunc( gl.NEVER );
  40892. break;
  40893. case AlwaysDepth:
  40894. gl.depthFunc( gl.ALWAYS );
  40895. break;
  40896. case LessDepth:
  40897. gl.depthFunc( gl.LESS );
  40898. break;
  40899. case LessEqualDepth:
  40900. gl.depthFunc( gl.LEQUAL );
  40901. break;
  40902. case EqualDepth:
  40903. gl.depthFunc( gl.EQUAL );
  40904. break;
  40905. case GreaterEqualDepth:
  40906. gl.depthFunc( gl.GEQUAL );
  40907. break;
  40908. case GreaterDepth:
  40909. gl.depthFunc( gl.GREATER );
  40910. break;
  40911. case NotEqualDepth:
  40912. gl.depthFunc( gl.NOTEQUAL );
  40913. break;
  40914. default:
  40915. gl.depthFunc( gl.LEQUAL );
  40916. }
  40917. this.currentDepthFunc = depthFunc;
  40918. }
  40919. }
  40920. setStencilTest( stencilTest ) {
  40921. const { gl } = this;
  40922. if ( stencilTest ) {
  40923. this.enable( gl.STENCIL_TEST );
  40924. } else {
  40925. this.disable( gl.STENCIL_TEST );
  40926. }
  40927. }
  40928. setStencilMask( stencilMask ) {
  40929. if ( this.currentStencilMask !== stencilMask ) {
  40930. this.gl.stencilMask( stencilMask );
  40931. this.currentStencilMask = stencilMask;
  40932. }
  40933. }
  40934. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  40935. if ( this.currentStencilFunc !== stencilFunc ||
  40936. this.currentStencilRef !== stencilRef ||
  40937. this.currentStencilFuncMask !== stencilMask ) {
  40938. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  40939. this.currentStencilFunc = stencilFunc;
  40940. this.currentStencilRef = stencilRef;
  40941. this.currentStencilFuncMask = stencilMask;
  40942. }
  40943. }
  40944. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  40945. if ( this.currentStencilFail !== stencilFail ||
  40946. this.currentStencilZFail !== stencilZFail ||
  40947. this.currentStencilZPass !== stencilZPass ) {
  40948. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  40949. this.currentStencilFail = stencilFail;
  40950. this.currentStencilZFail = stencilZFail;
  40951. this.currentStencilZPass = stencilZPass;
  40952. }
  40953. }
  40954. setMaterial( material, frontFaceCW ) {
  40955. const { gl } = this;
  40956. material.side === DoubleSide
  40957. ? this.disable( gl.CULL_FACE )
  40958. : this.enable( gl.CULL_FACE );
  40959. let flipSided = ( material.side === BackSide );
  40960. if ( frontFaceCW ) flipSided = ! flipSided;
  40961. this.setFlipSided( flipSided );
  40962. ( material.blending === NormalBlending && material.transparent === false )
  40963. ? this.setBlending( NoBlending )
  40964. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  40965. this.setDepthFunc( material.depthFunc );
  40966. this.setDepthTest( material.depthTest );
  40967. this.setDepthMask( material.depthWrite );
  40968. this.setColorMask( material.colorWrite );
  40969. const stencilWrite = material.stencilWrite;
  40970. this.setStencilTest( stencilWrite );
  40971. if ( stencilWrite ) {
  40972. this.setStencilMask( material.stencilWriteMask );
  40973. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  40974. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  40975. }
  40976. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  40977. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  40978. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  40979. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  40980. }
  40981. setPolygonOffset( polygonOffset, factor, units ) {
  40982. const { gl } = this;
  40983. if ( polygonOffset ) {
  40984. this.enable( gl.POLYGON_OFFSET_FILL );
  40985. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  40986. gl.polygonOffset( factor, units );
  40987. this.currentPolygonOffsetFactor = factor;
  40988. this.currentPolygonOffsetUnits = units;
  40989. }
  40990. } else {
  40991. this.disable( gl.POLYGON_OFFSET_FILL );
  40992. }
  40993. }
  40994. useProgram( program ) {
  40995. if ( this.currentProgram !== program ) {
  40996. this.gl.useProgram( program );
  40997. this.currentProgram = program;
  40998. return true;
  40999. }
  41000. return false;
  41001. }
  41002. // framebuffer
  41003. bindFramebuffer( target, framebuffer ) {
  41004. const { gl, currentBoundFramebuffers } = this;
  41005. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  41006. gl.bindFramebuffer( target, framebuffer );
  41007. currentBoundFramebuffers[ target ] = framebuffer;
  41008. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  41009. if ( target === gl.DRAW_FRAMEBUFFER ) {
  41010. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  41011. }
  41012. if ( target === gl.FRAMEBUFFER ) {
  41013. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  41014. }
  41015. return true;
  41016. }
  41017. return false;
  41018. }
  41019. drawBuffers( renderContext, framebuffer ) {
  41020. const { gl } = this;
  41021. let drawBuffers = [];
  41022. let needsUpdate = false;
  41023. if ( renderContext.textures !== null ) {
  41024. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  41025. if ( drawBuffers === undefined ) {
  41026. drawBuffers = [];
  41027. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  41028. }
  41029. const textures = renderContext.textures;
  41030. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  41031. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  41032. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  41033. }
  41034. drawBuffers.length = textures.length;
  41035. needsUpdate = true;
  41036. }
  41037. } else {
  41038. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  41039. drawBuffers[ 0 ] = gl.BACK;
  41040. needsUpdate = true;
  41041. }
  41042. }
  41043. if ( needsUpdate ) {
  41044. gl.drawBuffers( drawBuffers );
  41045. }
  41046. }
  41047. // texture
  41048. activeTexture( webglSlot ) {
  41049. const { gl, currentTextureSlot, maxTextures } = this;
  41050. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41051. if ( currentTextureSlot !== webglSlot ) {
  41052. gl.activeTexture( webglSlot );
  41053. this.currentTextureSlot = webglSlot;
  41054. }
  41055. }
  41056. bindTexture( webglType, webglTexture, webglSlot ) {
  41057. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  41058. if ( webglSlot === undefined ) {
  41059. if ( currentTextureSlot === null ) {
  41060. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41061. } else {
  41062. webglSlot = currentTextureSlot;
  41063. }
  41064. }
  41065. let boundTexture = currentBoundTextures[ webglSlot ];
  41066. if ( boundTexture === undefined ) {
  41067. boundTexture = { type: undefined, texture: undefined };
  41068. currentBoundTextures[ webglSlot ] = boundTexture;
  41069. }
  41070. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  41071. if ( currentTextureSlot !== webglSlot ) {
  41072. gl.activeTexture( webglSlot );
  41073. this.currentTextureSlot = webglSlot;
  41074. }
  41075. gl.bindTexture( webglType, webglTexture );
  41076. boundTexture.type = webglType;
  41077. boundTexture.texture = webglTexture;
  41078. }
  41079. }
  41080. bindBufferBase( target, index, buffer ) {
  41081. const { gl } = this;
  41082. const key = `${target}-${index}`;
  41083. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  41084. gl.bindBufferBase( target, index, buffer );
  41085. this.currentBoundBufferBases[ key ] = buffer;
  41086. return true;
  41087. }
  41088. return false;
  41089. }
  41090. unbindTexture() {
  41091. const { gl, currentTextureSlot, currentBoundTextures } = this;
  41092. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  41093. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  41094. gl.bindTexture( boundTexture.type, null );
  41095. boundTexture.type = undefined;
  41096. boundTexture.texture = undefined;
  41097. }
  41098. }
  41099. }
  41100. class WebGLUtils {
  41101. constructor( backend ) {
  41102. this.backend = backend;
  41103. this.gl = this.backend.gl;
  41104. this.extensions = backend.extensions;
  41105. }
  41106. convert( p, colorSpace = NoColorSpace ) {
  41107. const { gl, extensions } = this;
  41108. let extension;
  41109. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  41110. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  41111. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  41112. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  41113. if ( p === ByteType ) return gl.BYTE;
  41114. if ( p === ShortType ) return gl.SHORT;
  41115. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  41116. if ( p === IntType ) return gl.INT;
  41117. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  41118. if ( p === FloatType ) return gl.FLOAT;
  41119. if ( p === HalfFloatType ) {
  41120. return gl.HALF_FLOAT;
  41121. }
  41122. if ( p === AlphaFormat ) return gl.ALPHA;
  41123. if ( p === RGBFormat ) return gl.RGB;
  41124. if ( p === RGBAFormat ) return gl.RGBA;
  41125. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  41126. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  41127. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  41128. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  41129. // WebGL2 formats.
  41130. if ( p === RedFormat ) return gl.RED;
  41131. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  41132. if ( p === RGFormat ) return gl.RG;
  41133. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  41134. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  41135. // S3TC
  41136. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  41137. if ( colorSpace === SRGBColorSpace ) {
  41138. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  41139. if ( extension !== null ) {
  41140. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  41141. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  41142. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  41143. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  41144. } else {
  41145. return null;
  41146. }
  41147. } else {
  41148. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  41149. if ( extension !== null ) {
  41150. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  41151. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41152. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41153. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41154. } else {
  41155. return null;
  41156. }
  41157. }
  41158. }
  41159. // PVRTC
  41160. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  41161. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  41162. if ( extension !== null ) {
  41163. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  41164. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  41165. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  41166. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  41167. } else {
  41168. return null;
  41169. }
  41170. }
  41171. // ETC
  41172. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  41173. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  41174. if ( extension !== null ) {
  41175. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  41176. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  41177. } else {
  41178. return null;
  41179. }
  41180. }
  41181. // ASTC
  41182. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  41183. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  41184. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  41185. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  41186. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  41187. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  41188. if ( extension !== null ) {
  41189. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  41190. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  41191. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  41192. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  41193. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  41194. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  41195. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  41196. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  41197. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  41198. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  41199. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  41200. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  41201. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  41202. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  41203. } else {
  41204. return null;
  41205. }
  41206. }
  41207. // BPTC
  41208. if ( p === RGBA_BPTC_Format ) {
  41209. extension = extensions.get( 'EXT_texture_compression_bptc' );
  41210. if ( extension !== null ) {
  41211. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  41212. } else {
  41213. return null;
  41214. }
  41215. }
  41216. // RGTC
  41217. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  41218. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  41219. if ( extension !== null ) {
  41220. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  41221. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  41222. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  41223. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  41224. } else {
  41225. return null;
  41226. }
  41227. }
  41228. //
  41229. if ( p === UnsignedInt248Type ) {
  41230. return gl.UNSIGNED_INT_24_8;
  41231. }
  41232. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  41233. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  41234. }
  41235. _clientWaitAsync() {
  41236. const { gl } = this;
  41237. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  41238. gl.flush();
  41239. return new Promise( ( resolve, reject ) => {
  41240. function test() {
  41241. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  41242. if ( res === gl.WAIT_FAILED ) {
  41243. gl.deleteSync( sync );
  41244. reject();
  41245. return;
  41246. }
  41247. if ( res === gl.TIMEOUT_EXPIRED ) {
  41248. requestAnimationFrame( test );
  41249. return;
  41250. }
  41251. gl.deleteSync( sync );
  41252. resolve();
  41253. }
  41254. test();
  41255. } );
  41256. }
  41257. }
  41258. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  41259. class WebGLTextureUtils {
  41260. constructor( backend ) {
  41261. this.backend = backend;
  41262. this.gl = backend.gl;
  41263. this.extensions = backend.extensions;
  41264. this.defaultTextures = {};
  41265. if ( initialized === false ) {
  41266. this._init( this.gl );
  41267. initialized = true;
  41268. }
  41269. }
  41270. _init( gl ) {
  41271. // Store only WebGL constants here.
  41272. wrappingToGL = {
  41273. [ RepeatWrapping ]: gl.REPEAT,
  41274. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  41275. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  41276. };
  41277. filterToGL = {
  41278. [ NearestFilter ]: gl.NEAREST,
  41279. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  41280. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  41281. [ LinearFilter ]: gl.LINEAR,
  41282. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  41283. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  41284. };
  41285. compareToGL = {
  41286. [ NeverCompare ]: gl.NEVER,
  41287. [ AlwaysCompare ]: gl.ALWAYS,
  41288. [ LessCompare ]: gl.LESS,
  41289. [ LessEqualCompare ]: gl.LEQUAL,
  41290. [ EqualCompare ]: gl.EQUAL,
  41291. [ GreaterEqualCompare ]: gl.GEQUAL,
  41292. [ GreaterCompare ]: gl.GREATER,
  41293. [ NotEqualCompare ]: gl.NOTEQUAL
  41294. };
  41295. }
  41296. filterFallback( f ) {
  41297. const { gl } = this;
  41298. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  41299. return gl.NEAREST;
  41300. }
  41301. return gl.LINEAR;
  41302. }
  41303. getGLTextureType( texture ) {
  41304. const { gl } = this;
  41305. let glTextureType;
  41306. if ( texture.isCubeTexture === true ) {
  41307. glTextureType = gl.TEXTURE_CUBE_MAP;
  41308. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41309. glTextureType = gl.TEXTURE_2D_ARRAY;
  41310. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  41311. glTextureType = gl.TEXTURE_3D;
  41312. } else {
  41313. glTextureType = gl.TEXTURE_2D;
  41314. }
  41315. return glTextureType;
  41316. }
  41317. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  41318. const { gl, extensions } = this;
  41319. if ( internalFormatName !== null ) {
  41320. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  41321. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  41322. }
  41323. let internalFormat = glFormat;
  41324. if ( glFormat === gl.RED ) {
  41325. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  41326. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  41327. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  41328. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  41329. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41330. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41331. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41332. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41333. }
  41334. if ( glFormat === gl.RED_INTEGER ) {
  41335. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  41336. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  41337. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41338. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41339. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41340. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41341. }
  41342. if ( glFormat === gl.RG ) {
  41343. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  41344. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  41345. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  41346. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  41347. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41348. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41349. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41350. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41351. }
  41352. if ( glFormat === gl.RG_INTEGER ) {
  41353. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  41354. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  41355. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41356. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41357. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41358. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41359. }
  41360. if ( glFormat === gl.RGB ) {
  41361. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  41362. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  41363. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  41364. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  41365. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41366. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41367. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41368. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41369. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  41370. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  41371. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41372. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  41373. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  41374. }
  41375. if ( glFormat === gl.RGB_INTEGER ) {
  41376. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  41377. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  41378. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41379. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41380. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41381. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41382. }
  41383. if ( glFormat === gl.RGBA ) {
  41384. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  41385. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  41386. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  41387. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  41388. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41389. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41390. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41391. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41392. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  41393. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  41394. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41395. }
  41396. if ( glFormat === gl.RGBA_INTEGER ) {
  41397. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  41398. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  41399. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41400. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41401. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41402. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41403. }
  41404. if ( glFormat === gl.DEPTH_COMPONENT ) {
  41405. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  41406. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  41407. }
  41408. if ( glFormat === gl.DEPTH_STENCIL ) {
  41409. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  41410. }
  41411. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  41412. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  41413. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  41414. extensions.get( 'EXT_color_buffer_float' );
  41415. }
  41416. return internalFormat;
  41417. }
  41418. setTextureParameters( textureType, texture ) {
  41419. const { gl, extensions, backend } = this;
  41420. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  41421. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  41422. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  41423. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  41424. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  41425. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  41426. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  41427. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  41428. }
  41429. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  41430. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  41431. // follow WebGPU backend mapping for texture filtering
  41432. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  41433. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  41434. if ( texture.compareFunction ) {
  41435. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  41436. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  41437. }
  41438. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41439. if ( texture.magFilter === NearestFilter ) return;
  41440. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  41441. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  41442. if ( texture.anisotropy > 1 ) {
  41443. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41444. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  41445. }
  41446. }
  41447. }
  41448. createDefaultTexture( texture ) {
  41449. const { gl, backend, defaultTextures } = this;
  41450. const glTextureType = this.getGLTextureType( texture );
  41451. let textureGPU = defaultTextures[ glTextureType ];
  41452. if ( textureGPU === undefined ) {
  41453. textureGPU = gl.createTexture();
  41454. backend.state.bindTexture( glTextureType, textureGPU );
  41455. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  41456. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  41457. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  41458. defaultTextures[ glTextureType ] = textureGPU;
  41459. }
  41460. backend.set( texture, {
  41461. textureGPU,
  41462. glTextureType,
  41463. isDefault: true
  41464. } );
  41465. }
  41466. createTexture( texture, options ) {
  41467. const { gl, backend } = this;
  41468. const { levels, width, height, depth } = options;
  41469. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  41470. const glType = backend.utils.convert( texture.type );
  41471. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  41472. const textureGPU = gl.createTexture();
  41473. const glTextureType = this.getGLTextureType( texture );
  41474. backend.state.bindTexture( glTextureType, textureGPU );
  41475. this.setTextureParameters( glTextureType, texture );
  41476. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  41477. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  41478. } else if ( texture.isData3DTexture ) {
  41479. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  41480. } else if ( ! texture.isVideoTexture ) {
  41481. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  41482. }
  41483. backend.set( texture, {
  41484. textureGPU,
  41485. glTextureType,
  41486. glFormat,
  41487. glType,
  41488. glInternalFormat
  41489. } );
  41490. }
  41491. copyBufferToTexture( buffer, texture ) {
  41492. const { gl, backend } = this;
  41493. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  41494. const { width, height } = texture.source.data;
  41495. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  41496. backend.state.bindTexture( glTextureType, textureGPU );
  41497. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  41498. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  41499. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  41500. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  41501. backend.state.unbindTexture();
  41502. // debug
  41503. // const framebuffer = gl.createFramebuffer();
  41504. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  41505. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  41506. // const readout = new Float32Array( width * height * 4 );
  41507. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  41508. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  41509. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  41510. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  41511. // console.log( readout );
  41512. }
  41513. updateTexture( texture, options ) {
  41514. const { gl } = this;
  41515. const { width, height } = options;
  41516. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  41517. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  41518. return;
  41519. const getImage = ( source ) => {
  41520. if ( source.isDataTexture ) {
  41521. return source.image.data;
  41522. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  41523. return source;
  41524. }
  41525. return source.data;
  41526. };
  41527. this.backend.state.bindTexture( glTextureType, textureGPU );
  41528. this.setTextureParameters( glTextureType, texture );
  41529. if ( texture.isCompressedTexture ) {
  41530. const mipmaps = texture.mipmaps;
  41531. const image = options.image;
  41532. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41533. const mipmap = mipmaps[ i ];
  41534. if ( texture.isCompressedArrayTexture ) {
  41535. if ( texture.format !== gl.RGBA ) {
  41536. if ( glFormat !== null ) {
  41537. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  41538. } else {
  41539. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  41540. }
  41541. } else {
  41542. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  41543. }
  41544. } else {
  41545. if ( glFormat !== null ) {
  41546. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  41547. } else {
  41548. console.warn( 'Unsupported compressed texture format' );
  41549. }
  41550. }
  41551. }
  41552. } else if ( texture.isCubeTexture ) {
  41553. const images = options.images;
  41554. for ( let i = 0; i < 6; i ++ ) {
  41555. const image = getImage( images[ i ] );
  41556. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  41557. }
  41558. } else if ( texture.isDataArrayTexture ) {
  41559. const image = options.image;
  41560. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41561. } else if ( texture.isData3DTexture ) {
  41562. const image = options.image;
  41563. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41564. } else if ( texture.isVideoTexture ) {
  41565. texture.update();
  41566. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  41567. } else {
  41568. const image = getImage( options.image );
  41569. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  41570. }
  41571. }
  41572. generateMipmaps( texture ) {
  41573. const { gl, backend } = this;
  41574. const { textureGPU, glTextureType } = backend.get( texture );
  41575. backend.state.bindTexture( glTextureType, textureGPU );
  41576. gl.generateMipmap( glTextureType );
  41577. }
  41578. deallocateRenderBuffers( renderTarget ) {
  41579. const { gl, backend } = this;
  41580. // remove framebuffer reference
  41581. if ( renderTarget ) {
  41582. const renderContextData = backend.get( renderTarget );
  41583. renderContextData.renderBufferStorageSetup = undefined;
  41584. if ( renderContextData.framebuffers ) {
  41585. for ( const cacheKey in renderContextData.framebuffers ) {
  41586. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  41587. }
  41588. delete renderContextData.framebuffers;
  41589. }
  41590. if ( renderContextData.depthRenderbuffer ) {
  41591. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  41592. delete renderContextData.depthRenderbuffer;
  41593. }
  41594. if ( renderContextData.stencilRenderbuffer ) {
  41595. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  41596. delete renderContextData.stencilRenderbuffer;
  41597. }
  41598. if ( renderContextData.msaaFrameBuffer ) {
  41599. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  41600. delete renderContextData.msaaFrameBuffer;
  41601. }
  41602. if ( renderContextData.msaaRenderbuffers ) {
  41603. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  41604. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  41605. }
  41606. delete renderContextData.msaaRenderbuffers;
  41607. }
  41608. }
  41609. }
  41610. destroyTexture( texture ) {
  41611. const { gl, backend } = this;
  41612. const { textureGPU, renderTarget } = backend.get( texture );
  41613. this.deallocateRenderBuffers( renderTarget );
  41614. gl.deleteTexture( textureGPU );
  41615. backend.delete( texture );
  41616. }
  41617. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  41618. const { gl, backend } = this;
  41619. const { state } = this.backend;
  41620. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  41621. let width, height, minX, minY;
  41622. let dstX, dstY;
  41623. if ( srcRegion !== null ) {
  41624. width = srcRegion.max.x - srcRegion.min.x;
  41625. height = srcRegion.max.y - srcRegion.min.y;
  41626. minX = srcRegion.min.x;
  41627. minY = srcRegion.min.y;
  41628. } else {
  41629. width = srcTexture.image.width;
  41630. height = srcTexture.image.height;
  41631. minX = 0;
  41632. minY = 0;
  41633. }
  41634. if ( dstPosition !== null ) {
  41635. dstX = dstPosition.x;
  41636. dstY = dstPosition.y;
  41637. } else {
  41638. dstX = 0;
  41639. dstY = 0;
  41640. }
  41641. state.bindTexture( glTextureType, dstTextureGPU );
  41642. // As another texture upload may have changed pixelStorei
  41643. // parameters, make sure they are correct for the dstTexture
  41644. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  41645. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  41646. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  41647. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  41648. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  41649. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  41650. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  41651. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  41652. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  41653. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  41654. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  41655. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  41656. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  41657. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  41658. if ( srcTexture.isDataTexture ) {
  41659. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  41660. } else {
  41661. if ( srcTexture.isCompressedTexture ) {
  41662. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  41663. } else {
  41664. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  41665. }
  41666. }
  41667. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  41668. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  41669. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  41670. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  41671. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  41672. // Generate mipmaps only when copying level 0
  41673. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  41674. state.unbindTexture();
  41675. }
  41676. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41677. const { gl } = this;
  41678. const { state } = this.backend;
  41679. const { textureGPU } = this.backend.get( texture );
  41680. const { x, y, z: width, w: height } = rectangle;
  41681. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  41682. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  41683. if ( requireDrawFrameBuffer ) {
  41684. const partial = ( x !== 0 || y !== 0 );
  41685. let mask;
  41686. let attachment;
  41687. if ( texture.isDepthTexture === true ) {
  41688. mask = gl.DEPTH_BUFFER_BIT;
  41689. attachment = gl.DEPTH_ATTACHMENT;
  41690. if ( renderContext.stencil ) {
  41691. mask |= gl.STENCIL_BUFFER_BIT;
  41692. }
  41693. } else {
  41694. mask = gl.COLOR_BUFFER_BIT;
  41695. attachment = gl.COLOR_ATTACHMENT0;
  41696. }
  41697. if ( partial ) {
  41698. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  41699. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41700. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41701. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41702. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41703. const flippedY = srcHeight - y - height;
  41704. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  41705. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41706. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41707. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  41708. state.unbindTexture();
  41709. } else {
  41710. const fb = gl.createFramebuffer();
  41711. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41712. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  41713. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  41714. gl.deleteFramebuffer( fb );
  41715. }
  41716. } else {
  41717. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41718. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  41719. state.unbindTexture();
  41720. }
  41721. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  41722. this.backend._setFramebuffer( renderContext );
  41723. }
  41724. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  41725. setupRenderBufferStorage( renderbuffer, renderContext ) {
  41726. const { gl } = this;
  41727. const renderTarget = renderContext.renderTarget;
  41728. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  41729. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  41730. if ( depthBuffer && ! stencilBuffer ) {
  41731. let glInternalFormat = gl.DEPTH_COMPONENT24;
  41732. if ( samples > 0 ) {
  41733. if ( depthTexture && depthTexture.isDepthTexture ) {
  41734. if ( depthTexture.type === gl.FLOAT ) {
  41735. glInternalFormat = gl.DEPTH_COMPONENT32F;
  41736. }
  41737. }
  41738. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  41739. } else {
  41740. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  41741. }
  41742. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41743. } else if ( depthBuffer && stencilBuffer ) {
  41744. if ( samples > 0 ) {
  41745. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  41746. } else {
  41747. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  41748. }
  41749. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41750. }
  41751. }
  41752. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41753. const { backend, gl } = this;
  41754. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  41755. const fb = gl.createFramebuffer();
  41756. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41757. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  41758. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  41759. const typedArrayType = this._getTypedArrayType( glType );
  41760. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  41761. const elementCount = width * height;
  41762. const byteLength = elementCount * bytesPerTexel;
  41763. const buffer = gl.createBuffer();
  41764. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41765. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  41766. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  41767. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41768. await backend.utils._clientWaitAsync();
  41769. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  41770. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41771. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  41772. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41773. gl.deleteFramebuffer( fb );
  41774. return dstBuffer;
  41775. }
  41776. _getTypedArrayType( glType ) {
  41777. const { gl } = this;
  41778. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  41779. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  41780. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  41781. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  41782. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  41783. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  41784. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  41785. if ( glType === gl.FLOAT ) return Float32Array;
  41786. throw new Error( `Unsupported WebGL type: ${glType}` );
  41787. }
  41788. _getBytesPerTexel( glType, glFormat ) {
  41789. const { gl } = this;
  41790. let bytesPerComponent = 0;
  41791. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  41792. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  41793. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  41794. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  41795. glType === gl.UNSIGNED_SHORT ||
  41796. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  41797. if ( glType === gl.UNSIGNED_INT ||
  41798. glType === gl.FLOAT ) bytesPerComponent = 4;
  41799. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  41800. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  41801. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  41802. }
  41803. }
  41804. class WebGLExtensions {
  41805. constructor( backend ) {
  41806. this.backend = backend;
  41807. this.gl = this.backend.gl;
  41808. this.availableExtensions = this.gl.getSupportedExtensions();
  41809. this.extensions = {};
  41810. }
  41811. get( name ) {
  41812. let extension = this.extensions[ name ];
  41813. if ( extension === undefined ) {
  41814. extension = this.gl.getExtension( name );
  41815. this.extensions[ name ] = extension;
  41816. }
  41817. return extension;
  41818. }
  41819. has( name ) {
  41820. return this.availableExtensions.includes( name );
  41821. }
  41822. }
  41823. class WebGLCapabilities {
  41824. constructor( backend ) {
  41825. this.backend = backend;
  41826. this.maxAnisotropy = null;
  41827. }
  41828. getMaxAnisotropy() {
  41829. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  41830. const gl = this.backend.gl;
  41831. const extensions = this.backend.extensions;
  41832. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41833. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41834. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  41835. } else {
  41836. this.maxAnisotropy = 0;
  41837. }
  41838. return this.maxAnisotropy;
  41839. }
  41840. }
  41841. const GLFeatureName = {
  41842. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  41843. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  41844. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  41845. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  41846. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41847. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41848. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  41849. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  41850. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  41851. };
  41852. class WebGLBufferRenderer {
  41853. constructor( backend ) {
  41854. this.gl = backend.gl;
  41855. this.extensions = backend.extensions;
  41856. this.info = backend.renderer.info;
  41857. this.mode = null;
  41858. this.index = 0;
  41859. this.type = null;
  41860. this.object = null;
  41861. }
  41862. render( start, count ) {
  41863. const { gl, mode, object, type, info, index } = this;
  41864. if ( index !== 0 ) {
  41865. gl.drawElements( mode, count, type, start );
  41866. } else {
  41867. gl.drawArrays( mode, start, count );
  41868. }
  41869. info.update( object, count, mode, 1 );
  41870. }
  41871. renderInstances( start, count, primcount ) {
  41872. const { gl, mode, type, index, object, info } = this;
  41873. if ( primcount === 0 ) return;
  41874. if ( index !== 0 ) {
  41875. gl.drawElementsInstanced( mode, count, type, start, primcount );
  41876. } else {
  41877. gl.drawArraysInstanced( mode, start, count, primcount );
  41878. }
  41879. info.update( object, count, mode, primcount );
  41880. }
  41881. renderMultiDraw( starts, counts, drawCount ) {
  41882. const { extensions, mode, object, info } = this;
  41883. if ( drawCount === 0 ) return;
  41884. const extension = extensions.get( 'WEBGL_multi_draw' );
  41885. if ( extension === null ) {
  41886. for ( let i = 0; i < drawCount; i ++ ) {
  41887. this.render( starts[ i ], counts[ i ] );
  41888. }
  41889. } else {
  41890. if ( this.index !== 0 ) {
  41891. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  41892. } else {
  41893. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  41894. }
  41895. let elementCount = 0;
  41896. for ( let i = 0; i < drawCount; i ++ ) {
  41897. elementCount += counts[ i ];
  41898. }
  41899. info.update( object, elementCount, mode, 1 );
  41900. }
  41901. }
  41902. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  41903. const { extensions, mode, object, info } = this;
  41904. if ( drawCount === 0 ) return;
  41905. const extension = extensions.get( 'WEBGL_multi_draw' );
  41906. if ( extension === null ) {
  41907. for ( let i = 0; i < drawCount; i ++ ) {
  41908. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  41909. }
  41910. } else {
  41911. if ( this.index !== 0 ) {
  41912. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  41913. } else {
  41914. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  41915. }
  41916. let elementCount = 0;
  41917. for ( let i = 0; i < drawCount; i ++ ) {
  41918. elementCount += counts[ i ];
  41919. }
  41920. for ( let i = 0; i < primcount.length; i ++ ) {
  41921. info.update( object, elementCount, mode, primcount[ i ] );
  41922. }
  41923. }
  41924. }
  41925. //
  41926. }
  41927. //
  41928. class WebGLBackend extends Backend {
  41929. constructor( parameters = {} ) {
  41930. super( parameters );
  41931. this.isWebGLBackend = true;
  41932. }
  41933. init( renderer ) {
  41934. super.init( renderer );
  41935. //
  41936. const parameters = this.parameters;
  41937. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  41938. this.gl = glContext;
  41939. this.extensions = new WebGLExtensions( this );
  41940. this.capabilities = new WebGLCapabilities( this );
  41941. this.attributeUtils = new WebGLAttributeUtils( this );
  41942. this.textureUtils = new WebGLTextureUtils( this );
  41943. this.bufferRenderer = new WebGLBufferRenderer( this );
  41944. this.state = new WebGLState( this );
  41945. this.utils = new WebGLUtils( this );
  41946. this.vaoCache = {};
  41947. this.transformFeedbackCache = {};
  41948. this.discard = false;
  41949. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41950. this.extensions.get( 'EXT_color_buffer_float' );
  41951. this.extensions.get( 'WEBGL_clip_cull_distance' );
  41952. this.extensions.get( 'OES_texture_float_linear' );
  41953. this.extensions.get( 'EXT_color_buffer_half_float' );
  41954. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41955. this.extensions.get( 'WEBGL_render_shared_exponent' );
  41956. this.extensions.get( 'WEBGL_multi_draw' );
  41957. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  41958. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  41959. this._currentContext = null;
  41960. }
  41961. get coordinateSystem() {
  41962. return WebGLCoordinateSystem;
  41963. }
  41964. async getArrayBufferAsync( attribute ) {
  41965. return await this.attributeUtils.getArrayBufferAsync( attribute );
  41966. }
  41967. initTimestampQuery( renderContext ) {
  41968. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41969. const renderContextData = this.get( renderContext );
  41970. if ( this.queryRunning ) {
  41971. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  41972. renderContextData.queryQueue.push( renderContext );
  41973. return;
  41974. }
  41975. if ( renderContextData.activeQuery ) {
  41976. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  41977. renderContextData.activeQuery = null;
  41978. }
  41979. renderContextData.activeQuery = this.gl.createQuery();
  41980. if ( renderContextData.activeQuery !== null ) {
  41981. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  41982. this.queryRunning = true;
  41983. }
  41984. }
  41985. // timestamp utils
  41986. prepareTimestampBuffer( renderContext ) {
  41987. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41988. const renderContextData = this.get( renderContext );
  41989. if ( renderContextData.activeQuery ) {
  41990. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  41991. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  41992. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  41993. renderContextData.activeQuery = null;
  41994. this.queryRunning = false;
  41995. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  41996. const nextRenderContext = renderContextData.queryQueue.shift();
  41997. this.initTimestampQuery( nextRenderContext );
  41998. }
  41999. }
  42000. }
  42001. async resolveTimestampAsync( renderContext, type = 'render' ) {
  42002. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  42003. const renderContextData = this.get( renderContext );
  42004. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  42005. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  42006. const queryInfo = renderContextData.gpuQueries[ i ];
  42007. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  42008. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  42009. if ( available && ! disjoint ) {
  42010. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  42011. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  42012. this.gl.deleteQuery( queryInfo.query );
  42013. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  42014. i --;
  42015. this.renderer.info.updateTimestamp( type, duration );
  42016. }
  42017. }
  42018. }
  42019. getContext() {
  42020. return this.gl;
  42021. }
  42022. beginRender( renderContext ) {
  42023. const { gl } = this;
  42024. const renderContextData = this.get( renderContext );
  42025. //
  42026. //
  42027. this.initTimestampQuery( renderContext );
  42028. renderContextData.previousContext = this._currentContext;
  42029. this._currentContext = renderContext;
  42030. this._setFramebuffer( renderContext );
  42031. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  42032. //
  42033. if ( renderContext.viewport ) {
  42034. this.updateViewport( renderContext );
  42035. } else {
  42036. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  42037. }
  42038. if ( renderContext.scissor ) {
  42039. const { x, y, width, height } = renderContext.scissorValue;
  42040. gl.scissor( x, renderContext.height - height - y, width, height );
  42041. }
  42042. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42043. if ( occlusionQueryCount > 0 ) {
  42044. // Get a reference to the array of objects with queries. The renderContextData property
  42045. // can be changed by another render pass before the async reading of all previous queries complete
  42046. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  42047. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42048. renderContextData.lastOcclusionObject = null;
  42049. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  42050. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42051. renderContextData.occlusionQueryIndex = 0;
  42052. }
  42053. }
  42054. finishRender( renderContext ) {
  42055. const { gl, state } = this;
  42056. const renderContextData = this.get( renderContext );
  42057. const previousContext = renderContextData.previousContext;
  42058. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42059. if ( occlusionQueryCount > 0 ) {
  42060. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42061. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42062. }
  42063. this.resolveOccludedAsync( renderContext );
  42064. }
  42065. const textures = renderContext.textures;
  42066. if ( textures !== null ) {
  42067. for ( let i = 0; i < textures.length; i ++ ) {
  42068. const texture = textures[ i ];
  42069. if ( texture.generateMipmaps ) {
  42070. this.generateMipmaps( texture );
  42071. }
  42072. }
  42073. }
  42074. this._currentContext = previousContext;
  42075. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  42076. const renderTargetContextData = this.get( renderContext.renderTarget );
  42077. const { samples } = renderContext.renderTarget;
  42078. if ( samples > 0 ) {
  42079. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42080. const mask = gl.COLOR_BUFFER_BIT;
  42081. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42082. const textures = renderContext.textures;
  42083. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42084. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42085. for ( let i = 0; i < textures.length; i ++ ) {
  42086. // TODO Add support for MRT
  42087. if ( renderContext.scissor ) {
  42088. const { x, y, width, height } = renderContext.scissorValue;
  42089. const viewY = renderContext.height - height - y;
  42090. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  42091. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  42092. } else {
  42093. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  42094. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  42095. }
  42096. }
  42097. }
  42098. }
  42099. if ( previousContext !== null ) {
  42100. this._setFramebuffer( previousContext );
  42101. if ( previousContext.viewport ) {
  42102. this.updateViewport( previousContext );
  42103. } else {
  42104. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  42105. }
  42106. }
  42107. this.prepareTimestampBuffer( renderContext );
  42108. }
  42109. resolveOccludedAsync( renderContext ) {
  42110. const renderContextData = this.get( renderContext );
  42111. // handle occlusion query results
  42112. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  42113. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  42114. const occluded = new WeakSet();
  42115. const { gl } = this;
  42116. renderContextData.currentOcclusionQueryObjects = null;
  42117. renderContextData.currentOcclusionQueries = null;
  42118. const check = () => {
  42119. let completed = 0;
  42120. // check all queries and requeue as appropriate
  42121. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  42122. const query = currentOcclusionQueries[ i ];
  42123. if ( query === null ) continue;
  42124. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  42125. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  42126. currentOcclusionQueries[ i ] = null;
  42127. gl.deleteQuery( query );
  42128. completed ++;
  42129. }
  42130. }
  42131. if ( completed < currentOcclusionQueries.length ) {
  42132. requestAnimationFrame( check );
  42133. } else {
  42134. renderContextData.occluded = occluded;
  42135. }
  42136. };
  42137. check();
  42138. }
  42139. }
  42140. isOccluded( renderContext, object ) {
  42141. const renderContextData = this.get( renderContext );
  42142. return renderContextData.occluded && renderContextData.occluded.has( object );
  42143. }
  42144. updateViewport( renderContext ) {
  42145. const gl = this.gl;
  42146. const { x, y, width, height } = renderContext.viewportValue;
  42147. gl.viewport( x, renderContext.height - height - y, width, height );
  42148. }
  42149. setScissorTest( boolean ) {
  42150. const gl = this.gl;
  42151. if ( boolean ) {
  42152. gl.enable( gl.SCISSOR_TEST );
  42153. } else {
  42154. gl.disable( gl.SCISSOR_TEST );
  42155. }
  42156. }
  42157. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  42158. const { gl } = this;
  42159. if ( descriptor === null ) {
  42160. descriptor = {
  42161. textures: null,
  42162. clearColorValue: this.getClearColor()
  42163. };
  42164. }
  42165. //
  42166. let clear = 0;
  42167. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  42168. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  42169. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  42170. if ( clear !== 0 ) {
  42171. const clearColor = descriptor.clearColorValue || this.getClearColor();
  42172. // premultiply alpha
  42173. clearColor.r *= clearColor.a;
  42174. clearColor.g *= clearColor.a;
  42175. clearColor.b *= clearColor.a;
  42176. if ( depth ) this.state.setDepthMask( true );
  42177. if ( descriptor.textures === null ) {
  42178. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  42179. gl.clear( clear );
  42180. } else {
  42181. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  42182. if ( color ) {
  42183. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  42184. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  42185. }
  42186. }
  42187. if ( depth && stencil ) {
  42188. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  42189. } else if ( depth ) {
  42190. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  42191. } else if ( stencil ) {
  42192. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  42193. }
  42194. }
  42195. }
  42196. }
  42197. beginCompute( computeGroup ) {
  42198. const { state, gl } = this;
  42199. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  42200. this.initTimestampQuery( computeGroup );
  42201. }
  42202. compute( computeGroup, computeNode, bindings, pipeline ) {
  42203. const { state, gl } = this;
  42204. if ( ! this.discard ) {
  42205. // required here to handle async behaviour of render.compute()
  42206. gl.enable( gl.RASTERIZER_DISCARD );
  42207. this.discard = true;
  42208. }
  42209. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  42210. const vaoKey = this._getVaoKey( null, attributes );
  42211. const vaoGPU = this.vaoCache[ vaoKey ];
  42212. if ( vaoGPU === undefined ) {
  42213. this._createVao( null, attributes );
  42214. } else {
  42215. gl.bindVertexArray( vaoGPU );
  42216. }
  42217. state.useProgram( programGPU );
  42218. this._bindUniforms( bindings );
  42219. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  42220. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42221. gl.beginTransformFeedback( gl.POINTS );
  42222. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  42223. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  42224. } else {
  42225. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  42226. }
  42227. gl.endTransformFeedback();
  42228. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42229. // switch active buffers
  42230. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42231. const dualAttributeData = transformBuffers[ i ];
  42232. if ( dualAttributeData.pbo ) {
  42233. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  42234. }
  42235. dualAttributeData.switchBuffers();
  42236. }
  42237. }
  42238. finishCompute( computeGroup ) {
  42239. const gl = this.gl;
  42240. this.discard = false;
  42241. gl.disable( gl.RASTERIZER_DISCARD );
  42242. this.prepareTimestampBuffer( computeGroup );
  42243. }
  42244. draw( renderObject/*, info*/ ) {
  42245. const { object, pipeline, material, context } = renderObject;
  42246. const { programGPU } = this.get( pipeline );
  42247. const { gl, state } = this;
  42248. const contextData = this.get( context );
  42249. const drawParms = renderObject.getDrawParameters();
  42250. if ( drawParms === null ) return;
  42251. //
  42252. this._bindUniforms( renderObject.getBindings() );
  42253. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  42254. state.setMaterial( material, frontFaceCW );
  42255. state.useProgram( programGPU );
  42256. //
  42257. let vaoGPU = renderObject.staticVao;
  42258. if ( vaoGPU === undefined ) {
  42259. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  42260. vaoGPU = this.vaoCache[ vaoKey ];
  42261. if ( vaoGPU === undefined ) {
  42262. let staticVao;
  42263. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  42264. if ( staticVao ) renderObject.staticVao = vaoGPU;
  42265. }
  42266. }
  42267. gl.bindVertexArray( vaoGPU );
  42268. //
  42269. const index = renderObject.getIndex();
  42270. //
  42271. const lastObject = contextData.lastOcclusionObject;
  42272. if ( lastObject !== object && lastObject !== undefined ) {
  42273. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42274. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42275. contextData.occlusionQueryIndex ++;
  42276. }
  42277. if ( object.occlusionTest === true ) {
  42278. const query = gl.createQuery();
  42279. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  42280. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  42281. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42282. }
  42283. contextData.lastOcclusionObject = object;
  42284. }
  42285. //
  42286. const renderer = this.bufferRenderer;
  42287. if ( object.isPoints ) renderer.mode = gl.POINTS;
  42288. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  42289. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  42290. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  42291. else {
  42292. if ( material.wireframe === true ) {
  42293. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  42294. renderer.mode = gl.LINES;
  42295. } else {
  42296. renderer.mode = gl.TRIANGLES;
  42297. }
  42298. }
  42299. //
  42300. const { vertexCount, instanceCount } = drawParms;
  42301. let { firstVertex } = drawParms;
  42302. renderer.object = object;
  42303. if ( index !== null ) {
  42304. firstVertex *= index.array.BYTES_PER_ELEMENT;
  42305. const indexData = this.get( index );
  42306. renderer.index = index.count;
  42307. renderer.type = indexData.type;
  42308. } else {
  42309. renderer.index = 0;
  42310. }
  42311. if ( object.isBatchedMesh ) {
  42312. if ( object._multiDrawInstances !== null ) {
  42313. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  42314. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  42315. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  42316. } else {
  42317. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  42318. }
  42319. } else if ( instanceCount > 1 ) {
  42320. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  42321. } else {
  42322. renderer.render( firstVertex, vertexCount );
  42323. }
  42324. //
  42325. gl.bindVertexArray( null );
  42326. }
  42327. needsRenderUpdate( /*renderObject*/ ) {
  42328. return false;
  42329. }
  42330. getRenderCacheKey( /*renderObject*/ ) {
  42331. return '';
  42332. }
  42333. // textures
  42334. createDefaultTexture( texture ) {
  42335. this.textureUtils.createDefaultTexture( texture );
  42336. }
  42337. createTexture( texture, options ) {
  42338. this.textureUtils.createTexture( texture, options );
  42339. }
  42340. updateTexture( texture, options ) {
  42341. this.textureUtils.updateTexture( texture, options );
  42342. }
  42343. generateMipmaps( texture ) {
  42344. this.textureUtils.generateMipmaps( texture );
  42345. }
  42346. destroyTexture( texture ) {
  42347. this.textureUtils.destroyTexture( texture );
  42348. }
  42349. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42350. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  42351. }
  42352. createSampler( /*texture*/ ) {
  42353. //console.warn( 'Abstract class.' );
  42354. }
  42355. destroySampler() {}
  42356. // node builder
  42357. createNodeBuilder( object, renderer ) {
  42358. return new GLSLNodeBuilder( object, renderer );
  42359. }
  42360. // program
  42361. createProgram( program ) {
  42362. const gl = this.gl;
  42363. const { stage, code } = program;
  42364. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  42365. gl.shaderSource( shader, code );
  42366. gl.compileShader( shader );
  42367. this.set( program, {
  42368. shaderGPU: shader
  42369. } );
  42370. }
  42371. destroyProgram( /*program*/ ) {
  42372. console.warn( 'Abstract class.' );
  42373. }
  42374. createRenderPipeline( renderObject, promises ) {
  42375. const gl = this.gl;
  42376. const pipeline = renderObject.pipeline;
  42377. // Program
  42378. const { fragmentProgram, vertexProgram } = pipeline;
  42379. const programGPU = gl.createProgram();
  42380. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42381. const vertexShader = this.get( vertexProgram ).shaderGPU;
  42382. gl.attachShader( programGPU, fragmentShader );
  42383. gl.attachShader( programGPU, vertexShader );
  42384. gl.linkProgram( programGPU );
  42385. this.set( pipeline, {
  42386. programGPU,
  42387. fragmentShader,
  42388. vertexShader
  42389. } );
  42390. if ( promises !== null && this.parallel ) {
  42391. const p = new Promise( ( resolve /*, reject*/ ) => {
  42392. const parallel = this.parallel;
  42393. const checkStatus = () => {
  42394. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  42395. this._completeCompile( renderObject, pipeline );
  42396. resolve();
  42397. } else {
  42398. requestAnimationFrame( checkStatus );
  42399. }
  42400. };
  42401. checkStatus();
  42402. } );
  42403. promises.push( p );
  42404. return;
  42405. }
  42406. this._completeCompile( renderObject, pipeline );
  42407. }
  42408. _handleSource( string, errorLine ) {
  42409. const lines = string.split( '\n' );
  42410. const lines2 = [];
  42411. const from = Math.max( errorLine - 6, 0 );
  42412. const to = Math.min( errorLine + 6, lines.length );
  42413. for ( let i = from; i < to; i ++ ) {
  42414. const line = i + 1;
  42415. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  42416. }
  42417. return lines2.join( '\n' );
  42418. }
  42419. _getShaderErrors( gl, shader, type ) {
  42420. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  42421. const errors = gl.getShaderInfoLog( shader ).trim();
  42422. if ( status && errors === '' ) return '';
  42423. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  42424. if ( errorMatches ) {
  42425. const errorLine = parseInt( errorMatches[ 1 ] );
  42426. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  42427. } else {
  42428. return errors;
  42429. }
  42430. }
  42431. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  42432. if ( this.renderer.debug.checkShaderErrors ) {
  42433. const gl = this.gl;
  42434. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  42435. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42436. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  42437. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  42438. } else {
  42439. // default error reporting
  42440. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  42441. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  42442. console.error(
  42443. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  42444. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  42445. 'Program Info Log: ' + programLog + '\n' +
  42446. vertexErrors + '\n' +
  42447. fragmentErrors
  42448. );
  42449. }
  42450. } else if ( programLog !== '' ) {
  42451. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  42452. }
  42453. }
  42454. }
  42455. _completeCompile( renderObject, pipeline ) {
  42456. const { state, gl } = this;
  42457. const pipelineData = this.get( pipeline );
  42458. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  42459. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42460. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42461. }
  42462. state.useProgram( programGPU );
  42463. // Bindings
  42464. const bindings = renderObject.getBindings();
  42465. this._setupBindings( bindings, programGPU );
  42466. //
  42467. this.set( pipeline, {
  42468. programGPU
  42469. } );
  42470. }
  42471. createComputePipeline( computePipeline, bindings ) {
  42472. const { state, gl } = this;
  42473. // Program
  42474. const fragmentProgram = {
  42475. stage: 'fragment',
  42476. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  42477. };
  42478. this.createProgram( fragmentProgram );
  42479. const { computeProgram } = computePipeline;
  42480. const programGPU = gl.createProgram();
  42481. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42482. const vertexShader = this.get( computeProgram ).shaderGPU;
  42483. const transforms = computeProgram.transforms;
  42484. const transformVaryingNames = [];
  42485. const transformAttributeNodes = [];
  42486. for ( let i = 0; i < transforms.length; i ++ ) {
  42487. const transform = transforms[ i ];
  42488. transformVaryingNames.push( transform.varyingName );
  42489. transformAttributeNodes.push( transform.attributeNode );
  42490. }
  42491. gl.attachShader( programGPU, fragmentShader );
  42492. gl.attachShader( programGPU, vertexShader );
  42493. gl.transformFeedbackVaryings(
  42494. programGPU,
  42495. transformVaryingNames,
  42496. gl.SEPARATE_ATTRIBS
  42497. );
  42498. gl.linkProgram( programGPU );
  42499. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42500. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42501. }
  42502. state.useProgram( programGPU );
  42503. // Bindings
  42504. this.createBindings( null, bindings );
  42505. this._setupBindings( bindings, programGPU );
  42506. const attributeNodes = computeProgram.attributes;
  42507. const attributes = [];
  42508. const transformBuffers = [];
  42509. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  42510. const attribute = attributeNodes[ i ].node.attribute;
  42511. attributes.push( attribute );
  42512. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42513. }
  42514. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  42515. const attribute = transformAttributeNodes[ i ].attribute;
  42516. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42517. const attributeData = this.get( attribute );
  42518. transformBuffers.push( attributeData );
  42519. }
  42520. //
  42521. this.set( computePipeline, {
  42522. programGPU,
  42523. transformBuffers,
  42524. attributes
  42525. } );
  42526. }
  42527. createBindings( bindGroup, bindings ) {
  42528. this.updateBindings( bindGroup, bindings );
  42529. }
  42530. updateBindings( bindGroup, bindings ) {
  42531. if ( ! bindGroup ) return;
  42532. const { gl } = this;
  42533. const bindingsData = this.get( bindings );
  42534. const bindGroupData = this.get( bindGroup );
  42535. if ( bindingsData.textureIndex === undefined ) bindingsData.textureIndex = 0;
  42536. if ( bindGroupData.textureIndex === undefined ) {
  42537. bindGroupData.textureIndex = bindingsData.textureIndex;
  42538. } else {
  42539. // reset textureIndex to match previous mappimgs when rebuilt
  42540. bindingsData.textureIndex = bindGroupData.textureIndex;
  42541. }
  42542. let i = 0;
  42543. for ( const binding of bindGroup.bindings ) {
  42544. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42545. const data = binding.buffer;
  42546. const bufferGPU = gl.createBuffer();
  42547. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42548. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42549. this.set( binding, {
  42550. index: bindGroup.index * 2 + i ++,
  42551. bufferGPU
  42552. } );
  42553. } else if ( binding.isSampledTexture ) {
  42554. const { textureGPU, glTextureType } = this.get( binding.texture );
  42555. this.set( binding, {
  42556. index: bindingsData.textureIndex ++,
  42557. textureGPU,
  42558. glTextureType
  42559. } );
  42560. }
  42561. }
  42562. }
  42563. updateBinding( binding ) {
  42564. const gl = this.gl;
  42565. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42566. const bindingData = this.get( binding );
  42567. const bufferGPU = bindingData.bufferGPU;
  42568. const data = binding.buffer;
  42569. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42570. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42571. }
  42572. }
  42573. // attributes
  42574. createIndexAttribute( attribute ) {
  42575. const gl = this.gl;
  42576. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  42577. }
  42578. createAttribute( attribute ) {
  42579. if ( this.has( attribute ) ) return;
  42580. const gl = this.gl;
  42581. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42582. }
  42583. createStorageAttribute( attribute ) {
  42584. if ( this.has( attribute ) ) return;
  42585. const gl = this.gl;
  42586. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42587. }
  42588. updateAttribute( attribute ) {
  42589. this.attributeUtils.updateAttribute( attribute );
  42590. }
  42591. destroyAttribute( attribute ) {
  42592. this.attributeUtils.destroyAttribute( attribute );
  42593. }
  42594. updateSize() {
  42595. //console.warn( 'Abstract class.' );
  42596. }
  42597. hasFeature( name ) {
  42598. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  42599. const extensions = this.extensions;
  42600. for ( let i = 0; i < keysMatching.length; i ++ ) {
  42601. if ( extensions.has( keysMatching[ i ] ) ) return true;
  42602. }
  42603. return false;
  42604. }
  42605. getMaxAnisotropy() {
  42606. return this.capabilities.getMaxAnisotropy();
  42607. }
  42608. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  42609. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  42610. }
  42611. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42612. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  42613. }
  42614. _setFramebuffer( descriptor ) {
  42615. const { gl, state } = this;
  42616. let currentFrameBuffer = null;
  42617. if ( descriptor.textures !== null ) {
  42618. const renderTarget = descriptor.renderTarget;
  42619. const renderTargetContextData = this.get( renderTarget );
  42620. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  42621. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  42622. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  42623. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  42624. const cacheKey = getCacheKey( descriptor );
  42625. let fb;
  42626. if ( isCube ) {
  42627. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  42628. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  42629. } else {
  42630. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  42631. fb = renderTargetContextData.framebuffers[ cacheKey ];
  42632. }
  42633. if ( fb === undefined ) {
  42634. fb = gl.createFramebuffer();
  42635. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42636. const textures = descriptor.textures;
  42637. if ( isCube ) {
  42638. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  42639. const { textureGPU } = this.get( textures[ 0 ] );
  42640. const cubeFace = this.renderer._activeCubeFace;
  42641. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  42642. } else {
  42643. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  42644. for ( let i = 0; i < textures.length; i ++ ) {
  42645. const texture = textures[ i ];
  42646. const textureData = this.get( texture );
  42647. textureData.renderTarget = descriptor.renderTarget;
  42648. const attachment = gl.COLOR_ATTACHMENT0 + i;
  42649. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42650. }
  42651. state.drawBuffers( descriptor, fb );
  42652. }
  42653. if ( descriptor.depthTexture !== null ) {
  42654. const textureData = this.get( descriptor.depthTexture );
  42655. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42656. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42657. }
  42658. }
  42659. if ( samples > 0 ) {
  42660. if ( msaaFb === undefined ) {
  42661. const invalidationArray = [];
  42662. msaaFb = gl.createFramebuffer();
  42663. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  42664. const msaaRenderbuffers = [];
  42665. const textures = descriptor.textures;
  42666. for ( let i = 0; i < textures.length; i ++ ) {
  42667. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  42668. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42669. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  42670. if ( depthBuffer ) {
  42671. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42672. invalidationArray.push( depthStyle );
  42673. }
  42674. const texture = descriptor.textures[ i ];
  42675. const textureData = this.get( texture );
  42676. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  42677. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42678. }
  42679. renderTargetContextData.msaaFrameBuffer = msaaFb;
  42680. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  42681. if ( depthRenderbuffer === undefined ) {
  42682. depthRenderbuffer = gl.createRenderbuffer();
  42683. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  42684. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  42685. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42686. invalidationArray.push( depthStyle );
  42687. }
  42688. renderTargetContextData.invalidationArray = invalidationArray;
  42689. }
  42690. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42691. } else {
  42692. currentFrameBuffer = fb;
  42693. }
  42694. }
  42695. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  42696. }
  42697. _getVaoKey( index, attributes ) {
  42698. let key = [];
  42699. if ( index !== null ) {
  42700. const indexData = this.get( index );
  42701. key += ':' + indexData.id;
  42702. }
  42703. for ( let i = 0; i < attributes.length; i ++ ) {
  42704. const attributeData = this.get( attributes[ i ] );
  42705. key += ':' + attributeData.id;
  42706. }
  42707. return key;
  42708. }
  42709. _createVao( index, attributes ) {
  42710. const { gl } = this;
  42711. const vaoGPU = gl.createVertexArray();
  42712. let key = '';
  42713. let staticVao = true;
  42714. gl.bindVertexArray( vaoGPU );
  42715. if ( index !== null ) {
  42716. const indexData = this.get( index );
  42717. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  42718. key += ':' + indexData.id;
  42719. }
  42720. for ( let i = 0; i < attributes.length; i ++ ) {
  42721. const attribute = attributes[ i ];
  42722. const attributeData = this.get( attribute );
  42723. key += ':' + attributeData.id;
  42724. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  42725. gl.enableVertexAttribArray( i );
  42726. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  42727. let stride, offset;
  42728. if ( attribute.isInterleavedBufferAttribute === true ) {
  42729. stride = attribute.data.stride * attributeData.bytesPerElement;
  42730. offset = attribute.offset * attributeData.bytesPerElement;
  42731. } else {
  42732. stride = 0;
  42733. offset = 0;
  42734. }
  42735. if ( attributeData.isInteger ) {
  42736. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  42737. } else {
  42738. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  42739. }
  42740. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  42741. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  42742. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  42743. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  42744. }
  42745. }
  42746. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  42747. this.vaoCache[ key ] = vaoGPU;
  42748. return { vaoGPU, staticVao };
  42749. }
  42750. _getTransformFeedback( transformBuffers ) {
  42751. let key = '';
  42752. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42753. key += ':' + transformBuffers[ i ].id;
  42754. }
  42755. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  42756. if ( transformFeedbackGPU !== undefined ) {
  42757. return transformFeedbackGPU;
  42758. }
  42759. const { gl } = this;
  42760. transformFeedbackGPU = gl.createTransformFeedback();
  42761. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42762. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42763. const attributeData = transformBuffers[ i ];
  42764. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  42765. }
  42766. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42767. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  42768. return transformFeedbackGPU;
  42769. }
  42770. _setupBindings( bindings, programGPU ) {
  42771. const gl = this.gl;
  42772. for ( const bindGroup of bindings ) {
  42773. for ( const binding of bindGroup.bindings ) {
  42774. const bindingData = this.get( binding );
  42775. const index = bindingData.index;
  42776. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42777. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  42778. gl.uniformBlockBinding( programGPU, location, index );
  42779. } else if ( binding.isSampledTexture ) {
  42780. const location = gl.getUniformLocation( programGPU, binding.name );
  42781. gl.uniform1i( location, index );
  42782. }
  42783. }
  42784. }
  42785. }
  42786. _bindUniforms( bindings ) {
  42787. const { gl, state } = this;
  42788. for ( const bindGroup of bindings ) {
  42789. for ( const binding of bindGroup.bindings ) {
  42790. const bindingData = this.get( binding );
  42791. const index = bindingData.index;
  42792. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42793. // TODO USE bindBufferRange to group multiple uniform buffers
  42794. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  42795. } else if ( binding.isSampledTexture ) {
  42796. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  42797. }
  42798. }
  42799. }
  42800. }
  42801. }
  42802. class Sampler extends Binding {
  42803. constructor( name, texture ) {
  42804. super( name );
  42805. this.texture = texture;
  42806. this.version = texture ? texture.version : 0;
  42807. this.isSampler = true;
  42808. }
  42809. }
  42810. class NodeSampler extends Sampler {
  42811. constructor( name, textureNode, groupNode ) {
  42812. super( name, textureNode ? textureNode.value : null );
  42813. this.textureNode = textureNode;
  42814. this.groupNode = groupNode;
  42815. }
  42816. update() {
  42817. this.texture = this.textureNode.value;
  42818. }
  42819. }
  42820. class StorageBuffer extends Buffer {
  42821. constructor( name, attribute ) {
  42822. super( name, attribute ? attribute.array : null );
  42823. this.attribute = attribute;
  42824. this.isStorageBuffer = true;
  42825. }
  42826. }
  42827. let _id = 0;
  42828. class NodeStorageBuffer extends StorageBuffer {
  42829. constructor( nodeUniform, groupNode ) {
  42830. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  42831. this.nodeUniform = nodeUniform;
  42832. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  42833. this.groupNode = groupNode;
  42834. }
  42835. get buffer() {
  42836. return this.nodeUniform.value;
  42837. }
  42838. }
  42839. class WebGPUTexturePassUtils extends DataMap {
  42840. constructor( device ) {
  42841. super();
  42842. this.device = device;
  42843. const mipmapVertexSource = `
  42844. struct VarysStruct {
  42845. @builtin( position ) Position: vec4<f32>,
  42846. @location( 0 ) vTex : vec2<f32>
  42847. };
  42848. @vertex
  42849. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  42850. var Varys : VarysStruct;
  42851. var pos = array< vec2<f32>, 4 >(
  42852. vec2<f32>( -1.0, 1.0 ),
  42853. vec2<f32>( 1.0, 1.0 ),
  42854. vec2<f32>( -1.0, -1.0 ),
  42855. vec2<f32>( 1.0, -1.0 )
  42856. );
  42857. var tex = array< vec2<f32>, 4 >(
  42858. vec2<f32>( 0.0, 0.0 ),
  42859. vec2<f32>( 1.0, 0.0 ),
  42860. vec2<f32>( 0.0, 1.0 ),
  42861. vec2<f32>( 1.0, 1.0 )
  42862. );
  42863. Varys.vTex = tex[ vertexIndex ];
  42864. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  42865. return Varys;
  42866. }
  42867. `;
  42868. const mipmapFragmentSource = `
  42869. @group( 0 ) @binding( 0 )
  42870. var imgSampler : sampler;
  42871. @group( 0 ) @binding( 1 )
  42872. var img : texture_2d<f32>;
  42873. @fragment
  42874. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42875. return textureSample( img, imgSampler, vTex );
  42876. }
  42877. `;
  42878. const flipYFragmentSource = `
  42879. @group( 0 ) @binding( 0 )
  42880. var imgSampler : sampler;
  42881. @group( 0 ) @binding( 1 )
  42882. var img : texture_2d<f32>;
  42883. @fragment
  42884. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42885. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  42886. }
  42887. `;
  42888. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  42889. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42890. // We'll need a new pipeline for every texture format used.
  42891. this.transferPipelines = {};
  42892. this.flipYPipelines = {};
  42893. this.mipmapVertexShaderModule = device.createShaderModule( {
  42894. label: 'mipmapVertex',
  42895. code: mipmapVertexSource
  42896. } );
  42897. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42898. label: 'mipmapFragment',
  42899. code: mipmapFragmentSource
  42900. } );
  42901. this.flipYFragmentShaderModule = device.createShaderModule( {
  42902. label: 'flipYFragment',
  42903. code: flipYFragmentSource
  42904. } );
  42905. }
  42906. getTransferPipeline( format ) {
  42907. let pipeline = this.transferPipelines[ format ];
  42908. if ( pipeline === undefined ) {
  42909. pipeline = this.device.createRenderPipeline( {
  42910. label: `mipmap-${ format }`,
  42911. vertex: {
  42912. module: this.mipmapVertexShaderModule,
  42913. entryPoint: 'main'
  42914. },
  42915. fragment: {
  42916. module: this.mipmapFragmentShaderModule,
  42917. entryPoint: 'main',
  42918. targets: [ { format } ]
  42919. },
  42920. primitive: {
  42921. topology: GPUPrimitiveTopology.TriangleStrip,
  42922. stripIndexFormat: GPUIndexFormat.Uint32
  42923. },
  42924. layout: 'auto'
  42925. } );
  42926. this.transferPipelines[ format ] = pipeline;
  42927. }
  42928. return pipeline;
  42929. }
  42930. getFlipYPipeline( format ) {
  42931. let pipeline = this.flipYPipelines[ format ];
  42932. if ( pipeline === undefined ) {
  42933. pipeline = this.device.createRenderPipeline( {
  42934. label: `flipY-${ format }`,
  42935. vertex: {
  42936. module: this.mipmapVertexShaderModule,
  42937. entryPoint: 'main'
  42938. },
  42939. fragment: {
  42940. module: this.flipYFragmentShaderModule,
  42941. entryPoint: 'main',
  42942. targets: [ { format } ]
  42943. },
  42944. primitive: {
  42945. topology: GPUPrimitiveTopology.TriangleStrip,
  42946. stripIndexFormat: GPUIndexFormat.Uint32
  42947. },
  42948. layout: 'auto'
  42949. } );
  42950. this.flipYPipelines[ format ] = pipeline;
  42951. }
  42952. return pipeline;
  42953. }
  42954. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42955. const format = textureGPUDescriptor.format;
  42956. const { width, height } = textureGPUDescriptor.size;
  42957. const transferPipeline = this.getTransferPipeline( format );
  42958. const flipYPipeline = this.getFlipYPipeline( format );
  42959. const tempTexture = this.device.createTexture( {
  42960. size: { width, height, depthOrArrayLayers: 1 },
  42961. format,
  42962. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42963. } );
  42964. const srcView = textureGPU.createView( {
  42965. baseMipLevel: 0,
  42966. mipLevelCount: 1,
  42967. dimension: GPUTextureViewDimension.TwoD,
  42968. baseArrayLayer
  42969. } );
  42970. const dstView = tempTexture.createView( {
  42971. baseMipLevel: 0,
  42972. mipLevelCount: 1,
  42973. dimension: GPUTextureViewDimension.TwoD,
  42974. baseArrayLayer: 0
  42975. } );
  42976. const commandEncoder = this.device.createCommandEncoder( {} );
  42977. const pass = ( pipeline, sourceView, destinationView ) => {
  42978. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42979. const bindGroup = this.device.createBindGroup( {
  42980. layout: bindGroupLayout,
  42981. entries: [ {
  42982. binding: 0,
  42983. resource: this.flipYSampler
  42984. }, {
  42985. binding: 1,
  42986. resource: sourceView
  42987. } ]
  42988. } );
  42989. const passEncoder = commandEncoder.beginRenderPass( {
  42990. colorAttachments: [ {
  42991. view: destinationView,
  42992. loadOp: GPULoadOp.Clear,
  42993. storeOp: GPUStoreOp.Store,
  42994. clearValue: [ 0, 0, 0, 0 ]
  42995. } ]
  42996. } );
  42997. passEncoder.setPipeline( pipeline );
  42998. passEncoder.setBindGroup( 0, bindGroup );
  42999. passEncoder.draw( 4, 1, 0, 0 );
  43000. passEncoder.end();
  43001. };
  43002. pass( transferPipeline, srcView, dstView );
  43003. pass( flipYPipeline, dstView, srcView );
  43004. this.device.queue.submit( [ commandEncoder.finish() ] );
  43005. tempTexture.destroy();
  43006. }
  43007. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  43008. const textureData = this.get( textureGPU );
  43009. if ( textureData.useCount === undefined ) {
  43010. textureData.useCount = 0;
  43011. textureData.layers = [];
  43012. }
  43013. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  43014. const commandEncoder = this.device.createCommandEncoder( {} );
  43015. this._mipmapRunBundles( commandEncoder, passes );
  43016. this.device.queue.submit( [ commandEncoder.finish() ] );
  43017. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  43018. textureData.useCount ++;
  43019. }
  43020. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  43021. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  43022. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  43023. let srcView = textureGPU.createView( {
  43024. baseMipLevel: 0,
  43025. mipLevelCount: 1,
  43026. dimension: GPUTextureViewDimension.TwoD,
  43027. baseArrayLayer
  43028. } );
  43029. const passes = [];
  43030. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  43031. const bindGroup = this.device.createBindGroup( {
  43032. layout: bindGroupLayout,
  43033. entries: [ {
  43034. binding: 0,
  43035. resource: this.mipmapSampler
  43036. }, {
  43037. binding: 1,
  43038. resource: srcView
  43039. } ]
  43040. } );
  43041. const dstView = textureGPU.createView( {
  43042. baseMipLevel: i,
  43043. mipLevelCount: 1,
  43044. dimension: GPUTextureViewDimension.TwoD,
  43045. baseArrayLayer
  43046. } );
  43047. const passDescriptor = {
  43048. colorAttachments: [ {
  43049. view: dstView,
  43050. loadOp: GPULoadOp.Clear,
  43051. storeOp: GPUStoreOp.Store,
  43052. clearValue: [ 0, 0, 0, 0 ]
  43053. } ]
  43054. };
  43055. const passEncoder = this.device.createRenderBundleEncoder( {
  43056. colorFormats: [ textureGPUDescriptor.format ]
  43057. } );
  43058. passEncoder.setPipeline( pipeline );
  43059. passEncoder.setBindGroup( 0, bindGroup );
  43060. passEncoder.draw( 4, 1, 0, 0 );
  43061. passes.push( {
  43062. renderBundles: [ passEncoder.finish() ],
  43063. passDescriptor
  43064. } );
  43065. srcView = dstView;
  43066. }
  43067. return passes;
  43068. }
  43069. _mipmapRunBundles( commandEncoder, passes ) {
  43070. const levels = passes.length;
  43071. for ( let i = 0; i < levels; i ++ ) {
  43072. const pass = passes[ i ];
  43073. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  43074. passEncoder.executeBundles( pass.renderBundles );
  43075. passEncoder.end();
  43076. }
  43077. }
  43078. }
  43079. const _compareToWebGPU = {
  43080. [ NeverCompare ]: 'never',
  43081. [ LessCompare ]: 'less',
  43082. [ EqualCompare ]: 'equal',
  43083. [ LessEqualCompare ]: 'less-equal',
  43084. [ GreaterCompare ]: 'greater',
  43085. [ GreaterEqualCompare ]: 'greater-equal',
  43086. [ AlwaysCompare ]: 'always',
  43087. [ NotEqualCompare ]: 'not-equal'
  43088. };
  43089. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  43090. class WebGPUTextureUtils {
  43091. constructor( backend ) {
  43092. this.backend = backend;
  43093. this._passUtils = null;
  43094. this.defaultTexture = {};
  43095. this.defaultCubeTexture = {};
  43096. this.defaultVideoFrame = null;
  43097. this.colorBuffer = null;
  43098. this.depthTexture = new DepthTexture();
  43099. this.depthTexture.name = 'depthBuffer';
  43100. }
  43101. createSampler( texture ) {
  43102. const backend = this.backend;
  43103. const device = backend.device;
  43104. const textureGPU = backend.get( texture );
  43105. const samplerDescriptorGPU = {
  43106. addressModeU: this._convertAddressMode( texture.wrapS ),
  43107. addressModeV: this._convertAddressMode( texture.wrapT ),
  43108. addressModeW: this._convertAddressMode( texture.wrapR ),
  43109. magFilter: this._convertFilterMode( texture.magFilter ),
  43110. minFilter: this._convertFilterMode( texture.minFilter ),
  43111. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  43112. maxAnisotropy: texture.anisotropy
  43113. };
  43114. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  43115. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  43116. }
  43117. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  43118. }
  43119. createDefaultTexture( texture ) {
  43120. let textureGPU;
  43121. const format = getFormat( texture );
  43122. if ( texture.isCubeTexture ) {
  43123. textureGPU = this._getDefaultCubeTextureGPU( format );
  43124. } else if ( texture.isVideoTexture ) {
  43125. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  43126. } else {
  43127. textureGPU = this._getDefaultTextureGPU( format );
  43128. }
  43129. this.backend.get( texture ).texture = textureGPU;
  43130. }
  43131. createTexture( texture, options = {} ) {
  43132. const backend = this.backend;
  43133. const textureData = backend.get( texture );
  43134. if ( textureData.initialized ) {
  43135. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  43136. }
  43137. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  43138. if ( options.levels === undefined ) options.levels = 1;
  43139. if ( options.depth === undefined ) options.depth = 1;
  43140. const { width, height, depth, levels } = options;
  43141. const dimension = this._getDimension( texture );
  43142. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  43143. textureData.format = format;
  43144. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  43145. sampleCount = backend.utils.getSampleCount( sampleCount );
  43146. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  43147. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  43148. if ( texture.isStorageTexture === true ) {
  43149. usage |= GPUTextureUsage.STORAGE_BINDING;
  43150. }
  43151. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  43152. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  43153. }
  43154. const textureDescriptorGPU = {
  43155. label: texture.name,
  43156. size: {
  43157. width: width,
  43158. height: height,
  43159. depthOrArrayLayers: depth,
  43160. },
  43161. mipLevelCount: levels,
  43162. sampleCount: primarySampleCount,
  43163. dimension: dimension,
  43164. format: format,
  43165. usage: usage
  43166. };
  43167. // texture creation
  43168. if ( texture.isVideoTexture ) {
  43169. const video = texture.source.data;
  43170. const videoFrame = new VideoFrame( video );
  43171. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  43172. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  43173. videoFrame.close();
  43174. textureData.externalTexture = video;
  43175. } else {
  43176. if ( format === undefined ) {
  43177. console.warn( 'WebGPURenderer: Texture format not supported.' );
  43178. return this.createDefaultTexture( texture );
  43179. }
  43180. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  43181. }
  43182. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  43183. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  43184. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  43185. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  43186. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  43187. }
  43188. textureData.initialized = true;
  43189. textureData.textureDescriptorGPU = textureDescriptorGPU;
  43190. }
  43191. destroyTexture( texture ) {
  43192. const backend = this.backend;
  43193. const textureData = backend.get( texture );
  43194. textureData.texture.destroy();
  43195. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  43196. backend.delete( texture );
  43197. }
  43198. destroySampler( texture ) {
  43199. const backend = this.backend;
  43200. const textureData = backend.get( texture );
  43201. delete textureData.sampler;
  43202. }
  43203. generateMipmaps( texture ) {
  43204. const textureData = this.backend.get( texture );
  43205. if ( texture.isCubeTexture ) {
  43206. for ( let i = 0; i < 6; i ++ ) {
  43207. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43208. }
  43209. } else {
  43210. const depth = texture.image.depth || 1;
  43211. for ( let i = 0; i < depth; i ++ ) {
  43212. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43213. }
  43214. }
  43215. }
  43216. getColorBuffer() {
  43217. if ( this.colorBuffer ) this.colorBuffer.destroy();
  43218. const backend = this.backend;
  43219. const { width, height } = backend.getDrawingBufferSize();
  43220. this.colorBuffer = backend.device.createTexture( {
  43221. label: 'colorBuffer',
  43222. size: {
  43223. width: width,
  43224. height: height,
  43225. depthOrArrayLayers: 1
  43226. },
  43227. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  43228. format: backend.utils.getPreferredCanvasFormat(),
  43229. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  43230. } );
  43231. return this.colorBuffer;
  43232. }
  43233. getDepthBuffer( depth = true, stencil = false ) {
  43234. const backend = this.backend;
  43235. const { width, height } = backend.getDrawingBufferSize();
  43236. const depthTexture = this.depthTexture;
  43237. const depthTextureGPU = backend.get( depthTexture ).texture;
  43238. let format, type;
  43239. if ( stencil ) {
  43240. format = DepthStencilFormat;
  43241. type = UnsignedInt248Type;
  43242. } else if ( depth ) {
  43243. format = DepthFormat;
  43244. type = UnsignedIntType;
  43245. }
  43246. if ( depthTextureGPU !== undefined ) {
  43247. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  43248. return depthTextureGPU;
  43249. }
  43250. this.destroyTexture( depthTexture );
  43251. }
  43252. depthTexture.name = 'depthBuffer';
  43253. depthTexture.format = format;
  43254. depthTexture.type = type;
  43255. depthTexture.image.width = width;
  43256. depthTexture.image.height = height;
  43257. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  43258. return backend.get( depthTexture ).texture;
  43259. }
  43260. updateTexture( texture, options ) {
  43261. const textureData = this.backend.get( texture );
  43262. const { textureDescriptorGPU } = textureData;
  43263. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  43264. return;
  43265. // transfer texture data
  43266. if ( texture.isDataTexture ) {
  43267. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43268. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43269. for ( let i = 0; i < options.image.depth; i ++ ) {
  43270. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  43271. }
  43272. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  43273. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  43274. } else if ( texture.isCubeTexture ) {
  43275. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  43276. } else if ( texture.isVideoTexture ) {
  43277. const video = texture.source.data;
  43278. textureData.externalTexture = video;
  43279. } else {
  43280. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43281. }
  43282. //
  43283. textureData.version = texture.version;
  43284. if ( texture.onUpdate ) texture.onUpdate( texture );
  43285. }
  43286. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43287. const device = this.backend.device;
  43288. const textureData = this.backend.get( texture );
  43289. const textureGPU = textureData.texture;
  43290. const format = textureData.textureDescriptorGPU.format;
  43291. const bytesPerTexel = this._getBytesPerTexel( format );
  43292. let bytesPerRow = width * bytesPerTexel;
  43293. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  43294. const readBuffer = device.createBuffer(
  43295. {
  43296. size: width * height * bytesPerTexel,
  43297. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43298. }
  43299. );
  43300. const encoder = device.createCommandEncoder();
  43301. encoder.copyTextureToBuffer(
  43302. {
  43303. texture: textureGPU,
  43304. origin: { x, y, z: faceIndex },
  43305. },
  43306. {
  43307. buffer: readBuffer,
  43308. bytesPerRow: bytesPerRow
  43309. },
  43310. {
  43311. width: width,
  43312. height: height
  43313. }
  43314. );
  43315. const typedArrayType = this._getTypedArrayType( format );
  43316. device.queue.submit( [ encoder.finish() ] );
  43317. await readBuffer.mapAsync( GPUMapMode.READ );
  43318. const buffer = readBuffer.getMappedRange();
  43319. return new typedArrayType( buffer );
  43320. }
  43321. _isEnvironmentTexture( texture ) {
  43322. const mapping = texture.mapping;
  43323. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  43324. }
  43325. _getDefaultTextureGPU( format ) {
  43326. let defaultTexture = this.defaultTexture[ format ];
  43327. if ( defaultTexture === undefined ) {
  43328. const texture = new Texture();
  43329. texture.minFilter = NearestFilter;
  43330. texture.magFilter = NearestFilter;
  43331. this.createTexture( texture, { width: 1, height: 1, format } );
  43332. this.defaultTexture[ format ] = defaultTexture = texture;
  43333. }
  43334. return this.backend.get( defaultTexture ).texture;
  43335. }
  43336. _getDefaultCubeTextureGPU( format ) {
  43337. let defaultCubeTexture = this.defaultTexture[ format ];
  43338. if ( defaultCubeTexture === undefined ) {
  43339. const texture = new CubeTexture();
  43340. texture.minFilter = NearestFilter;
  43341. texture.magFilter = NearestFilter;
  43342. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  43343. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  43344. }
  43345. return this.backend.get( defaultCubeTexture ).texture;
  43346. }
  43347. _getDefaultVideoFrame() {
  43348. let defaultVideoFrame = this.defaultVideoFrame;
  43349. if ( defaultVideoFrame === null ) {
  43350. const init = {
  43351. timestamp: 0,
  43352. codedWidth: 1,
  43353. codedHeight: 1,
  43354. format: 'RGBA',
  43355. };
  43356. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  43357. }
  43358. return defaultVideoFrame;
  43359. }
  43360. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  43361. for ( let i = 0; i < 6; i ++ ) {
  43362. const image = images[ i ];
  43363. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  43364. if ( image.isDataTexture ) {
  43365. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43366. } else {
  43367. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43368. }
  43369. }
  43370. }
  43371. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  43372. const device = this.backend.device;
  43373. device.queue.copyExternalImageToTexture(
  43374. {
  43375. source: image
  43376. }, {
  43377. texture: textureGPU,
  43378. mipLevel: 0,
  43379. origin: { x: 0, y: 0, z: originDepth }
  43380. }, {
  43381. width: image.width,
  43382. height: image.height,
  43383. depthOrArrayLayers: 1
  43384. }
  43385. );
  43386. if ( flipY === true ) {
  43387. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  43388. }
  43389. }
  43390. _getPassUtils() {
  43391. let passUtils = this._passUtils;
  43392. if ( passUtils === null ) {
  43393. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  43394. }
  43395. return passUtils;
  43396. }
  43397. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  43398. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  43399. }
  43400. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  43401. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  43402. }
  43403. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  43404. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43405. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  43406. const device = this.backend.device;
  43407. const data = image.data;
  43408. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  43409. const bytesPerRow = image.width * bytesPerTexel;
  43410. device.queue.writeTexture(
  43411. {
  43412. texture: textureGPU,
  43413. mipLevel: 0,
  43414. origin: { x: 0, y: 0, z: originDepth }
  43415. },
  43416. data,
  43417. {
  43418. offset: image.width * image.height * bytesPerTexel * depth,
  43419. bytesPerRow
  43420. },
  43421. {
  43422. width: image.width,
  43423. height: image.height,
  43424. depthOrArrayLayers: 1
  43425. } );
  43426. if ( flipY === true ) {
  43427. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  43428. }
  43429. }
  43430. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  43431. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43432. const device = this.backend.device;
  43433. const blockData = this._getBlockData( textureDescriptorGPU.format );
  43434. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  43435. for ( let i = 0; i < mipmaps.length; i ++ ) {
  43436. const mipmap = mipmaps[ i ];
  43437. const width = mipmap.width;
  43438. const height = mipmap.height;
  43439. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  43440. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  43441. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  43442. for ( let j = 0; j < depth; j ++ ) {
  43443. device.queue.writeTexture(
  43444. {
  43445. texture: textureGPU,
  43446. mipLevel: i,
  43447. origin: { x: 0, y: 0, z: j }
  43448. },
  43449. mipmap.data,
  43450. {
  43451. offset: j * bytesPerImage,
  43452. bytesPerRow,
  43453. rowsPerImage: Math.ceil( height / blockData.height )
  43454. },
  43455. {
  43456. width: Math.ceil( width / blockData.width ) * blockData.width,
  43457. height: Math.ceil( height / blockData.height ) * blockData.height,
  43458. depthOrArrayLayers: 1
  43459. }
  43460. );
  43461. }
  43462. }
  43463. }
  43464. _getBlockData( format ) {
  43465. // this method is only relevant for compressed texture formats
  43466. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  43467. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  43468. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  43469. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  43470. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  43471. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  43472. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  43473. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43474. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43475. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43476. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  43477. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  43478. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  43479. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  43480. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43481. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  43482. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  43483. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  43484. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  43485. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  43486. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  43487. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  43488. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  43489. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  43490. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  43491. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  43492. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  43493. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  43494. }
  43495. _convertAddressMode( value ) {
  43496. let addressMode = GPUAddressMode.ClampToEdge;
  43497. if ( value === RepeatWrapping ) {
  43498. addressMode = GPUAddressMode.Repeat;
  43499. } else if ( value === MirroredRepeatWrapping ) {
  43500. addressMode = GPUAddressMode.MirrorRepeat;
  43501. }
  43502. return addressMode;
  43503. }
  43504. _convertFilterMode( value ) {
  43505. let filterMode = GPUFilterMode.Linear;
  43506. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  43507. filterMode = GPUFilterMode.Nearest;
  43508. }
  43509. return filterMode;
  43510. }
  43511. _getBytesPerTexel( format ) {
  43512. // 8-bit formats
  43513. if ( format === GPUTextureFormat.R8Unorm ||
  43514. format === GPUTextureFormat.R8Snorm ||
  43515. format === GPUTextureFormat.R8Uint ||
  43516. format === GPUTextureFormat.R8Sint ) return 1;
  43517. // 16-bit formats
  43518. if ( format === GPUTextureFormat.R16Uint ||
  43519. format === GPUTextureFormat.R16Sint ||
  43520. format === GPUTextureFormat.R16Float ||
  43521. format === GPUTextureFormat.RG8Unorm ||
  43522. format === GPUTextureFormat.RG8Snorm ||
  43523. format === GPUTextureFormat.RG8Uint ||
  43524. format === GPUTextureFormat.RG8Sint ) return 2;
  43525. // 32-bit formats
  43526. if ( format === GPUTextureFormat.R32Uint ||
  43527. format === GPUTextureFormat.R32Sint ||
  43528. format === GPUTextureFormat.R32Float ||
  43529. format === GPUTextureFormat.RG16Uint ||
  43530. format === GPUTextureFormat.RG16Sint ||
  43531. format === GPUTextureFormat.RG16Float ||
  43532. format === GPUTextureFormat.RGBA8Unorm ||
  43533. format === GPUTextureFormat.RGBA8UnormSRGB ||
  43534. format === GPUTextureFormat.RGBA8Snorm ||
  43535. format === GPUTextureFormat.RGBA8Uint ||
  43536. format === GPUTextureFormat.RGBA8Sint ||
  43537. format === GPUTextureFormat.BGRA8Unorm ||
  43538. format === GPUTextureFormat.BGRA8UnormSRGB ||
  43539. // Packed 32-bit formats
  43540. format === GPUTextureFormat.RGB9E5UFloat ||
  43541. format === GPUTextureFormat.RGB10A2Unorm ||
  43542. format === GPUTextureFormat.RG11B10UFloat ||
  43543. format === GPUTextureFormat.Depth32Float ||
  43544. format === GPUTextureFormat.Depth24Plus ||
  43545. format === GPUTextureFormat.Depth24PlusStencil8 ||
  43546. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  43547. // 64-bit formats
  43548. if ( format === GPUTextureFormat.RG32Uint ||
  43549. format === GPUTextureFormat.RG32Sint ||
  43550. format === GPUTextureFormat.RG32Float ||
  43551. format === GPUTextureFormat.RGBA16Uint ||
  43552. format === GPUTextureFormat.RGBA16Sint ||
  43553. format === GPUTextureFormat.RGBA16Float ) return 8;
  43554. // 128-bit formats
  43555. if ( format === GPUTextureFormat.RGBA32Uint ||
  43556. format === GPUTextureFormat.RGBA32Sint ||
  43557. format === GPUTextureFormat.RGBA32Float ) return 16;
  43558. }
  43559. _getTypedArrayType( format ) {
  43560. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  43561. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  43562. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  43563. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  43564. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  43565. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  43566. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  43567. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  43568. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  43569. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  43570. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  43571. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  43572. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  43573. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  43574. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  43575. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  43576. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  43577. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  43578. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  43579. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  43580. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  43581. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  43582. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  43583. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  43584. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  43585. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  43586. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  43587. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  43588. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  43589. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  43590. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  43591. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  43592. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  43593. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  43594. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  43595. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  43596. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  43597. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  43598. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  43599. }
  43600. _getDimension( texture ) {
  43601. let dimension;
  43602. if ( texture.isData3DTexture ) {
  43603. dimension = GPUTextureDimension.ThreeD;
  43604. } else {
  43605. dimension = GPUTextureDimension.TwoD;
  43606. }
  43607. return dimension;
  43608. }
  43609. }
  43610. function getFormat( texture, device = null ) {
  43611. const format = texture.format;
  43612. const type = texture.type;
  43613. const colorSpace = texture.colorSpace;
  43614. let formatGPU;
  43615. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  43616. formatGPU = GPUTextureFormat.BGRA8Unorm;
  43617. } else if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  43618. switch ( format ) {
  43619. case RGBA_S3TC_DXT1_Format:
  43620. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  43621. break;
  43622. case RGBA_S3TC_DXT3_Format:
  43623. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  43624. break;
  43625. case RGBA_S3TC_DXT5_Format:
  43626. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  43627. break;
  43628. case RGB_ETC2_Format:
  43629. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  43630. break;
  43631. case RGBA_ETC2_EAC_Format:
  43632. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  43633. break;
  43634. case RGBA_ASTC_4x4_Format:
  43635. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  43636. break;
  43637. case RGBA_ASTC_5x4_Format:
  43638. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  43639. break;
  43640. case RGBA_ASTC_5x5_Format:
  43641. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  43642. break;
  43643. case RGBA_ASTC_6x5_Format:
  43644. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  43645. break;
  43646. case RGBA_ASTC_6x6_Format:
  43647. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  43648. break;
  43649. case RGBA_ASTC_8x5_Format:
  43650. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  43651. break;
  43652. case RGBA_ASTC_8x6_Format:
  43653. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  43654. break;
  43655. case RGBA_ASTC_8x8_Format:
  43656. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  43657. break;
  43658. case RGBA_ASTC_10x5_Format:
  43659. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  43660. break;
  43661. case RGBA_ASTC_10x6_Format:
  43662. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  43663. break;
  43664. case RGBA_ASTC_10x8_Format:
  43665. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  43666. break;
  43667. case RGBA_ASTC_10x10_Format:
  43668. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  43669. break;
  43670. case RGBA_ASTC_12x10_Format:
  43671. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  43672. break;
  43673. case RGBA_ASTC_12x12_Format:
  43674. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  43675. break;
  43676. default:
  43677. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43678. }
  43679. } else {
  43680. switch ( format ) {
  43681. case RGBAFormat:
  43682. switch ( type ) {
  43683. case ByteType:
  43684. formatGPU = GPUTextureFormat.RGBA8Snorm;
  43685. break;
  43686. case ShortType:
  43687. formatGPU = GPUTextureFormat.RGBA16Sint;
  43688. break;
  43689. case UnsignedShortType:
  43690. formatGPU = GPUTextureFormat.RGBA16Uint;
  43691. break;
  43692. case UnsignedIntType:
  43693. formatGPU = GPUTextureFormat.RGBA32Uint;
  43694. break;
  43695. case IntType:
  43696. formatGPU = GPUTextureFormat.RGBA32Sint;
  43697. break;
  43698. case UnsignedByteType:
  43699. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43700. break;
  43701. case HalfFloatType:
  43702. formatGPU = GPUTextureFormat.RGBA16Float;
  43703. break;
  43704. case FloatType:
  43705. formatGPU = GPUTextureFormat.RGBA32Float;
  43706. break;
  43707. default:
  43708. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  43709. }
  43710. break;
  43711. case RGBFormat:
  43712. switch ( type ) {
  43713. case UnsignedInt5999Type:
  43714. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  43715. break;
  43716. default:
  43717. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  43718. }
  43719. break;
  43720. case RedFormat:
  43721. switch ( type ) {
  43722. case ByteType:
  43723. formatGPU = GPUTextureFormat.R8Snorm;
  43724. break;
  43725. case ShortType:
  43726. formatGPU = GPUTextureFormat.R16Sint;
  43727. break;
  43728. case UnsignedShortType:
  43729. formatGPU = GPUTextureFormat.R16Uint;
  43730. break;
  43731. case UnsignedIntType:
  43732. formatGPU = GPUTextureFormat.R32Uint;
  43733. break;
  43734. case IntType:
  43735. formatGPU = GPUTextureFormat.R32Sint;
  43736. break;
  43737. case UnsignedByteType:
  43738. formatGPU = GPUTextureFormat.R8Unorm;
  43739. break;
  43740. case HalfFloatType:
  43741. formatGPU = GPUTextureFormat.R16Float;
  43742. break;
  43743. case FloatType:
  43744. formatGPU = GPUTextureFormat.R32Float;
  43745. break;
  43746. default:
  43747. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  43748. }
  43749. break;
  43750. case RGFormat:
  43751. switch ( type ) {
  43752. case ByteType:
  43753. formatGPU = GPUTextureFormat.RG8Snorm;
  43754. break;
  43755. case ShortType:
  43756. formatGPU = GPUTextureFormat.RG16Sint;
  43757. break;
  43758. case UnsignedShortType:
  43759. formatGPU = GPUTextureFormat.RG16Uint;
  43760. break;
  43761. case UnsignedIntType:
  43762. formatGPU = GPUTextureFormat.RG32Uint;
  43763. break;
  43764. case IntType:
  43765. formatGPU = GPUTextureFormat.RG32Sint;
  43766. break;
  43767. case UnsignedByteType:
  43768. formatGPU = GPUTextureFormat.RG8Unorm;
  43769. break;
  43770. case HalfFloatType:
  43771. formatGPU = GPUTextureFormat.RG16Float;
  43772. break;
  43773. case FloatType:
  43774. formatGPU = GPUTextureFormat.RG32Float;
  43775. break;
  43776. default:
  43777. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  43778. }
  43779. break;
  43780. case DepthFormat:
  43781. switch ( type ) {
  43782. case UnsignedShortType:
  43783. formatGPU = GPUTextureFormat.Depth16Unorm;
  43784. break;
  43785. case UnsignedIntType:
  43786. formatGPU = GPUTextureFormat.Depth24Plus;
  43787. break;
  43788. case FloatType:
  43789. formatGPU = GPUTextureFormat.Depth32Float;
  43790. break;
  43791. default:
  43792. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  43793. }
  43794. break;
  43795. case DepthStencilFormat:
  43796. switch ( type ) {
  43797. case UnsignedInt248Type:
  43798. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  43799. break;
  43800. case FloatType:
  43801. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  43802. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  43803. }
  43804. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  43805. break;
  43806. default:
  43807. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  43808. }
  43809. break;
  43810. case RedIntegerFormat:
  43811. switch ( type ) {
  43812. case IntType:
  43813. formatGPU = GPUTextureFormat.R32Sint;
  43814. break;
  43815. case UnsignedIntType:
  43816. formatGPU = GPUTextureFormat.R32Uint;
  43817. break;
  43818. default:
  43819. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  43820. }
  43821. break;
  43822. case RGIntegerFormat:
  43823. switch ( type ) {
  43824. case IntType:
  43825. formatGPU = GPUTextureFormat.RG32Sint;
  43826. break;
  43827. case UnsignedIntType:
  43828. formatGPU = GPUTextureFormat.RG32Uint;
  43829. break;
  43830. default:
  43831. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  43832. }
  43833. break;
  43834. case RGBAIntegerFormat:
  43835. switch ( type ) {
  43836. case IntType:
  43837. formatGPU = GPUTextureFormat.RGBA32Sint;
  43838. break;
  43839. case UnsignedIntType:
  43840. formatGPU = GPUTextureFormat.RGBA32Uint;
  43841. break;
  43842. default:
  43843. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43844. }
  43845. break;
  43846. default:
  43847. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43848. }
  43849. }
  43850. return formatGPU;
  43851. }
  43852. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43853. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43854. const wgslTypeLib$1 = {
  43855. 'f32': 'float',
  43856. 'i32': 'int',
  43857. 'u32': 'uint',
  43858. 'bool': 'bool',
  43859. 'vec2<f32>': 'vec2',
  43860. 'vec2<i32>': 'ivec2',
  43861. 'vec2<u32>': 'uvec2',
  43862. 'vec2<bool>': 'bvec2',
  43863. 'vec2f': 'vec2',
  43864. 'vec2i': 'ivec2',
  43865. 'vec2u': 'uvec2',
  43866. 'vec2b': 'bvec2',
  43867. 'vec3<f32>': 'vec3',
  43868. 'vec3<i32>': 'ivec3',
  43869. 'vec3<u32>': 'uvec3',
  43870. 'vec3<bool>': 'bvec3',
  43871. 'vec3f': 'vec3',
  43872. 'vec3i': 'ivec3',
  43873. 'vec3u': 'uvec3',
  43874. 'vec3b': 'bvec3',
  43875. 'vec4<f32>': 'vec4',
  43876. 'vec4<i32>': 'ivec4',
  43877. 'vec4<u32>': 'uvec4',
  43878. 'vec4<bool>': 'bvec4',
  43879. 'vec4f': 'vec4',
  43880. 'vec4i': 'ivec4',
  43881. 'vec4u': 'uvec4',
  43882. 'vec4b': 'bvec4',
  43883. 'mat2x2<f32>': 'mat2',
  43884. 'mat2x2f': 'mat2',
  43885. 'mat3x3<f32>': 'mat3',
  43886. 'mat3x3f': 'mat3',
  43887. 'mat4x4<f32>': 'mat4',
  43888. 'mat4x4f': 'mat4',
  43889. 'sampler': 'sampler',
  43890. 'texture_1d': 'texture',
  43891. 'texture_2d': 'texture',
  43892. 'texture_2d_array': 'texture',
  43893. 'texture_multisampled_2d': 'cubeTexture',
  43894. 'texture_depth_2d': 'depthTexture',
  43895. 'texture_3d': 'texture3D',
  43896. 'texture_cube': 'cubeTexture',
  43897. 'texture_cube_array': 'cubeTexture',
  43898. 'texture_storage_1d': 'storageTexture',
  43899. 'texture_storage_2d': 'storageTexture',
  43900. 'texture_storage_2d_array': 'storageTexture',
  43901. 'texture_storage_3d': 'storageTexture'
  43902. };
  43903. const parse = ( source ) => {
  43904. source = source.trim();
  43905. const declaration = source.match( declarationRegexp );
  43906. if ( declaration !== null && declaration.length === 4 ) {
  43907. const inputsCode = declaration[ 2 ];
  43908. const propsMatches = [];
  43909. let match = null;
  43910. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  43911. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  43912. }
  43913. // Process matches to correctly pair names and types
  43914. const inputs = [];
  43915. for ( let i = 0; i < propsMatches.length; i ++ ) {
  43916. const { name, type } = propsMatches[ i ];
  43917. let resolvedType = type;
  43918. if ( resolvedType.startsWith( 'texture' ) ) {
  43919. resolvedType = type.split( '<' )[ 0 ];
  43920. }
  43921. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  43922. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  43923. }
  43924. const blockCode = source.substring( declaration[ 0 ].length );
  43925. const outputType = declaration[ 3 ] || 'void';
  43926. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  43927. const type = wgslTypeLib$1[ outputType ] || outputType;
  43928. return {
  43929. type,
  43930. inputs,
  43931. name,
  43932. inputsCode,
  43933. blockCode,
  43934. outputType
  43935. };
  43936. } else {
  43937. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  43938. }
  43939. };
  43940. class WGSLNodeFunction extends NodeFunction {
  43941. constructor( source ) {
  43942. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  43943. super( type, inputs, name );
  43944. this.inputsCode = inputsCode;
  43945. this.blockCode = blockCode;
  43946. this.outputType = outputType;
  43947. }
  43948. getCode( name = this.name ) {
  43949. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  43950. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  43951. }
  43952. }
  43953. class WGSLNodeParser extends NodeParser {
  43954. parseFunction( source ) {
  43955. return new WGSLNodeFunction( source );
  43956. }
  43957. }
  43958. // GPUShaderStage is not defined in browsers not supporting WebGPU
  43959. const GPUShaderStage = self.GPUShaderStage;
  43960. const gpuShaderStageLib = {
  43961. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  43962. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  43963. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  43964. };
  43965. const supports = {
  43966. instance: true,
  43967. swizzleAssign: false,
  43968. storageBuffer: true
  43969. };
  43970. const wgslFnOpLib = {
  43971. '^^': 'tsl_xor'
  43972. };
  43973. const wgslTypeLib = {
  43974. float: 'f32',
  43975. int: 'i32',
  43976. uint: 'u32',
  43977. bool: 'bool',
  43978. color: 'vec3<f32>',
  43979. vec2: 'vec2<f32>',
  43980. ivec2: 'vec2<i32>',
  43981. uvec2: 'vec2<u32>',
  43982. bvec2: 'vec2<bool>',
  43983. vec3: 'vec3<f32>',
  43984. ivec3: 'vec3<i32>',
  43985. uvec3: 'vec3<u32>',
  43986. bvec3: 'vec3<bool>',
  43987. vec4: 'vec4<f32>',
  43988. ivec4: 'vec4<i32>',
  43989. uvec4: 'vec4<u32>',
  43990. bvec4: 'vec4<bool>',
  43991. mat2: 'mat2x2<f32>',
  43992. imat2: 'mat2x2<i32>',
  43993. umat2: 'mat2x2<u32>',
  43994. bmat2: 'mat2x2<bool>',
  43995. mat3: 'mat3x3<f32>',
  43996. imat3: 'mat3x3<i32>',
  43997. umat3: 'mat3x3<u32>',
  43998. bmat3: 'mat3x3<bool>',
  43999. mat4: 'mat4x4<f32>',
  44000. imat4: 'mat4x4<i32>',
  44001. umat4: 'mat4x4<u32>',
  44002. bmat4: 'mat4x4<bool>'
  44003. };
  44004. const wgslPolyfill = {
  44005. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  44006. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  44007. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  44008. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  44009. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  44010. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  44011. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  44012. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  44013. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  44014. repeatWrapping: new CodeNode( `
  44015. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  44016. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  44017. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  44018. }
  44019. ` ),
  44020. biquadraticTexture: new CodeNode( `
  44021. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  44022. let iRes = vec2i( textureDimensions( map, level ) );
  44023. let res = vec2f( iRes );
  44024. let uvScaled = coord * res;
  44025. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  44026. // https://www.shadertoy.com/view/WtyXRy
  44027. let uv = uvWrapping - 0.5;
  44028. let iuv = floor( uv );
  44029. let f = fract( uv );
  44030. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  44031. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  44032. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  44033. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  44034. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  44035. }
  44036. ` )
  44037. };
  44038. const wgslMethods = {
  44039. dFdx: 'dpdx',
  44040. dFdy: '- dpdy',
  44041. mod_float: 'tsl_mod_float',
  44042. mod_vec2: 'tsl_mod_vec2',
  44043. mod_vec3: 'tsl_mod_vec3',
  44044. mod_vec4: 'tsl_mod_vec4',
  44045. equals_bool: 'tsl_equals_bool',
  44046. equals_bvec2: 'tsl_equals_bvec2',
  44047. equals_bvec3: 'tsl_equals_bvec3',
  44048. equals_bvec4: 'tsl_equals_bvec4',
  44049. inversesqrt: 'inverseSqrt',
  44050. bitcast: 'bitcast<f32>'
  44051. };
  44052. // WebGPU issue: does not support pow() with negative base on Windows
  44053. if ( /Windows/g.test( navigator.userAgent ) ) {
  44054. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  44055. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  44056. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  44057. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  44058. wgslMethods.pow_float = 'tsl_pow_float';
  44059. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  44060. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  44061. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  44062. }
  44063. //
  44064. let diagnostics = '';
  44065. if ( /Firefox/g.test( navigator.userAgent ) !== true ) {
  44066. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  44067. }
  44068. //
  44069. class WGSLNodeBuilder extends NodeBuilder {
  44070. constructor( object, renderer ) {
  44071. super( object, renderer, new WGSLNodeParser() );
  44072. this.uniformGroups = {};
  44073. this.builtins = {};
  44074. this.directives = {};
  44075. this.scopedArrays = new Map();
  44076. }
  44077. needsToWorkingColorSpace( texture ) {
  44078. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44079. }
  44080. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44081. if ( shaderStage === 'fragment' ) {
  44082. if ( depthSnippet ) {
  44083. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  44084. } else {
  44085. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  44086. }
  44087. } else if ( this.isFilteredTexture( texture ) ) {
  44088. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  44089. } else {
  44090. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  44091. }
  44092. }
  44093. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  44094. if ( shaderStage === 'fragment' ) {
  44095. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  44096. } else {
  44097. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  44098. }
  44099. }
  44100. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44101. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  44102. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  44103. } else if ( this.isFilteredTexture( texture ) ) {
  44104. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  44105. } else {
  44106. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  44107. }
  44108. }
  44109. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  44110. this._include( 'biquadraticTexture' );
  44111. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  44112. }
  44113. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  44114. this._include( 'repeatWrapping' );
  44115. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  44116. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  44117. }
  44118. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  44119. if ( depthSnippet ) {
  44120. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  44121. } else {
  44122. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44123. }
  44124. }
  44125. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  44126. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  44127. }
  44128. isUnfilterable( texture ) {
  44129. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  44130. }
  44131. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44132. let snippet = null;
  44133. if ( texture.isVideoTexture === true ) {
  44134. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44135. } else if ( this.isUnfilterable( texture ) ) {
  44136. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  44137. } else {
  44138. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  44139. }
  44140. return snippet;
  44141. }
  44142. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44143. if ( shaderStage === 'fragment' ) {
  44144. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  44145. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44146. } else {
  44147. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  44148. }
  44149. }
  44150. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44151. if ( shaderStage === 'fragment' ) {
  44152. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  44153. } else {
  44154. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44155. }
  44156. }
  44157. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44158. let snippet = null;
  44159. if ( texture.isVideoTexture === true ) {
  44160. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44161. } else {
  44162. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  44163. }
  44164. return snippet;
  44165. }
  44166. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44167. if ( shaderStage === 'fragment' ) {
  44168. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  44169. } else {
  44170. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  44171. }
  44172. }
  44173. getPropertyName( node, shaderStage = this.shaderStage ) {
  44174. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  44175. if ( shaderStage === 'vertex' ) {
  44176. return `varyings.${ node.name }`;
  44177. }
  44178. } else if ( node.isNodeUniform === true ) {
  44179. const name = node.name;
  44180. const type = node.type;
  44181. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44182. return name;
  44183. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  44184. return `NodeBuffer_${ node.id }.${name}`;
  44185. } else {
  44186. return node.groupNode.name + '.' + name;
  44187. }
  44188. }
  44189. return super.getPropertyName( node );
  44190. }
  44191. getOutputStructName() {
  44192. return 'output';
  44193. }
  44194. _getUniformGroupCount( shaderStage ) {
  44195. return Object.keys( this.uniforms[ shaderStage ] ).length;
  44196. }
  44197. getFunctionOperator( op ) {
  44198. const fnOp = wgslFnOpLib[ op ];
  44199. if ( fnOp !== undefined ) {
  44200. this._include( fnOp );
  44201. return fnOp;
  44202. }
  44203. return null;
  44204. }
  44205. getStorageAccess( node ) {
  44206. if ( node.isStorageTextureNode ) {
  44207. switch ( node.access ) {
  44208. case GPUStorageTextureAccess.ReadOnly:
  44209. return 'read';
  44210. case GPUStorageTextureAccess.WriteOnly:
  44211. return 'write';
  44212. default:
  44213. return 'read_write';
  44214. }
  44215. } else {
  44216. switch ( node.access ) {
  44217. case GPUBufferBindingType.Storage:
  44218. return 'read_write';
  44219. case GPUBufferBindingType.ReadOnlyStorage:
  44220. return 'read';
  44221. default:
  44222. return 'write';
  44223. }
  44224. }
  44225. }
  44226. getUniformFromNode( node, type, shaderStage, name = null ) {
  44227. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44228. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44229. if ( nodeData.uniformGPU === undefined ) {
  44230. let uniformGPU;
  44231. const group = node.groupNode;
  44232. const groupName = group.name;
  44233. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44234. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44235. let texture = null;
  44236. if ( type === 'texture' || type === 'storageTexture' ) {
  44237. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  44238. } else if ( type === 'cubeTexture' ) {
  44239. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  44240. } else if ( type === 'texture3D' ) {
  44241. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  44242. }
  44243. texture.store = node.isStorageTextureNode === true;
  44244. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44245. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  44246. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  44247. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44248. bindings.push( sampler, texture );
  44249. uniformGPU = [ sampler, texture ];
  44250. } else {
  44251. bindings.push( texture );
  44252. uniformGPU = [ texture ];
  44253. }
  44254. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  44255. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  44256. const buffer = new bufferClass( node, group );
  44257. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44258. bindings.push( buffer );
  44259. uniformGPU = buffer;
  44260. } else {
  44261. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44262. let uniformsGroup = uniformsStage[ groupName ];
  44263. if ( uniformsGroup === undefined ) {
  44264. uniformsGroup = new NodeUniformsGroup( groupName, group );
  44265. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44266. uniformsStage[ groupName ] = uniformsGroup;
  44267. bindings.push( uniformsGroup );
  44268. }
  44269. uniformGPU = this.getNodeUniform( uniformNode, type );
  44270. uniformsGroup.addUniform( uniformGPU );
  44271. }
  44272. nodeData.uniformGPU = uniformGPU;
  44273. }
  44274. return uniformNode;
  44275. }
  44276. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  44277. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  44278. if ( map.has( name ) === false ) {
  44279. map.set( name, {
  44280. name,
  44281. property,
  44282. type
  44283. } );
  44284. }
  44285. return property;
  44286. }
  44287. hasBuiltin( name, shaderStage = this.shaderStage ) {
  44288. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  44289. }
  44290. getVertexIndex() {
  44291. if ( this.shaderStage === 'vertex' ) {
  44292. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  44293. }
  44294. return 'vertexIndex';
  44295. }
  44296. buildFunctionCode( shaderNode ) {
  44297. const layout = shaderNode.layout;
  44298. const flowData = this.flowShaderNode( shaderNode );
  44299. const parameters = [];
  44300. for ( const input of layout.inputs ) {
  44301. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  44302. }
  44303. //
  44304. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  44305. ${ flowData.vars }
  44306. ${ flowData.code }
  44307. `;
  44308. if ( flowData.result ) {
  44309. code += `\treturn ${ flowData.result };\n`;
  44310. }
  44311. code += '\n}\n';
  44312. //
  44313. return code;
  44314. }
  44315. getInstanceIndex() {
  44316. if ( this.shaderStage === 'vertex' ) {
  44317. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  44318. }
  44319. return 'instanceIndex';
  44320. }
  44321. getInvocationLocalIndex() {
  44322. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  44323. }
  44324. getSubgroupSize() {
  44325. this.enableSubGroups();
  44326. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44327. }
  44328. getInvocationSubgroupIndex() {
  44329. this.enableSubGroups();
  44330. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  44331. }
  44332. getSubgroupIndex() {
  44333. this.enableSubGroups();
  44334. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  44335. }
  44336. getDrawIndex() {
  44337. return null;
  44338. }
  44339. getFrontFacing() {
  44340. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  44341. }
  44342. getFragCoord() {
  44343. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  44344. }
  44345. getFragDepth() {
  44346. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  44347. }
  44348. isFlipY() {
  44349. return false;
  44350. }
  44351. enableDirective( name, shaderStage = this.shaderStage ) {
  44352. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  44353. stage.add( name );
  44354. }
  44355. getDirectives( shaderStage ) {
  44356. const snippets = [];
  44357. const directives = this.directives[ shaderStage ];
  44358. if ( directives !== undefined ) {
  44359. for ( const directive of directives ) {
  44360. snippets.push( `enable ${directive};` );
  44361. }
  44362. }
  44363. return snippets.join( '\n' );
  44364. }
  44365. enableSubGroups() {
  44366. this.enableDirective( 'subgroups' );
  44367. }
  44368. enableSubgroupsF16() {
  44369. this.enableDirective( 'subgroups-f16' );
  44370. }
  44371. enableClipDistances() {
  44372. this.enableDirective( 'clip_distances' );
  44373. }
  44374. enableShaderF16() {
  44375. this.enableDirective( 'f16' );
  44376. }
  44377. enableDualSourceBlending() {
  44378. this.enableDirective( 'dual_source_blending' );
  44379. }
  44380. getBuiltins( shaderStage ) {
  44381. const snippets = [];
  44382. const builtins = this.builtins[ shaderStage ];
  44383. if ( builtins !== undefined ) {
  44384. for ( const { name, property, type } of builtins.values() ) {
  44385. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  44386. }
  44387. }
  44388. return snippets.join( ',\n\t' );
  44389. }
  44390. getScopedArray( name, scope, bufferType, bufferCount ) {
  44391. if ( this.scopedArrays.has( name ) === false ) {
  44392. this.scopedArrays.set( name, {
  44393. name,
  44394. scope,
  44395. bufferType,
  44396. bufferCount
  44397. } );
  44398. }
  44399. return name;
  44400. }
  44401. getScopedArrays( shaderStage ) {
  44402. if ( shaderStage !== 'compute' ) {
  44403. return;
  44404. }
  44405. const snippets = [];
  44406. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  44407. const type = this.getType( bufferType );
  44408. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  44409. }
  44410. return snippets.join( '\n' );
  44411. }
  44412. getAttributes( shaderStage ) {
  44413. const snippets = [];
  44414. if ( shaderStage === 'compute' ) {
  44415. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  44416. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  44417. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  44418. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  44419. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  44420. this.enableDirective( 'subgroups', shaderStage );
  44421. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44422. }
  44423. }
  44424. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44425. const builtins = this.getBuiltins( 'attribute' );
  44426. if ( builtins ) snippets.push( builtins );
  44427. const attributes = this.getAttributesArray();
  44428. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  44429. const attribute = attributes[ index ];
  44430. const name = attribute.name;
  44431. const type = this.getType( attribute.type );
  44432. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  44433. }
  44434. }
  44435. return snippets.join( ',\n\t' );
  44436. }
  44437. getStructMembers( struct ) {
  44438. const snippets = [];
  44439. const members = struct.getMemberTypes();
  44440. for ( let i = 0; i < members.length; i ++ ) {
  44441. const member = members[ i ];
  44442. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  44443. }
  44444. const builtins = this.getBuiltins( 'output' );
  44445. if ( builtins ) snippets.push( '\t' + builtins );
  44446. return snippets.join( ',\n' );
  44447. }
  44448. getStructs( shaderStage ) {
  44449. const snippets = [];
  44450. const structs = this.structs[ shaderStage ];
  44451. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  44452. const struct = structs[ index ];
  44453. const name = struct.name;
  44454. let snippet = `\struct ${ name } {\n`;
  44455. snippet += this.getStructMembers( struct );
  44456. snippet += '\n}';
  44457. snippets.push( snippet );
  44458. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  44459. }
  44460. return snippets.join( '\n\n' );
  44461. }
  44462. getVar( type, name ) {
  44463. return `var ${ name } : ${ this.getType( type ) }`;
  44464. }
  44465. getVars( shaderStage ) {
  44466. const snippets = [];
  44467. const vars = this.vars[ shaderStage ];
  44468. if ( vars !== undefined ) {
  44469. for ( const variable of vars ) {
  44470. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  44471. }
  44472. }
  44473. return `\n${ snippets.join( '\n' ) }\n`;
  44474. }
  44475. getVaryings( shaderStage ) {
  44476. const snippets = [];
  44477. if ( shaderStage === 'vertex' ) {
  44478. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  44479. }
  44480. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  44481. const varyings = this.varyings;
  44482. const vars = this.vars[ shaderStage ];
  44483. for ( let index = 0; index < varyings.length; index ++ ) {
  44484. const varying = varyings[ index ];
  44485. if ( varying.needsInterpolation ) {
  44486. let attributesSnippet = `@location( ${index} )`;
  44487. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  44488. attributesSnippet += ' @interpolate( flat )';
  44489. }
  44490. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  44491. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  44492. vars.push( varying );
  44493. }
  44494. }
  44495. }
  44496. const builtins = this.getBuiltins( shaderStage );
  44497. if ( builtins ) snippets.push( builtins );
  44498. const code = snippets.join( ',\n\t' );
  44499. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  44500. }
  44501. getUniforms( shaderStage ) {
  44502. const uniforms = this.uniforms[ shaderStage ];
  44503. const bindingSnippets = [];
  44504. const bufferSnippets = [];
  44505. const structSnippets = [];
  44506. const uniformGroups = {};
  44507. for ( const uniform of uniforms ) {
  44508. const groupName = uniform.groupNode.name;
  44509. const uniformIndexes = this.bindingsIndexes[ groupName ];
  44510. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  44511. const texture = uniform.node.value;
  44512. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  44513. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  44514. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  44515. } else {
  44516. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  44517. }
  44518. }
  44519. let textureType;
  44520. let multisampled = '';
  44521. if ( texture.isMultisampleRenderTargetTexture === true ) {
  44522. multisampled = '_multisampled';
  44523. }
  44524. if ( texture.isCubeTexture === true ) {
  44525. textureType = 'texture_cube<f32>';
  44526. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44527. textureType = 'texture_2d_array<f32>';
  44528. } else if ( texture.isDepthTexture === true ) {
  44529. textureType = `texture_depth${multisampled}_2d`;
  44530. } else if ( texture.isVideoTexture === true ) {
  44531. textureType = 'texture_external';
  44532. } else if ( texture.isData3DTexture === true ) {
  44533. textureType = 'texture_3d<f32>';
  44534. } else if ( uniform.node.isStorageTextureNode === true ) {
  44535. const format = getFormat( texture );
  44536. const access = this.getStorageAccess( uniform.node );
  44537. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  44538. } else {
  44539. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  44540. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  44541. }
  44542. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  44543. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  44544. const bufferNode = uniform.node;
  44545. const bufferType = this.getType( bufferNode.bufferType );
  44546. const bufferCount = bufferNode.bufferCount;
  44547. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  44548. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  44549. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  44550. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  44551. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  44552. } else {
  44553. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  44554. const groupName = uniform.groupNode.name;
  44555. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  44556. index: uniformIndexes.binding ++,
  44557. id: uniformIndexes.group,
  44558. snippets: []
  44559. } );
  44560. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  44561. }
  44562. }
  44563. for ( const name in uniformGroups ) {
  44564. const group = uniformGroups[ name ];
  44565. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  44566. }
  44567. let code = bindingSnippets.join( '\n' );
  44568. code += bufferSnippets.join( '\n' );
  44569. code += structSnippets.join( '\n' );
  44570. return code;
  44571. }
  44572. buildCode() {
  44573. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44574. this.sortBindingGroups();
  44575. for ( const shaderStage in shadersData ) {
  44576. const stageData = shadersData[ shaderStage ];
  44577. stageData.uniforms = this.getUniforms( shaderStage );
  44578. stageData.attributes = this.getAttributes( shaderStage );
  44579. stageData.varyings = this.getVaryings( shaderStage );
  44580. stageData.structs = this.getStructs( shaderStage );
  44581. stageData.vars = this.getVars( shaderStage );
  44582. stageData.codes = this.getCodes( shaderStage );
  44583. stageData.directives = this.getDirectives( shaderStage );
  44584. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  44585. //
  44586. let flow = '// code\n\n';
  44587. flow += this.flowCode[ shaderStage ];
  44588. const flowNodes = this.flowNodes[ shaderStage ];
  44589. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44590. const outputNode = mainNode.outputNode;
  44591. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  44592. for ( const node of flowNodes ) {
  44593. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44594. const slotName = node.name;
  44595. if ( slotName ) {
  44596. if ( flow.length > 0 ) flow += '\n';
  44597. flow += `\t// flow -> ${ slotName }\n\t`;
  44598. }
  44599. flow += `${ flowSlotData.code }\n\t`;
  44600. if ( node === mainNode && shaderStage !== 'compute' ) {
  44601. flow += '// result\n\n\t';
  44602. if ( shaderStage === 'vertex' ) {
  44603. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  44604. } else if ( shaderStage === 'fragment' ) {
  44605. if ( isOutputStruct ) {
  44606. stageData.returnType = outputNode.nodeType;
  44607. flow += `return ${ flowSlotData.result };`;
  44608. } else {
  44609. let structSnippet = '\t@location(0) color: vec4<f32>';
  44610. const builtins = this.getBuiltins( 'output' );
  44611. if ( builtins ) structSnippet += ',\n\t' + builtins;
  44612. stageData.returnType = 'OutputStruct';
  44613. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  44614. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  44615. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  44616. }
  44617. }
  44618. }
  44619. }
  44620. stageData.flow = flow;
  44621. }
  44622. if ( this.material !== null ) {
  44623. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  44624. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  44625. } else {
  44626. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  44627. }
  44628. }
  44629. getMethod( method, output = null ) {
  44630. let wgslMethod;
  44631. if ( output !== null ) {
  44632. wgslMethod = this._getWGSLMethod( method + '_' + output );
  44633. }
  44634. if ( wgslMethod === undefined ) {
  44635. wgslMethod = this._getWGSLMethod( method );
  44636. }
  44637. return wgslMethod || method;
  44638. }
  44639. getType( type ) {
  44640. return wgslTypeLib[ type ] || type;
  44641. }
  44642. isAvailable( name ) {
  44643. let result = supports[ name ];
  44644. if ( result === undefined ) {
  44645. if ( name === 'float32Filterable' ) {
  44646. result = this.renderer.hasFeature( 'float32-filterable' );
  44647. }
  44648. supports[ name ] = result;
  44649. }
  44650. return result;
  44651. }
  44652. _getWGSLMethod( method ) {
  44653. if ( wgslPolyfill[ method ] !== undefined ) {
  44654. this._include( method );
  44655. }
  44656. return wgslMethods[ method ];
  44657. }
  44658. _include( name ) {
  44659. const codeNode = wgslPolyfill[ name ];
  44660. codeNode.build( this );
  44661. if ( this.currentFunctionNode !== null ) {
  44662. this.currentFunctionNode.includes.push( codeNode );
  44663. }
  44664. return codeNode;
  44665. }
  44666. _getWGSLVertexCode( shaderData ) {
  44667. return `${ this.getSignature() }
  44668. // directives
  44669. ${shaderData.directives}
  44670. // uniforms
  44671. ${shaderData.uniforms}
  44672. // varyings
  44673. ${shaderData.varyings}
  44674. var<private> varyings : VaryingsStruct;
  44675. // codes
  44676. ${shaderData.codes}
  44677. @vertex
  44678. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  44679. // vars
  44680. ${shaderData.vars}
  44681. // flow
  44682. ${shaderData.flow}
  44683. return varyings;
  44684. }
  44685. `;
  44686. }
  44687. _getWGSLFragmentCode( shaderData ) {
  44688. return `${ this.getSignature() }
  44689. // global
  44690. ${ diagnostics }
  44691. // uniforms
  44692. ${shaderData.uniforms}
  44693. // structs
  44694. ${shaderData.structs}
  44695. // codes
  44696. ${shaderData.codes}
  44697. @fragment
  44698. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  44699. // vars
  44700. ${shaderData.vars}
  44701. // flow
  44702. ${shaderData.flow}
  44703. }
  44704. `;
  44705. }
  44706. _getWGSLComputeCode( shaderData, workgroupSize ) {
  44707. return `${ this.getSignature() }
  44708. // directives
  44709. ${shaderData.directives}
  44710. // system
  44711. var<private> instanceIndex : u32;
  44712. // locals
  44713. ${shaderData.scopedArrays}
  44714. // uniforms
  44715. ${shaderData.uniforms}
  44716. // codes
  44717. ${shaderData.codes}
  44718. @compute @workgroup_size( ${workgroupSize} )
  44719. fn main( ${shaderData.attributes} ) {
  44720. // system
  44721. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  44722. // vars
  44723. ${shaderData.vars}
  44724. // flow
  44725. ${shaderData.flow}
  44726. }
  44727. `;
  44728. }
  44729. _getWGSLStruct( name, vars ) {
  44730. return `
  44731. struct ${name} {
  44732. ${vars}
  44733. };`;
  44734. }
  44735. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  44736. const structName = name + 'Struct';
  44737. const structSnippet = this._getWGSLStruct( structName, vars );
  44738. return `${structSnippet}
  44739. @binding( ${binding} ) @group( ${group} )
  44740. var<${access}> ${name} : ${structName};`;
  44741. }
  44742. }
  44743. class WebGPUUtils {
  44744. constructor( backend ) {
  44745. this.backend = backend;
  44746. }
  44747. getCurrentDepthStencilFormat( renderContext ) {
  44748. let format;
  44749. if ( renderContext.depthTexture !== null ) {
  44750. format = this.getTextureFormatGPU( renderContext.depthTexture );
  44751. } else if ( renderContext.depth && renderContext.stencil ) {
  44752. format = GPUTextureFormat.Depth24PlusStencil8;
  44753. } else if ( renderContext.depth ) {
  44754. format = GPUTextureFormat.Depth24Plus;
  44755. }
  44756. return format;
  44757. }
  44758. getTextureFormatGPU( texture ) {
  44759. return this.backend.get( texture ).format;
  44760. }
  44761. getCurrentColorFormat( renderContext ) {
  44762. let format;
  44763. if ( renderContext.textures !== null ) {
  44764. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  44765. } else {
  44766. format = this.getPreferredCanvasFormat(); // default context format
  44767. }
  44768. return format;
  44769. }
  44770. getCurrentColorSpace( renderContext ) {
  44771. if ( renderContext.textures !== null ) {
  44772. return renderContext.textures[ 0 ].colorSpace;
  44773. }
  44774. return this.backend.renderer.outputColorSpace;
  44775. }
  44776. getPrimitiveTopology( object, material ) {
  44777. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  44778. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  44779. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  44780. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  44781. }
  44782. getSampleCount( sampleCount ) {
  44783. let count = 1;
  44784. if ( sampleCount > 1 ) {
  44785. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  44786. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  44787. if ( count === 2 ) {
  44788. count = 4;
  44789. }
  44790. }
  44791. return count;
  44792. }
  44793. getSampleCountRenderContext( renderContext ) {
  44794. if ( renderContext.textures !== null ) {
  44795. return this.getSampleCount( renderContext.sampleCount );
  44796. }
  44797. return this.getSampleCount( this.backend.renderer.samples );
  44798. }
  44799. getPreferredCanvasFormat() {
  44800. // TODO: Remove this check when Quest 34.5 is out
  44801. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  44802. if ( navigator.userAgent.includes( 'Quest' ) ) {
  44803. return GPUTextureFormat.BGRA8Unorm;
  44804. } else {
  44805. return navigator.gpu.getPreferredCanvasFormat();
  44806. }
  44807. }
  44808. }
  44809. const typedArraysToVertexFormatPrefix = new Map( [
  44810. [ Int8Array, [ 'sint8', 'snorm8' ]],
  44811. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  44812. [ Int16Array, [ 'sint16', 'snorm16' ]],
  44813. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  44814. [ Int32Array, [ 'sint32', 'snorm32' ]],
  44815. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  44816. [ Float32Array, [ 'float32', ]],
  44817. ] );
  44818. const typedAttributeToVertexFormatPrefix = new Map( [
  44819. [ Float16BufferAttribute, [ 'float16', ]],
  44820. ] );
  44821. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  44822. [ Int32Array, 'sint32' ],
  44823. [ Int16Array, 'sint32' ], // patch for INT16
  44824. [ Uint32Array, 'uint32' ],
  44825. [ Uint16Array, 'uint32' ], // patch for UINT16
  44826. [ Float32Array, 'float32' ]
  44827. ] );
  44828. class WebGPUAttributeUtils {
  44829. constructor( backend ) {
  44830. this.backend = backend;
  44831. }
  44832. createAttribute( attribute, usage ) {
  44833. const bufferAttribute = this._getBufferAttribute( attribute );
  44834. const backend = this.backend;
  44835. const bufferData = backend.get( bufferAttribute );
  44836. let buffer = bufferData.buffer;
  44837. if ( buffer === undefined ) {
  44838. const device = backend.device;
  44839. let array = bufferAttribute.array;
  44840. // patch for INT16 and UINT16
  44841. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  44842. const tempArray = new Uint32Array( array.length );
  44843. for ( let i = 0; i < array.length; i ++ ) {
  44844. tempArray[ i ] = array[ i ];
  44845. }
  44846. array = tempArray;
  44847. }
  44848. bufferAttribute.array = array;
  44849. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  44850. array = new array.constructor( bufferAttribute.count * 4 );
  44851. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  44852. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  44853. }
  44854. // Update BufferAttribute
  44855. bufferAttribute.itemSize = 4;
  44856. bufferAttribute.array = array;
  44857. }
  44858. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  44859. buffer = device.createBuffer( {
  44860. label: bufferAttribute.name,
  44861. size: size,
  44862. usage: usage,
  44863. mappedAtCreation: true
  44864. } );
  44865. new array.constructor( buffer.getMappedRange() ).set( array );
  44866. buffer.unmap();
  44867. bufferData.buffer = buffer;
  44868. }
  44869. }
  44870. updateAttribute( attribute ) {
  44871. const bufferAttribute = this._getBufferAttribute( attribute );
  44872. const backend = this.backend;
  44873. const device = backend.device;
  44874. const buffer = backend.get( bufferAttribute ).buffer;
  44875. const array = bufferAttribute.array;
  44876. const updateRanges = bufferAttribute.updateRanges;
  44877. if ( updateRanges.length === 0 ) {
  44878. // Not using update ranges
  44879. device.queue.writeBuffer(
  44880. buffer,
  44881. 0,
  44882. array,
  44883. 0
  44884. );
  44885. } else {
  44886. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44887. const range = updateRanges[ i ];
  44888. device.queue.writeBuffer(
  44889. buffer,
  44890. 0,
  44891. array,
  44892. range.start * array.BYTES_PER_ELEMENT,
  44893. range.count * array.BYTES_PER_ELEMENT
  44894. );
  44895. }
  44896. bufferAttribute.clearUpdateRanges();
  44897. }
  44898. }
  44899. createShaderVertexBuffers( renderObject ) {
  44900. const attributes = renderObject.getAttributes();
  44901. const vertexBuffers = new Map();
  44902. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  44903. const geometryAttribute = attributes[ slot ];
  44904. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  44905. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  44906. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  44907. if ( vertexBufferLayout === undefined ) {
  44908. let arrayStride, stepMode;
  44909. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  44910. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  44911. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44912. } else {
  44913. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  44914. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44915. }
  44916. // patch for INT16 and UINT16
  44917. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  44918. arrayStride = 4;
  44919. }
  44920. vertexBufferLayout = {
  44921. arrayStride,
  44922. attributes: [],
  44923. stepMode
  44924. };
  44925. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  44926. }
  44927. const format = this._getVertexFormat( geometryAttribute );
  44928. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  44929. vertexBufferLayout.attributes.push( {
  44930. shaderLocation: slot,
  44931. offset,
  44932. format
  44933. } );
  44934. }
  44935. return Array.from( vertexBuffers.values() );
  44936. }
  44937. destroyAttribute( attribute ) {
  44938. const backend = this.backend;
  44939. const data = backend.get( this._getBufferAttribute( attribute ) );
  44940. data.buffer.destroy();
  44941. backend.delete( attribute );
  44942. }
  44943. async getArrayBufferAsync( attribute ) {
  44944. const backend = this.backend;
  44945. const device = backend.device;
  44946. const data = backend.get( this._getBufferAttribute( attribute ) );
  44947. const bufferGPU = data.buffer;
  44948. const size = bufferGPU.size;
  44949. const readBufferGPU = device.createBuffer( {
  44950. label: attribute.name,
  44951. size,
  44952. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44953. } );
  44954. const cmdEncoder = device.createCommandEncoder( {} );
  44955. cmdEncoder.copyBufferToBuffer(
  44956. bufferGPU,
  44957. 0,
  44958. readBufferGPU,
  44959. 0,
  44960. size
  44961. );
  44962. readBufferGPU.unmap();
  44963. const gpuCommands = cmdEncoder.finish();
  44964. device.queue.submit( [ gpuCommands ] );
  44965. await readBufferGPU.mapAsync( GPUMapMode.READ );
  44966. const arrayBuffer = readBufferGPU.getMappedRange();
  44967. return arrayBuffer;
  44968. }
  44969. _getVertexFormat( geometryAttribute ) {
  44970. const { itemSize, normalized } = geometryAttribute;
  44971. const ArrayType = geometryAttribute.array.constructor;
  44972. const AttributeType = geometryAttribute.constructor;
  44973. let format;
  44974. if ( itemSize == 1 ) {
  44975. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  44976. } else {
  44977. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  44978. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  44979. if ( prefix ) {
  44980. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  44981. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  44982. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  44983. if ( paddedItemSize % 1 ) {
  44984. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  44985. }
  44986. format = `${prefix}x${paddedItemSize}`;
  44987. }
  44988. }
  44989. if ( ! format ) {
  44990. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  44991. }
  44992. return format;
  44993. }
  44994. _getBufferAttribute( attribute ) {
  44995. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  44996. return attribute;
  44997. }
  44998. }
  44999. class WebGPUBindingUtils {
  45000. constructor( backend ) {
  45001. this.backend = backend;
  45002. this.bindGroupLayoutCache = new WeakMap();
  45003. }
  45004. createBindingsLayout( bindGroup ) {
  45005. const backend = this.backend;
  45006. const device = backend.device;
  45007. const entries = [];
  45008. let index = 0;
  45009. for ( const binding of bindGroup.bindings ) {
  45010. const bindingGPU = {
  45011. binding: index ++,
  45012. visibility: binding.visibility
  45013. };
  45014. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  45015. const buffer = {}; // GPUBufferBindingLayout
  45016. if ( binding.isStorageBuffer ) {
  45017. buffer.type = binding.access;
  45018. }
  45019. bindingGPU.buffer = buffer;
  45020. } else if ( binding.isSampler ) {
  45021. const sampler = {}; // GPUSamplerBindingLayout
  45022. if ( binding.texture.isDepthTexture ) {
  45023. if ( binding.texture.compareFunction !== null ) {
  45024. sampler.type = 'comparison';
  45025. }
  45026. }
  45027. bindingGPU.sampler = sampler;
  45028. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  45029. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  45030. } else if ( binding.isSampledTexture && binding.store ) {
  45031. const format = this.backend.get( binding.texture ).texture.format;
  45032. const access = binding.access;
  45033. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  45034. } else if ( binding.isSampledTexture ) {
  45035. const texture = {}; // GPUTextureBindingLayout
  45036. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  45037. texture.multisampled = true;
  45038. }
  45039. if ( binding.texture.isDepthTexture ) {
  45040. texture.sampleType = GPUTextureSampleType.Depth;
  45041. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  45042. const type = binding.texture.type;
  45043. if ( type === IntType ) {
  45044. texture.sampleType = GPUTextureSampleType.SInt;
  45045. } else if ( type === UnsignedIntType ) {
  45046. texture.sampleType = GPUTextureSampleType.UInt;
  45047. } else if ( type === FloatType ) {
  45048. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  45049. texture.sampleType = GPUTextureSampleType.Float;
  45050. } else {
  45051. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  45052. }
  45053. }
  45054. }
  45055. if ( binding.isSampledCubeTexture ) {
  45056. texture.viewDimension = GPUTextureViewDimension.Cube;
  45057. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45058. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  45059. } else if ( binding.isSampledTexture3D ) {
  45060. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  45061. }
  45062. bindingGPU.texture = texture;
  45063. } else {
  45064. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  45065. }
  45066. entries.push( bindingGPU );
  45067. }
  45068. return device.createBindGroupLayout( { entries } );
  45069. }
  45070. createBindings( bindGroup ) {
  45071. const { backend, bindGroupLayoutCache } = this;
  45072. const bindingsData = backend.get( bindGroup );
  45073. // setup (static) binding layout and (dynamic) binding group
  45074. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  45075. if ( bindLayoutGPU === undefined ) {
  45076. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  45077. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  45078. }
  45079. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  45080. bindingsData.layout = bindLayoutGPU;
  45081. bindingsData.group = bindGroupGPU;
  45082. }
  45083. updateBinding( binding ) {
  45084. const backend = this.backend;
  45085. const device = backend.device;
  45086. const buffer = binding.buffer;
  45087. const bufferGPU = backend.get( binding ).buffer;
  45088. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  45089. }
  45090. createBindGroup( bindGroup, layoutGPU ) {
  45091. const backend = this.backend;
  45092. const device = backend.device;
  45093. let bindingPoint = 0;
  45094. const entriesGPU = [];
  45095. for ( const binding of bindGroup.bindings ) {
  45096. if ( binding.isUniformBuffer ) {
  45097. const bindingData = backend.get( binding );
  45098. if ( bindingData.buffer === undefined ) {
  45099. const byteLength = binding.byteLength;
  45100. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  45101. const bufferGPU = device.createBuffer( {
  45102. label: 'bindingBuffer_' + binding.name,
  45103. size: byteLength,
  45104. usage: usage
  45105. } );
  45106. bindingData.buffer = bufferGPU;
  45107. }
  45108. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45109. } else if ( binding.isStorageBuffer ) {
  45110. const bindingData = backend.get( binding );
  45111. if ( bindingData.buffer === undefined ) {
  45112. const attribute = binding.attribute;
  45113. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  45114. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  45115. bindingData.buffer = backend.get( attribute ).buffer;
  45116. }
  45117. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45118. } else if ( binding.isSampler ) {
  45119. const textureGPU = backend.get( binding.texture );
  45120. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  45121. } else if ( binding.isSampledTexture ) {
  45122. const textureData = backend.get( binding.texture );
  45123. let resourceGPU;
  45124. if ( textureData.externalTexture !== undefined ) {
  45125. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  45126. } else {
  45127. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  45128. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  45129. resourceGPU = textureData[ propertyName ];
  45130. if ( resourceGPU === undefined ) {
  45131. const aspectGPU = GPUTextureAspect.All;
  45132. let dimensionViewGPU;
  45133. if ( binding.isSampledCubeTexture ) {
  45134. dimensionViewGPU = GPUTextureViewDimension.Cube;
  45135. } else if ( binding.isSampledTexture3D ) {
  45136. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  45137. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45138. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  45139. } else {
  45140. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  45141. }
  45142. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  45143. }
  45144. }
  45145. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  45146. }
  45147. bindingPoint ++;
  45148. }
  45149. return device.createBindGroup( {
  45150. label: 'bindGroup_' + bindGroup.name,
  45151. layout: layoutGPU,
  45152. entries: entriesGPU
  45153. } );
  45154. }
  45155. }
  45156. class WebGPUPipelineUtils {
  45157. constructor( backend ) {
  45158. this.backend = backend;
  45159. }
  45160. _getSampleCount( renderObjectContext ) {
  45161. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  45162. }
  45163. createRenderPipeline( renderObject, promises ) {
  45164. const { object, material, geometry, pipeline } = renderObject;
  45165. const { vertexProgram, fragmentProgram } = pipeline;
  45166. const backend = this.backend;
  45167. const device = backend.device;
  45168. const utils = backend.utils;
  45169. const pipelineData = backend.get( pipeline );
  45170. // bind group layouts
  45171. const bindGroupLayouts = [];
  45172. for ( const bindGroup of renderObject.getBindings() ) {
  45173. const bindingsData = backend.get( bindGroup );
  45174. bindGroupLayouts.push( bindingsData.layout );
  45175. }
  45176. // vertex buffers
  45177. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  45178. // blending
  45179. let blending;
  45180. if ( material.transparent === true && material.blending !== NoBlending ) {
  45181. blending = this._getBlending( material );
  45182. }
  45183. // stencil
  45184. let stencilFront = {};
  45185. if ( material.stencilWrite === true ) {
  45186. stencilFront = {
  45187. compare: this._getStencilCompare( material ),
  45188. failOp: this._getStencilOperation( material.stencilFail ),
  45189. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  45190. passOp: this._getStencilOperation( material.stencilZPass )
  45191. };
  45192. }
  45193. const colorWriteMask = this._getColorWriteMask( material );
  45194. const targets = [];
  45195. if ( renderObject.context.textures !== null ) {
  45196. const textures = renderObject.context.textures;
  45197. for ( let i = 0; i < textures.length; i ++ ) {
  45198. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  45199. targets.push( {
  45200. format: colorFormat,
  45201. blend: blending,
  45202. writeMask: colorWriteMask
  45203. } );
  45204. }
  45205. } else {
  45206. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45207. targets.push( {
  45208. format: colorFormat,
  45209. blend: blending,
  45210. writeMask: colorWriteMask
  45211. } );
  45212. }
  45213. const vertexModule = backend.get( vertexProgram ).module;
  45214. const fragmentModule = backend.get( fragmentProgram ).module;
  45215. const primitiveState = this._getPrimitiveState( object, geometry, material );
  45216. const depthCompare = this._getDepthCompare( material );
  45217. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45218. const sampleCount = this._getSampleCount( renderObject.context );
  45219. const pipelineDescriptor = {
  45220. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  45221. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  45222. fragment: Object.assign( {}, fragmentModule, { targets } ),
  45223. primitive: primitiveState,
  45224. depthStencil: {
  45225. format: depthStencilFormat,
  45226. depthWriteEnabled: material.depthWrite,
  45227. depthCompare: depthCompare,
  45228. stencilFront: stencilFront,
  45229. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  45230. stencilReadMask: material.stencilFuncMask,
  45231. stencilWriteMask: material.stencilWriteMask
  45232. },
  45233. multisample: {
  45234. count: sampleCount,
  45235. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  45236. },
  45237. layout: device.createPipelineLayout( {
  45238. bindGroupLayouts
  45239. } )
  45240. };
  45241. if ( promises === null ) {
  45242. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  45243. } else {
  45244. const p = new Promise( ( resolve /*, reject*/ ) => {
  45245. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  45246. pipelineData.pipeline = pipeline;
  45247. resolve();
  45248. } );
  45249. } );
  45250. promises.push( p );
  45251. }
  45252. }
  45253. createBundleEncoder( renderContext ) {
  45254. const backend = this.backend;
  45255. const { utils, device } = backend;
  45256. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  45257. const colorFormat = utils.getCurrentColorFormat( renderContext );
  45258. const sampleCount = this._getSampleCount( renderContext );
  45259. const descriptor = {
  45260. label: 'renderBundleEncoder',
  45261. colorFormats: [ colorFormat ],
  45262. depthStencilFormat,
  45263. sampleCount
  45264. };
  45265. return device.createRenderBundleEncoder( descriptor );
  45266. }
  45267. createComputePipeline( pipeline, bindings ) {
  45268. const backend = this.backend;
  45269. const device = backend.device;
  45270. const computeProgram = backend.get( pipeline.computeProgram ).module;
  45271. const pipelineGPU = backend.get( pipeline );
  45272. // bind group layouts
  45273. const bindGroupLayouts = [];
  45274. for ( const bindingsGroup of bindings ) {
  45275. const bindingsData = backend.get( bindingsGroup );
  45276. bindGroupLayouts.push( bindingsData.layout );
  45277. }
  45278. pipelineGPU.pipeline = device.createComputePipeline( {
  45279. compute: computeProgram,
  45280. layout: device.createPipelineLayout( {
  45281. bindGroupLayouts
  45282. } )
  45283. } );
  45284. }
  45285. _getBlending( material ) {
  45286. let color, alpha;
  45287. const blending = material.blending;
  45288. const blendSrc = material.blendSrc;
  45289. const blendDst = material.blendDst;
  45290. const blendEquation = material.blendEquation;
  45291. if ( blending === CustomBlending ) {
  45292. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  45293. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  45294. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  45295. color = {
  45296. srcFactor: this._getBlendFactor( blendSrc ),
  45297. dstFactor: this._getBlendFactor( blendDst ),
  45298. operation: this._getBlendOperation( blendEquation )
  45299. };
  45300. alpha = {
  45301. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  45302. dstFactor: this._getBlendFactor( blendDstAlpha ),
  45303. operation: this._getBlendOperation( blendEquationAlpha )
  45304. };
  45305. } else {
  45306. const premultipliedAlpha = material.premultipliedAlpha;
  45307. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  45308. color = {
  45309. srcFactor: srcRGB,
  45310. dstFactor: dstRGB,
  45311. operation: GPUBlendOperation.Add
  45312. };
  45313. alpha = {
  45314. srcFactor: srcAlpha,
  45315. dstFactor: dstAlpha,
  45316. operation: GPUBlendOperation.Add
  45317. };
  45318. };
  45319. if ( premultipliedAlpha ) {
  45320. switch ( blending ) {
  45321. case NormalBlending:
  45322. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45323. break;
  45324. case AdditiveBlending:
  45325. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  45326. break;
  45327. case SubtractiveBlending:
  45328. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45329. break;
  45330. case MultiplyBlending:
  45331. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  45332. break;
  45333. }
  45334. } else {
  45335. switch ( blending ) {
  45336. case NormalBlending:
  45337. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45338. break;
  45339. case AdditiveBlending:
  45340. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  45341. break;
  45342. case SubtractiveBlending:
  45343. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45344. break;
  45345. case MultiplyBlending:
  45346. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  45347. break;
  45348. }
  45349. }
  45350. }
  45351. if ( color !== undefined && alpha !== undefined ) {
  45352. return { color, alpha };
  45353. } else {
  45354. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  45355. }
  45356. }
  45357. _getBlendFactor( blend ) {
  45358. let blendFactor;
  45359. switch ( blend ) {
  45360. case ZeroFactor:
  45361. blendFactor = GPUBlendFactor.Zero;
  45362. break;
  45363. case OneFactor:
  45364. blendFactor = GPUBlendFactor.One;
  45365. break;
  45366. case SrcColorFactor:
  45367. blendFactor = GPUBlendFactor.Src;
  45368. break;
  45369. case OneMinusSrcColorFactor:
  45370. blendFactor = GPUBlendFactor.OneMinusSrc;
  45371. break;
  45372. case SrcAlphaFactor:
  45373. blendFactor = GPUBlendFactor.SrcAlpha;
  45374. break;
  45375. case OneMinusSrcAlphaFactor:
  45376. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  45377. break;
  45378. case DstColorFactor:
  45379. blendFactor = GPUBlendFactor.Dst;
  45380. break;
  45381. case OneMinusDstColorFactor:
  45382. blendFactor = GPUBlendFactor.OneMinusDstColor;
  45383. break;
  45384. case DstAlphaFactor:
  45385. blendFactor = GPUBlendFactor.DstAlpha;
  45386. break;
  45387. case OneMinusDstAlphaFactor:
  45388. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  45389. break;
  45390. case SrcAlphaSaturateFactor:
  45391. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  45392. break;
  45393. case BlendColorFactor:
  45394. blendFactor = GPUBlendFactor.Constant;
  45395. break;
  45396. case OneMinusBlendColorFactor:
  45397. blendFactor = GPUBlendFactor.OneMinusConstant;
  45398. break;
  45399. default:
  45400. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  45401. }
  45402. return blendFactor;
  45403. }
  45404. _getStencilCompare( material ) {
  45405. let stencilCompare;
  45406. const stencilFunc = material.stencilFunc;
  45407. switch ( stencilFunc ) {
  45408. case NeverStencilFunc:
  45409. stencilCompare = GPUCompareFunction.Never;
  45410. break;
  45411. case AlwaysStencilFunc:
  45412. stencilCompare = GPUCompareFunction.Always;
  45413. break;
  45414. case LessStencilFunc:
  45415. stencilCompare = GPUCompareFunction.Less;
  45416. break;
  45417. case LessEqualStencilFunc:
  45418. stencilCompare = GPUCompareFunction.LessEqual;
  45419. break;
  45420. case EqualStencilFunc:
  45421. stencilCompare = GPUCompareFunction.Equal;
  45422. break;
  45423. case GreaterEqualStencilFunc:
  45424. stencilCompare = GPUCompareFunction.GreaterEqual;
  45425. break;
  45426. case GreaterStencilFunc:
  45427. stencilCompare = GPUCompareFunction.Greater;
  45428. break;
  45429. case NotEqualStencilFunc:
  45430. stencilCompare = GPUCompareFunction.NotEqual;
  45431. break;
  45432. default:
  45433. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  45434. }
  45435. return stencilCompare;
  45436. }
  45437. _getStencilOperation( op ) {
  45438. let stencilOperation;
  45439. switch ( op ) {
  45440. case KeepStencilOp:
  45441. stencilOperation = GPUStencilOperation.Keep;
  45442. break;
  45443. case ZeroStencilOp:
  45444. stencilOperation = GPUStencilOperation.Zero;
  45445. break;
  45446. case ReplaceStencilOp:
  45447. stencilOperation = GPUStencilOperation.Replace;
  45448. break;
  45449. case InvertStencilOp:
  45450. stencilOperation = GPUStencilOperation.Invert;
  45451. break;
  45452. case IncrementStencilOp:
  45453. stencilOperation = GPUStencilOperation.IncrementClamp;
  45454. break;
  45455. case DecrementStencilOp:
  45456. stencilOperation = GPUStencilOperation.DecrementClamp;
  45457. break;
  45458. case IncrementWrapStencilOp:
  45459. stencilOperation = GPUStencilOperation.IncrementWrap;
  45460. break;
  45461. case DecrementWrapStencilOp:
  45462. stencilOperation = GPUStencilOperation.DecrementWrap;
  45463. break;
  45464. default:
  45465. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  45466. }
  45467. return stencilOperation;
  45468. }
  45469. _getBlendOperation( blendEquation ) {
  45470. let blendOperation;
  45471. switch ( blendEquation ) {
  45472. case AddEquation:
  45473. blendOperation = GPUBlendOperation.Add;
  45474. break;
  45475. case SubtractEquation:
  45476. blendOperation = GPUBlendOperation.Subtract;
  45477. break;
  45478. case ReverseSubtractEquation:
  45479. blendOperation = GPUBlendOperation.ReverseSubtract;
  45480. break;
  45481. case MinEquation:
  45482. blendOperation = GPUBlendOperation.Min;
  45483. break;
  45484. case MaxEquation:
  45485. blendOperation = GPUBlendOperation.Max;
  45486. break;
  45487. default:
  45488. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  45489. }
  45490. return blendOperation;
  45491. }
  45492. _getPrimitiveState( object, geometry, material ) {
  45493. const descriptor = {};
  45494. const utils = this.backend.utils;
  45495. descriptor.topology = utils.getPrimitiveTopology( object, material );
  45496. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  45497. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45498. }
  45499. switch ( material.side ) {
  45500. case FrontSide:
  45501. descriptor.frontFace = GPUFrontFace.CCW;
  45502. descriptor.cullMode = GPUCullMode.Back;
  45503. break;
  45504. case BackSide:
  45505. descriptor.frontFace = GPUFrontFace.CCW;
  45506. descriptor.cullMode = GPUCullMode.Front;
  45507. break;
  45508. case DoubleSide:
  45509. descriptor.frontFace = GPUFrontFace.CCW;
  45510. descriptor.cullMode = GPUCullMode.None;
  45511. break;
  45512. default:
  45513. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  45514. break;
  45515. }
  45516. return descriptor;
  45517. }
  45518. _getColorWriteMask( material ) {
  45519. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  45520. }
  45521. _getDepthCompare( material ) {
  45522. let depthCompare;
  45523. if ( material.depthTest === false ) {
  45524. depthCompare = GPUCompareFunction.Always;
  45525. } else {
  45526. const depthFunc = material.depthFunc;
  45527. switch ( depthFunc ) {
  45528. case NeverDepth:
  45529. depthCompare = GPUCompareFunction.Never;
  45530. break;
  45531. case AlwaysDepth:
  45532. depthCompare = GPUCompareFunction.Always;
  45533. break;
  45534. case LessDepth:
  45535. depthCompare = GPUCompareFunction.Less;
  45536. break;
  45537. case LessEqualDepth:
  45538. depthCompare = GPUCompareFunction.LessEqual;
  45539. break;
  45540. case EqualDepth:
  45541. depthCompare = GPUCompareFunction.Equal;
  45542. break;
  45543. case GreaterEqualDepth:
  45544. depthCompare = GPUCompareFunction.GreaterEqual;
  45545. break;
  45546. case GreaterDepth:
  45547. depthCompare = GPUCompareFunction.Greater;
  45548. break;
  45549. case NotEqualDepth:
  45550. depthCompare = GPUCompareFunction.NotEqual;
  45551. break;
  45552. default:
  45553. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  45554. }
  45555. }
  45556. return depthCompare;
  45557. }
  45558. }
  45559. /*// debugger tools
  45560. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  45561. //*/
  45562. //
  45563. class WebGPUBackend extends Backend {
  45564. constructor( parameters = {} ) {
  45565. super( parameters );
  45566. this.isWebGPUBackend = true;
  45567. // some parameters require default values other than "undefined"
  45568. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  45569. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  45570. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45571. this.device = null;
  45572. this.context = null;
  45573. this.colorBuffer = null;
  45574. this.defaultRenderPassdescriptor = null;
  45575. this.utils = new WebGPUUtils( this );
  45576. this.attributeUtils = new WebGPUAttributeUtils( this );
  45577. this.bindingUtils = new WebGPUBindingUtils( this );
  45578. this.pipelineUtils = new WebGPUPipelineUtils( this );
  45579. this.textureUtils = new WebGPUTextureUtils( this );
  45580. this.occludedResolveCache = new Map();
  45581. }
  45582. async init( renderer ) {
  45583. await super.init( renderer );
  45584. //
  45585. const parameters = this.parameters;
  45586. // create the device if it is not passed with parameters
  45587. let device;
  45588. if ( parameters.device === undefined ) {
  45589. const adapterOptions = {
  45590. powerPreference: parameters.powerPreference
  45591. };
  45592. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  45593. if ( adapter === null ) {
  45594. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  45595. }
  45596. // feature support
  45597. const features = Object.values( GPUFeatureName );
  45598. const supportedFeatures = [];
  45599. for ( const name of features ) {
  45600. if ( adapter.features.has( name ) ) {
  45601. supportedFeatures.push( name );
  45602. }
  45603. }
  45604. const deviceDescriptor = {
  45605. requiredFeatures: supportedFeatures,
  45606. requiredLimits: parameters.requiredLimits
  45607. };
  45608. device = await adapter.requestDevice( deviceDescriptor );
  45609. } else {
  45610. device = parameters.device;
  45611. }
  45612. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  45613. this.device = device;
  45614. this.context = context;
  45615. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  45616. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  45617. this.context.configure( {
  45618. device: this.device,
  45619. format: this.utils.getPreferredCanvasFormat(),
  45620. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  45621. alphaMode: alphaMode
  45622. } );
  45623. this.updateSize();
  45624. }
  45625. get coordinateSystem() {
  45626. return WebGPUCoordinateSystem;
  45627. }
  45628. async getArrayBufferAsync( attribute ) {
  45629. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45630. }
  45631. getContext() {
  45632. return this.context;
  45633. }
  45634. _getDefaultRenderPassDescriptor() {
  45635. let descriptor = this.defaultRenderPassdescriptor;
  45636. if ( descriptor === null ) {
  45637. const renderer = this.renderer;
  45638. descriptor = {
  45639. colorAttachments: [ {
  45640. view: null
  45641. } ],
  45642. depthStencilAttachment: {
  45643. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  45644. }
  45645. };
  45646. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45647. if ( this.renderer.samples > 0 ) {
  45648. colorAttachment.view = this.colorBuffer.createView();
  45649. } else {
  45650. colorAttachment.resolveTarget = undefined;
  45651. }
  45652. this.defaultRenderPassdescriptor = descriptor;
  45653. }
  45654. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45655. if ( this.renderer.samples > 0 ) {
  45656. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  45657. } else {
  45658. colorAttachment.view = this.context.getCurrentTexture().createView();
  45659. }
  45660. return descriptor;
  45661. }
  45662. _getRenderPassDescriptor( renderContext ) {
  45663. const renderTarget = renderContext.renderTarget;
  45664. const renderTargetData = this.get( renderTarget );
  45665. let descriptors = renderTargetData.descriptors;
  45666. if ( descriptors === undefined ||
  45667. renderTargetData.width !== renderTarget.width ||
  45668. renderTargetData.height !== renderTarget.height ||
  45669. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  45670. renderTargetData.samples !== renderTarget.samples
  45671. ) {
  45672. descriptors = {};
  45673. renderTargetData.descriptors = descriptors;
  45674. // dispose
  45675. const onDispose = () => {
  45676. renderTarget.removeEventListener( 'dispose', onDispose );
  45677. this.delete( renderTarget );
  45678. };
  45679. renderTarget.addEventListener( 'dispose', onDispose );
  45680. }
  45681. const cacheKey = renderContext.getCacheKey();
  45682. let descriptor = descriptors[ cacheKey ];
  45683. if ( descriptor === undefined ) {
  45684. const textures = renderContext.textures;
  45685. const colorAttachments = [];
  45686. for ( let i = 0; i < textures.length; i ++ ) {
  45687. const textureData = this.get( textures[ i ] );
  45688. const textureView = textureData.texture.createView( {
  45689. baseMipLevel: renderContext.activeMipmapLevel,
  45690. mipLevelCount: 1,
  45691. baseArrayLayer: renderContext.activeCubeFace,
  45692. dimension: GPUTextureViewDimension.TwoD
  45693. } );
  45694. let view, resolveTarget;
  45695. if ( textureData.msaaTexture !== undefined ) {
  45696. view = textureData.msaaTexture.createView();
  45697. resolveTarget = textureView;
  45698. } else {
  45699. view = textureView;
  45700. resolveTarget = undefined;
  45701. }
  45702. colorAttachments.push( {
  45703. view,
  45704. resolveTarget,
  45705. loadOp: GPULoadOp.Load,
  45706. storeOp: GPUStoreOp.Store
  45707. } );
  45708. }
  45709. const depthTextureData = this.get( renderContext.depthTexture );
  45710. const depthStencilAttachment = {
  45711. view: depthTextureData.texture.createView()
  45712. };
  45713. descriptor = {
  45714. colorAttachments,
  45715. depthStencilAttachment
  45716. };
  45717. descriptors[ cacheKey ] = descriptor;
  45718. renderTargetData.width = renderTarget.width;
  45719. renderTargetData.height = renderTarget.height;
  45720. renderTargetData.samples = renderTarget.samples;
  45721. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  45722. }
  45723. return descriptor;
  45724. }
  45725. beginRender( renderContext ) {
  45726. const renderContextData = this.get( renderContext );
  45727. const device = this.device;
  45728. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45729. let occlusionQuerySet;
  45730. if ( occlusionQueryCount > 0 ) {
  45731. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  45732. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  45733. // Get a reference to the array of objects with queries. The renderContextData property
  45734. // can be changed by another render pass before the buffer.mapAsyc() completes.
  45735. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  45736. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  45737. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  45738. //
  45739. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  45740. renderContextData.occlusionQuerySet = occlusionQuerySet;
  45741. renderContextData.occlusionQueryIndex = 0;
  45742. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  45743. renderContextData.lastOcclusionObject = null;
  45744. }
  45745. let descriptor;
  45746. if ( renderContext.textures === null ) {
  45747. descriptor = this._getDefaultRenderPassDescriptor();
  45748. } else {
  45749. descriptor = this._getRenderPassDescriptor( renderContext );
  45750. }
  45751. this.initTimestampQuery( renderContext, descriptor );
  45752. descriptor.occlusionQuerySet = occlusionQuerySet;
  45753. const depthStencilAttachment = descriptor.depthStencilAttachment;
  45754. if ( renderContext.textures !== null ) {
  45755. const colorAttachments = descriptor.colorAttachments;
  45756. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  45757. const colorAttachment = colorAttachments[ i ];
  45758. if ( renderContext.clearColor ) {
  45759. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  45760. colorAttachment.loadOp = GPULoadOp.Clear;
  45761. colorAttachment.storeOp = GPUStoreOp.Store;
  45762. } else {
  45763. colorAttachment.loadOp = GPULoadOp.Load;
  45764. colorAttachment.storeOp = GPUStoreOp.Store;
  45765. }
  45766. }
  45767. } else {
  45768. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45769. if ( renderContext.clearColor ) {
  45770. colorAttachment.clearValue = renderContext.clearColorValue;
  45771. colorAttachment.loadOp = GPULoadOp.Clear;
  45772. colorAttachment.storeOp = GPUStoreOp.Store;
  45773. } else {
  45774. colorAttachment.loadOp = GPULoadOp.Load;
  45775. colorAttachment.storeOp = GPUStoreOp.Store;
  45776. }
  45777. }
  45778. //
  45779. if ( renderContext.depth ) {
  45780. if ( renderContext.clearDepth ) {
  45781. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  45782. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45783. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45784. } else {
  45785. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45786. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45787. }
  45788. }
  45789. if ( renderContext.stencil ) {
  45790. if ( renderContext.clearStencil ) {
  45791. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  45792. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45793. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45794. } else {
  45795. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45796. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45797. }
  45798. }
  45799. //
  45800. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  45801. const currentPass = encoder.beginRenderPass( descriptor );
  45802. //
  45803. renderContextData.descriptor = descriptor;
  45804. renderContextData.encoder = encoder;
  45805. renderContextData.currentPass = currentPass;
  45806. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45807. renderContextData.renderBundles = [];
  45808. //
  45809. if ( renderContext.viewport ) {
  45810. this.updateViewport( renderContext );
  45811. }
  45812. if ( renderContext.scissor ) {
  45813. const { x, y, width, height } = renderContext.scissorValue;
  45814. currentPass.setScissorRect( x, y, width, height );
  45815. }
  45816. }
  45817. finishRender( renderContext ) {
  45818. const renderContextData = this.get( renderContext );
  45819. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45820. if ( renderContextData.renderBundles.length > 0 ) {
  45821. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  45822. }
  45823. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  45824. renderContextData.currentPass.endOcclusionQuery();
  45825. }
  45826. renderContextData.currentPass.end();
  45827. if ( occlusionQueryCount > 0 ) {
  45828. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  45829. //
  45830. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  45831. if ( queryResolveBuffer === undefined ) {
  45832. queryResolveBuffer = this.device.createBuffer(
  45833. {
  45834. size: bufferSize,
  45835. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  45836. }
  45837. );
  45838. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  45839. }
  45840. //
  45841. const readBuffer = this.device.createBuffer(
  45842. {
  45843. size: bufferSize,
  45844. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45845. }
  45846. );
  45847. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  45848. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  45849. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  45850. renderContextData.occlusionQueryBuffer = readBuffer;
  45851. //
  45852. this.resolveOccludedAsync( renderContext );
  45853. }
  45854. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  45855. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  45856. //
  45857. if ( renderContext.textures !== null ) {
  45858. const textures = renderContext.textures;
  45859. for ( let i = 0; i < textures.length; i ++ ) {
  45860. const texture = textures[ i ];
  45861. if ( texture.generateMipmaps === true ) {
  45862. this.textureUtils.generateMipmaps( texture );
  45863. }
  45864. }
  45865. }
  45866. }
  45867. isOccluded( renderContext, object ) {
  45868. const renderContextData = this.get( renderContext );
  45869. return renderContextData.occluded && renderContextData.occluded.has( object );
  45870. }
  45871. async resolveOccludedAsync( renderContext ) {
  45872. const renderContextData = this.get( renderContext );
  45873. // handle occlusion query results
  45874. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  45875. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  45876. const occluded = new WeakSet();
  45877. renderContextData.currentOcclusionQueryObjects = null;
  45878. renderContextData.currentOcclusionQueryBuffer = null;
  45879. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  45880. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  45881. const results = new BigUint64Array( buffer );
  45882. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  45883. if ( results[ i ] !== BigInt( 0 ) ) {
  45884. occluded.add( currentOcclusionQueryObjects[ i ] );
  45885. }
  45886. }
  45887. currentOcclusionQueryBuffer.destroy();
  45888. renderContextData.occluded = occluded;
  45889. }
  45890. }
  45891. updateViewport( renderContext ) {
  45892. const { currentPass } = this.get( renderContext );
  45893. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  45894. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  45895. }
  45896. clear( color, depth, stencil, renderTargetData = null ) {
  45897. const device = this.device;
  45898. const renderer = this.renderer;
  45899. let colorAttachments = [];
  45900. let depthStencilAttachment;
  45901. let clearValue;
  45902. let supportsDepth;
  45903. let supportsStencil;
  45904. if ( color ) {
  45905. const clearColor = this.getClearColor();
  45906. if ( this.renderer.alpha === true ) {
  45907. // premultiply alpha
  45908. const a = clearColor.a;
  45909. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  45910. } else {
  45911. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  45912. }
  45913. }
  45914. if ( renderTargetData === null ) {
  45915. supportsDepth = renderer.depth;
  45916. supportsStencil = renderer.stencil;
  45917. const descriptor = this._getDefaultRenderPassDescriptor();
  45918. if ( color ) {
  45919. colorAttachments = descriptor.colorAttachments;
  45920. const colorAttachment = colorAttachments[ 0 ];
  45921. colorAttachment.clearValue = clearValue;
  45922. colorAttachment.loadOp = GPULoadOp.Clear;
  45923. colorAttachment.storeOp = GPUStoreOp.Store;
  45924. }
  45925. if ( supportsDepth || supportsStencil ) {
  45926. depthStencilAttachment = descriptor.depthStencilAttachment;
  45927. }
  45928. } else {
  45929. supportsDepth = renderTargetData.depth;
  45930. supportsStencil = renderTargetData.stencil;
  45931. if ( color ) {
  45932. for ( const texture of renderTargetData.textures ) {
  45933. const textureData = this.get( texture );
  45934. const textureView = textureData.texture.createView();
  45935. let view, resolveTarget;
  45936. if ( textureData.msaaTexture !== undefined ) {
  45937. view = textureData.msaaTexture.createView();
  45938. resolveTarget = textureView;
  45939. } else {
  45940. view = textureView;
  45941. resolveTarget = undefined;
  45942. }
  45943. colorAttachments.push( {
  45944. view,
  45945. resolveTarget,
  45946. clearValue,
  45947. loadOp: GPULoadOp.Clear,
  45948. storeOp: GPUStoreOp.Store
  45949. } );
  45950. }
  45951. }
  45952. if ( supportsDepth || supportsStencil ) {
  45953. const depthTextureData = this.get( renderTargetData.depthTexture );
  45954. depthStencilAttachment = {
  45955. view: depthTextureData.texture.createView()
  45956. };
  45957. }
  45958. }
  45959. //
  45960. if ( supportsDepth ) {
  45961. if ( depth ) {
  45962. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45963. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  45964. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45965. } else {
  45966. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45967. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45968. }
  45969. }
  45970. //
  45971. if ( supportsStencil ) {
  45972. if ( stencil ) {
  45973. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45974. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  45975. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45976. } else {
  45977. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45978. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45979. }
  45980. }
  45981. //
  45982. const encoder = device.createCommandEncoder( {} );
  45983. const currentPass = encoder.beginRenderPass( {
  45984. colorAttachments,
  45985. depthStencilAttachment
  45986. } );
  45987. currentPass.end();
  45988. device.queue.submit( [ encoder.finish() ] );
  45989. }
  45990. // compute
  45991. beginCompute( computeGroup ) {
  45992. const groupGPU = this.get( computeGroup );
  45993. const descriptor = {};
  45994. this.initTimestampQuery( computeGroup, descriptor );
  45995. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  45996. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  45997. }
  45998. compute( computeGroup, computeNode, bindings, pipeline ) {
  45999. const { passEncoderGPU } = this.get( computeGroup );
  46000. // pipeline
  46001. const pipelineGPU = this.get( pipeline ).pipeline;
  46002. passEncoderGPU.setPipeline( pipelineGPU );
  46003. // bind groups
  46004. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46005. const bindGroup = bindings[ i ];
  46006. const bindingsData = this.get( bindGroup );
  46007. passEncoderGPU.setBindGroup( i, bindingsData.group );
  46008. }
  46009. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  46010. const computeNodeData = this.get( computeNode );
  46011. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  46012. const { dispatchSize } = computeNodeData;
  46013. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  46014. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  46015. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  46016. } else {
  46017. dispatchSize.x = computeNode.dispatchCount;
  46018. }
  46019. passEncoderGPU.dispatchWorkgroups(
  46020. dispatchSize.x,
  46021. dispatchSize.y,
  46022. dispatchSize.z
  46023. );
  46024. }
  46025. finishCompute( computeGroup ) {
  46026. const groupData = this.get( computeGroup );
  46027. groupData.passEncoderGPU.end();
  46028. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  46029. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  46030. }
  46031. // render object
  46032. draw( renderObject, info ) {
  46033. const { object, context, pipeline } = renderObject;
  46034. const bindings = renderObject.getBindings();
  46035. const renderContextData = this.get( context );
  46036. const pipelineGPU = this.get( pipeline ).pipeline;
  46037. const currentSets = renderContextData.currentSets;
  46038. const passEncoderGPU = renderContextData.currentPass;
  46039. const drawParms = renderObject.getDrawParameters();
  46040. if ( drawParms === null ) return;
  46041. // pipeline
  46042. if ( currentSets.pipeline !== pipelineGPU ) {
  46043. passEncoderGPU.setPipeline( pipelineGPU );
  46044. currentSets.pipeline = pipelineGPU;
  46045. }
  46046. // bind groups
  46047. const currentBindingGroups = currentSets.bindingGroups;
  46048. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46049. const bindGroup = bindings[ i ];
  46050. const bindingsData = this.get( bindGroup );
  46051. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  46052. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  46053. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  46054. }
  46055. }
  46056. // attributes
  46057. const index = renderObject.getIndex();
  46058. const hasIndex = ( index !== null );
  46059. // index
  46060. if ( hasIndex === true ) {
  46061. if ( currentSets.index !== index ) {
  46062. const buffer = this.get( index ).buffer;
  46063. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46064. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  46065. currentSets.index = index;
  46066. }
  46067. }
  46068. // vertex buffers
  46069. const vertexBuffers = renderObject.getVertexBuffers();
  46070. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  46071. const vertexBuffer = vertexBuffers[ i ];
  46072. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  46073. const buffer = this.get( vertexBuffer ).buffer;
  46074. passEncoderGPU.setVertexBuffer( i, buffer );
  46075. currentSets.attributes[ i ] = vertexBuffer;
  46076. }
  46077. }
  46078. // occlusion queries - handle multiple consecutive draw calls for an object
  46079. if ( renderContextData.occlusionQuerySet !== undefined ) {
  46080. const lastObject = renderContextData.lastOcclusionObject;
  46081. if ( lastObject !== object ) {
  46082. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  46083. passEncoderGPU.endOcclusionQuery();
  46084. renderContextData.occlusionQueryIndex ++;
  46085. }
  46086. if ( object.occlusionTest === true ) {
  46087. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  46088. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  46089. }
  46090. renderContextData.lastOcclusionObject = object;
  46091. }
  46092. }
  46093. // draw
  46094. if ( object.isBatchedMesh === true ) {
  46095. const starts = object._multiDrawStarts;
  46096. const counts = object._multiDrawCounts;
  46097. const drawCount = object._multiDrawCount;
  46098. const drawInstances = object._multiDrawInstances;
  46099. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  46100. for ( let i = 0; i < drawCount; i ++ ) {
  46101. const count = drawInstances ? drawInstances[ i ] : 1;
  46102. const firstInstance = count > 1 ? 0 : i;
  46103. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  46104. }
  46105. } else if ( hasIndex === true ) {
  46106. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParms;
  46107. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  46108. info.update( object, indexCount, instanceCount );
  46109. } else {
  46110. const { vertexCount, instanceCount, firstVertex } = drawParms;
  46111. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  46112. info.update( object, vertexCount, instanceCount );
  46113. }
  46114. }
  46115. // cache key
  46116. needsRenderUpdate( renderObject ) {
  46117. const data = this.get( renderObject );
  46118. const { object, material } = renderObject;
  46119. const utils = this.utils;
  46120. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  46121. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  46122. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  46123. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  46124. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  46125. let needsUpdate = false;
  46126. if ( data.material !== material || data.materialVersion !== material.version ||
  46127. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  46128. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  46129. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  46130. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  46131. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  46132. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  46133. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  46134. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  46135. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  46136. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  46137. data.primitiveTopology !== primitiveTopology ||
  46138. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  46139. ) {
  46140. data.material = material; data.materialVersion = material.version;
  46141. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  46142. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  46143. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  46144. data.colorWrite = material.colorWrite;
  46145. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  46146. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  46147. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  46148. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  46149. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  46150. data.sampleCount = sampleCount;
  46151. data.colorSpace = colorSpace;
  46152. data.colorFormat = colorFormat;
  46153. data.depthStencilFormat = depthStencilFormat;
  46154. data.primitiveTopology = primitiveTopology;
  46155. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  46156. needsUpdate = true;
  46157. }
  46158. return needsUpdate;
  46159. }
  46160. getRenderCacheKey( renderObject ) {
  46161. const { object, material } = renderObject;
  46162. const utils = this.utils;
  46163. const renderContext = renderObject.context;
  46164. return [
  46165. material.transparent, material.blending, material.premultipliedAlpha,
  46166. material.blendSrc, material.blendDst, material.blendEquation,
  46167. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  46168. material.colorWrite,
  46169. material.depthWrite, material.depthTest, material.depthFunc,
  46170. material.stencilWrite, material.stencilFunc,
  46171. material.stencilFail, material.stencilZFail, material.stencilZPass,
  46172. material.stencilFuncMask, material.stencilWriteMask,
  46173. material.side,
  46174. utils.getSampleCountRenderContext( renderContext ),
  46175. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  46176. utils.getPrimitiveTopology( object, material ),
  46177. renderObject.clippingContext.cacheKey
  46178. ].join();
  46179. }
  46180. // textures
  46181. createSampler( texture ) {
  46182. this.textureUtils.createSampler( texture );
  46183. }
  46184. destroySampler( texture ) {
  46185. this.textureUtils.destroySampler( texture );
  46186. }
  46187. createDefaultTexture( texture ) {
  46188. this.textureUtils.createDefaultTexture( texture );
  46189. }
  46190. createTexture( texture, options ) {
  46191. this.textureUtils.createTexture( texture, options );
  46192. }
  46193. updateTexture( texture, options ) {
  46194. this.textureUtils.updateTexture( texture, options );
  46195. }
  46196. generateMipmaps( texture ) {
  46197. this.textureUtils.generateMipmaps( texture );
  46198. }
  46199. destroyTexture( texture ) {
  46200. this.textureUtils.destroyTexture( texture );
  46201. }
  46202. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46203. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  46204. }
  46205. initTimestampQuery( renderContext, descriptor ) {
  46206. if ( ! this.trackTimestamp ) return;
  46207. const renderContextData = this.get( renderContext );
  46208. if ( ! renderContextData.timeStampQuerySet ) {
  46209. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  46210. // beginning and one for the end of compute pass execution.
  46211. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  46212. const timestampWrites = {
  46213. querySet: timeStampQuerySet,
  46214. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  46215. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  46216. };
  46217. Object.assign( descriptor, {
  46218. timestampWrites,
  46219. } );
  46220. renderContextData.timeStampQuerySet = timeStampQuerySet;
  46221. }
  46222. }
  46223. // timestamp utils
  46224. prepareTimestampBuffer( renderContext, encoder ) {
  46225. if ( ! this.trackTimestamp ) return;
  46226. const renderContextData = this.get( renderContext );
  46227. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  46228. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  46229. renderContextData.currentTimestampQueryBuffers = {
  46230. resolveBuffer: this.device.createBuffer( {
  46231. label: 'timestamp resolve buffer',
  46232. size: size,
  46233. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  46234. } ),
  46235. resultBuffer: this.device.createBuffer( {
  46236. label: 'timestamp result buffer',
  46237. size: size,
  46238. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  46239. } ),
  46240. isMappingPending: false,
  46241. };
  46242. }
  46243. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  46244. if ( isMappingPending === true ) return;
  46245. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  46246. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  46247. }
  46248. async resolveTimestampAsync( renderContext, type = 'render' ) {
  46249. if ( ! this.trackTimestamp ) return;
  46250. const renderContextData = this.get( renderContext );
  46251. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  46252. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  46253. if ( isMappingPending === true ) return;
  46254. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  46255. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  46256. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  46257. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  46258. this.renderer.info.updateTimestamp( type, duration );
  46259. resultBuffer.unmap();
  46260. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  46261. } );
  46262. }
  46263. // node builder
  46264. createNodeBuilder( object, renderer ) {
  46265. return new WGSLNodeBuilder( object, renderer );
  46266. }
  46267. // program
  46268. createProgram( program ) {
  46269. const programGPU = this.get( program );
  46270. programGPU.module = {
  46271. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  46272. entryPoint: 'main'
  46273. };
  46274. }
  46275. destroyProgram( program ) {
  46276. this.delete( program );
  46277. }
  46278. // pipelines
  46279. createRenderPipeline( renderObject, promises ) {
  46280. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  46281. }
  46282. createComputePipeline( computePipeline, bindings ) {
  46283. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  46284. }
  46285. beginBundle( renderContext ) {
  46286. const renderContextData = this.get( renderContext );
  46287. renderContextData._currentPass = renderContextData.currentPass;
  46288. renderContextData._currentSets = renderContextData.currentSets;
  46289. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46290. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  46291. }
  46292. finishBundle( renderContext, bundle ) {
  46293. const renderContextData = this.get( renderContext );
  46294. const bundleEncoder = renderContextData.currentPass;
  46295. const bundleGPU = bundleEncoder.finish();
  46296. this.get( bundle ).bundleGPU = bundleGPU;
  46297. // restore render pass state
  46298. renderContextData.currentSets = renderContextData._currentSets;
  46299. renderContextData.currentPass = renderContextData._currentPass;
  46300. }
  46301. addBundle( renderContext, bundle ) {
  46302. const renderContextData = this.get( renderContext );
  46303. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  46304. }
  46305. // bindings
  46306. createBindings( bindGroup ) {
  46307. this.bindingUtils.createBindings( bindGroup );
  46308. }
  46309. updateBindings( bindGroup ) {
  46310. this.bindingUtils.createBindings( bindGroup );
  46311. }
  46312. updateBinding( binding ) {
  46313. this.bindingUtils.updateBinding( binding );
  46314. }
  46315. // attributes
  46316. createIndexAttribute( attribute ) {
  46317. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46318. }
  46319. createAttribute( attribute ) {
  46320. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46321. }
  46322. createStorageAttribute( attribute ) {
  46323. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46324. }
  46325. updateAttribute( attribute ) {
  46326. this.attributeUtils.updateAttribute( attribute );
  46327. }
  46328. destroyAttribute( attribute ) {
  46329. this.attributeUtils.destroyAttribute( attribute );
  46330. }
  46331. // canvas
  46332. updateSize() {
  46333. this.colorBuffer = this.textureUtils.getColorBuffer();
  46334. this.defaultRenderPassdescriptor = null;
  46335. }
  46336. // utils public
  46337. getMaxAnisotropy() {
  46338. return 16;
  46339. }
  46340. hasFeature( name ) {
  46341. return this.device.features.has( name );
  46342. }
  46343. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  46344. let dstX = 0;
  46345. let dstY = 0;
  46346. let dstLayer = 0;
  46347. let srcX = 0;
  46348. let srcY = 0;
  46349. let srcLayer = 0;
  46350. let srcWidth = srcTexture.image.width;
  46351. let srcHeight = srcTexture.image.height;
  46352. if ( srcRegion !== null ) {
  46353. srcX = srcRegion.x;
  46354. srcY = srcRegion.y;
  46355. srcLayer = srcRegion.z || 0;
  46356. srcWidth = srcRegion.width;
  46357. srcHeight = srcRegion.height;
  46358. }
  46359. if ( dstPosition !== null ) {
  46360. dstX = dstPosition.x;
  46361. dstY = dstPosition.y;
  46362. dstLayer = dstPosition.z || 0;
  46363. }
  46364. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  46365. const sourceGPU = this.get( srcTexture ).texture;
  46366. const destinationGPU = this.get( dstTexture ).texture;
  46367. encoder.copyTextureToTexture(
  46368. {
  46369. texture: sourceGPU,
  46370. mipLevel: level,
  46371. origin: { x: srcX, y: srcY, z: srcLayer }
  46372. },
  46373. {
  46374. texture: destinationGPU,
  46375. mipLevel: level,
  46376. origin: { x: dstX, y: dstY, z: dstLayer }
  46377. },
  46378. [
  46379. srcWidth,
  46380. srcHeight,
  46381. 1
  46382. ]
  46383. );
  46384. this.device.queue.submit( [ encoder.finish() ] );
  46385. }
  46386. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46387. const renderContextData = this.get( renderContext );
  46388. const { encoder, descriptor } = renderContextData;
  46389. let sourceGPU = null;
  46390. if ( renderContext.renderTarget ) {
  46391. if ( texture.isDepthTexture ) {
  46392. sourceGPU = this.get( renderContext.depthTexture ).texture;
  46393. } else {
  46394. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  46395. }
  46396. } else {
  46397. if ( texture.isDepthTexture ) {
  46398. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  46399. } else {
  46400. sourceGPU = this.context.getCurrentTexture();
  46401. }
  46402. }
  46403. const destinationGPU = this.get( texture ).texture;
  46404. if ( sourceGPU.format !== destinationGPU.format ) {
  46405. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  46406. return;
  46407. }
  46408. renderContextData.currentPass.end();
  46409. encoder.copyTextureToTexture(
  46410. {
  46411. texture: sourceGPU,
  46412. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  46413. },
  46414. {
  46415. texture: destinationGPU
  46416. },
  46417. [
  46418. rectangle.z,
  46419. rectangle.w
  46420. ]
  46421. );
  46422. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  46423. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  46424. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  46425. }
  46426. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46427. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46428. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  46429. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46430. }
  46431. }
  46432. class IESSpotLight extends SpotLight {
  46433. constructor( color, intensity, distance, angle, penumbra, decay ) {
  46434. super( color, intensity, distance, angle, penumbra, decay );
  46435. this.iesMap = null;
  46436. }
  46437. copy( source, recursive ) {
  46438. super.copy( source, recursive );
  46439. this.iesMap = source.iesMap;
  46440. return this;
  46441. }
  46442. }
  46443. class StandardNodeLibrary extends NodeLibrary {
  46444. constructor() {
  46445. super();
  46446. this.addMaterial( MeshPhongNodeMaterial, MeshPhongMaterial );
  46447. this.addMaterial( MeshStandardNodeMaterial, MeshStandardMaterial );
  46448. this.addMaterial( MeshPhysicalNodeMaterial, MeshPhysicalMaterial );
  46449. this.addMaterial( MeshToonNodeMaterial, MeshToonMaterial );
  46450. this.addMaterial( MeshBasicNodeMaterial, MeshBasicMaterial );
  46451. this.addMaterial( MeshLambertNodeMaterial, MeshLambertMaterial );
  46452. this.addMaterial( MeshNormalNodeMaterial, MeshNormalMaterial );
  46453. this.addMaterial( MeshMatcapNodeMaterial, MeshMatcapMaterial );
  46454. this.addMaterial( LineBasicNodeMaterial, LineBasicMaterial );
  46455. this.addMaterial( LineDashedNodeMaterial, LineDashedMaterial );
  46456. this.addMaterial( PointsNodeMaterial, PointsMaterial );
  46457. this.addMaterial( SpriteNodeMaterial, SpriteMaterial );
  46458. this.addMaterial( ShadowNodeMaterial, ShadowMaterial );
  46459. this.addLight( PointLightNode, PointLight );
  46460. this.addLight( DirectionalLightNode, DirectionalLight );
  46461. this.addLight( RectAreaLightNode, RectAreaLight );
  46462. this.addLight( SpotLightNode, SpotLight );
  46463. this.addLight( AmbientLightNode, AmbientLight );
  46464. this.addLight( HemisphereLightNode, HemisphereLight );
  46465. this.addLight( LightProbeNode, LightProbe );
  46466. this.addLight( IESSpotLightNode, IESSpotLight );
  46467. this.addToneMapping( linearToneMapping, LinearToneMapping );
  46468. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  46469. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  46470. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  46471. this.addToneMapping( agxToneMapping, AgXToneMapping );
  46472. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  46473. this.addColorSpace( linearSRGBTosRGB, getColorSpaceMethod( LinearSRGBColorSpace, SRGBColorSpace ) );
  46474. this.addColorSpace( sRGBToLinearSRGB, getColorSpaceMethod( SRGBColorSpace, LinearSRGBColorSpace ) );
  46475. }
  46476. }
  46477. /*
  46478. const debugHandler = {
  46479. get: function ( target, name ) {
  46480. // Add |update
  46481. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  46482. return target[ name ];
  46483. }
  46484. };
  46485. */
  46486. class WebGPURenderer extends Renderer {
  46487. constructor( parameters = {} ) {
  46488. let BackendClass;
  46489. if ( parameters.forceWebGL ) {
  46490. BackendClass = WebGLBackend;
  46491. } else {
  46492. BackendClass = WebGPUBackend;
  46493. parameters.getFallback = () => {
  46494. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  46495. return new WebGLBackend( parameters );
  46496. };
  46497. }
  46498. const backend = new BackendClass( parameters );
  46499. //super( new Proxy( backend, debugHandler ) );
  46500. super( backend, parameters );
  46501. this.nodes.library = new StandardNodeLibrary();
  46502. this.isWebGPURenderer = true;
  46503. }
  46504. }
  46505. class BundleGroup extends Group {
  46506. constructor() {
  46507. super();
  46508. this.isBundleGroup = true;
  46509. this.type = 'BundleGroup';
  46510. this.static = true;
  46511. this.version = 0;
  46512. }
  46513. set needsUpdate( value ) {
  46514. if ( value === true ) this.version ++;
  46515. }
  46516. }
  46517. const _material = /*@__PURE__*/ new NodeMaterial();
  46518. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  46519. class PostProcessing {
  46520. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  46521. this.renderer = renderer;
  46522. this.outputNode = outputNode;
  46523. this.outputColorTransform = true;
  46524. this.needsUpdate = true;
  46525. _material.name = 'PostProcessing';
  46526. }
  46527. render() {
  46528. this.update();
  46529. const renderer = this.renderer;
  46530. const toneMapping = renderer.toneMapping;
  46531. const outputColorSpace = renderer.outputColorSpace;
  46532. renderer.toneMapping = NoToneMapping;
  46533. renderer.outputColorSpace = LinearSRGBColorSpace;
  46534. //
  46535. _quadMesh.render( renderer );
  46536. //
  46537. renderer.toneMapping = toneMapping;
  46538. renderer.outputColorSpace = outputColorSpace;
  46539. }
  46540. update() {
  46541. if ( this.needsUpdate === true ) {
  46542. const renderer = this.renderer;
  46543. const toneMapping = renderer.toneMapping;
  46544. const outputColorSpace = renderer.outputColorSpace;
  46545. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  46546. _quadMesh.material.needsUpdate = true;
  46547. this.needsUpdate = false;
  46548. }
  46549. }
  46550. async renderAsync() {
  46551. this.update();
  46552. const renderer = this.renderer;
  46553. const toneMapping = renderer.toneMapping;
  46554. const outputColorSpace = renderer.outputColorSpace;
  46555. renderer.toneMapping = NoToneMapping;
  46556. renderer.outputColorSpace = LinearSRGBColorSpace;
  46557. //
  46558. await _quadMesh.renderAsync( renderer );
  46559. //
  46560. renderer.toneMapping = toneMapping;
  46561. renderer.outputColorSpace = outputColorSpace;
  46562. }
  46563. }
  46564. class StorageTexture extends Texture {
  46565. constructor( width = 1, height = 1 ) {
  46566. super();
  46567. this.image = { width, height };
  46568. this.magFilter = LinearFilter;
  46569. this.minFilter = LinearFilter;
  46570. this.isStorageTexture = true;
  46571. }
  46572. }
  46573. class StorageBufferAttribute extends BufferAttribute {
  46574. constructor( array, itemSize, typeClass = Float32Array ) {
  46575. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  46576. super( array, itemSize );
  46577. this.isStorageBufferAttribute = true;
  46578. }
  46579. }
  46580. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  46581. constructor( array, itemSize, typeClass = Float32Array ) {
  46582. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  46583. super( array, itemSize );
  46584. this.isStorageInstancedBufferAttribute = true;
  46585. }
  46586. }
  46587. class NodeLoader extends Loader {
  46588. constructor( manager ) {
  46589. super( manager );
  46590. this.textures = {};
  46591. this.nodes = {};
  46592. }
  46593. load( url, onLoad, onProgress, onError ) {
  46594. const loader = new FileLoader( this.manager );
  46595. loader.setPath( this.path );
  46596. loader.setRequestHeader( this.requestHeader );
  46597. loader.setWithCredentials( this.withCredentials );
  46598. loader.load( url, ( text ) => {
  46599. try {
  46600. onLoad( this.parse( JSON.parse( text ) ) );
  46601. } catch ( e ) {
  46602. if ( onError ) {
  46603. onError( e );
  46604. } else {
  46605. console.error( e );
  46606. }
  46607. this.manager.itemError( url );
  46608. }
  46609. }, onProgress, onError );
  46610. }
  46611. parseNodes( json ) {
  46612. const nodes = {};
  46613. if ( json !== undefined ) {
  46614. for ( const nodeJSON of json ) {
  46615. const { uuid, type } = nodeJSON;
  46616. nodes[ uuid ] = this.createNodeFromType( type );
  46617. nodes[ uuid ].uuid = uuid;
  46618. }
  46619. const meta = { nodes, textures: this.textures };
  46620. for ( const nodeJSON of json ) {
  46621. nodeJSON.meta = meta;
  46622. const node = nodes[ nodeJSON.uuid ];
  46623. node.deserialize( nodeJSON );
  46624. delete nodeJSON.meta;
  46625. }
  46626. }
  46627. return nodes;
  46628. }
  46629. parse( json ) {
  46630. const node = this.createNodeFromType( json.type );
  46631. node.uuid = json.uuid;
  46632. const nodes = this.parseNodes( json.nodes );
  46633. const meta = { nodes, textures: this.textures };
  46634. json.meta = meta;
  46635. node.deserialize( json );
  46636. delete json.meta;
  46637. return node;
  46638. }
  46639. setTextures( value ) {
  46640. this.textures = value;
  46641. return this;
  46642. }
  46643. setNodes( value ) {
  46644. this.nodes = value;
  46645. return this;
  46646. }
  46647. createNodeFromType( type ) {
  46648. if ( this.nodes[ type ] === undefined ) {
  46649. console.error( 'THREE.NodeLoader: Node type not found:', type );
  46650. return float();
  46651. }
  46652. return nodeObject( new this.nodes[ type ]() );
  46653. }
  46654. }
  46655. class NodeMaterialLoader extends MaterialLoader {
  46656. constructor( manager ) {
  46657. super( manager );
  46658. this.nodes = {};
  46659. this.nodeMaterials = {};
  46660. }
  46661. parse( json ) {
  46662. const material = super.parse( json );
  46663. const nodes = this.nodes;
  46664. const inputNodes = json.inputNodes;
  46665. for ( const property in inputNodes ) {
  46666. const uuid = inputNodes[ property ];
  46667. material[ property ] = nodes[ uuid ];
  46668. }
  46669. return material;
  46670. }
  46671. setNodes( value ) {
  46672. this.nodes = value;
  46673. return this;
  46674. }
  46675. setNodeMaterials( value ) {
  46676. this.nodeMaterials = value;
  46677. return this;
  46678. }
  46679. createMaterialFromType( type ) {
  46680. const materialClass = this.nodeMaterials[ type ];
  46681. if ( materialClass !== undefined ) {
  46682. return new materialClass();
  46683. }
  46684. return super.createMaterialFromType( type );
  46685. }
  46686. }
  46687. class NodeObjectLoader extends ObjectLoader {
  46688. constructor( manager ) {
  46689. super( manager );
  46690. this.nodes = {};
  46691. this.nodeMaterials = {};
  46692. this._nodesJSON = null;
  46693. }
  46694. setNodes( value ) {
  46695. this.nodes = value;
  46696. return this;
  46697. }
  46698. setNodeMaterials( value ) {
  46699. this.nodeMaterials = value;
  46700. return this;
  46701. }
  46702. parse( json, onLoad ) {
  46703. this._nodesJSON = json.nodes;
  46704. const data = super.parse( json, onLoad );
  46705. this._nodesJSON = null; // dispose
  46706. return data;
  46707. }
  46708. parseNodes( json, textures ) {
  46709. if ( json !== undefined ) {
  46710. const loader = new NodeLoader();
  46711. loader.setNodes( this.nodes );
  46712. loader.setTextures( textures );
  46713. return loader.parseNodes( json );
  46714. }
  46715. return {};
  46716. }
  46717. parseMaterials( json, textures ) {
  46718. const materials = {};
  46719. if ( json !== undefined ) {
  46720. const nodes = this.parseNodes( this._nodesJSON, textures );
  46721. const loader = new NodeMaterialLoader();
  46722. loader.setTextures( textures );
  46723. loader.setNodes( nodes );
  46724. loader.setNodeMaterials( this.nodeMaterials );
  46725. for ( let i = 0, l = json.length; i < l; i ++ ) {
  46726. const data = json[ i ];
  46727. materials[ data.uuid ] = loader.parse( data );
  46728. }
  46729. }
  46730. return materials;
  46731. }
  46732. }
  46733. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  46734. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  46735. revision: REVISION,
  46736. } } ) );
  46737. }
  46738. if ( typeof window !== 'undefined' ) {
  46739. if ( window.__THREE__ ) {
  46740. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  46741. } else {
  46742. window.__THREE__ = REVISION;
  46743. }
  46744. }
  46745. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnaglyphPassNode, AnalyticLightNode, AnamorphicNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, BloomNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DenoiseNode, DepthFormat, DepthOfFieldNode, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DotScreenNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, FXAANode, F_Schlick, FileLoader, FilmNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GTAONode, GaussianBlurNode, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, Lut3DNode, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParallaxBarrierPassNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, PixelationPassNode, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, 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, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGBShiftNode, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, SSAAPassNode, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, SobelOperatorNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StereoPassNode, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, TimerNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, TransitionNode, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, afterImage, agxToneMapping, all, alphaT, anaglyphPass, anamorphic, and, anisotropy, anisotropyB, anisotropyT, any, ao, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bleach, bloom, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, denoise, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, dispersion, distance, div, dodge, dof, dot, dotScreen, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, film, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, fxaa, gain, gapSize, gaussianBlur, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getShIrradianceAt, getTextureIndex, global, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, localId, log, log2, loop, luminance, lut3D, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, motionBlur, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxBarrierPass, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToViewZ, pixelationPass, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rgbShift, rotate, rotateUV, roughness, round, rtt, sRGBToLinearSRGB, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, sepia, setCurrentStack, shaderStages, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, sobel, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, ssaaPass, stack, step, stereoPass, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transition, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor };
粤ICP备19079148号