three.webgpu.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '168';
  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. class Triangle {
  4899. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4900. this.a = a;
  4901. this.b = b;
  4902. this.c = c;
  4903. }
  4904. static getNormal( a, b, c, target ) {
  4905. target.subVectors( c, b );
  4906. _v0$1.subVectors( a, b );
  4907. target.cross( _v0$1 );
  4908. const targetLengthSq = target.lengthSq();
  4909. if ( targetLengthSq > 0 ) {
  4910. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4911. }
  4912. return target.set( 0, 0, 0 );
  4913. }
  4914. // static/instance method to calculate barycentric coordinates
  4915. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4916. static getBarycoord( point, a, b, c, target ) {
  4917. _v0$1.subVectors( c, a );
  4918. _v1$3.subVectors( b, a );
  4919. _v2$2.subVectors( point, a );
  4920. const dot00 = _v0$1.dot( _v0$1 );
  4921. const dot01 = _v0$1.dot( _v1$3 );
  4922. const dot02 = _v0$1.dot( _v2$2 );
  4923. const dot11 = _v1$3.dot( _v1$3 );
  4924. const dot12 = _v1$3.dot( _v2$2 );
  4925. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4926. // collinear or singular triangle
  4927. if ( denom === 0 ) {
  4928. target.set( 0, 0, 0 );
  4929. return null;
  4930. }
  4931. const invDenom = 1 / denom;
  4932. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4933. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4934. // barycentric coordinates must always sum to 1
  4935. return target.set( 1 - u - v, v, u );
  4936. }
  4937. static containsPoint( point, a, b, c ) {
  4938. // if the triangle is degenerate then we can't contain a point
  4939. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4940. return false;
  4941. }
  4942. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4943. }
  4944. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4945. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4946. target.x = 0;
  4947. target.y = 0;
  4948. if ( 'z' in target ) target.z = 0;
  4949. if ( 'w' in target ) target.w = 0;
  4950. return null;
  4951. }
  4952. target.setScalar( 0 );
  4953. target.addScaledVector( v1, _v3$2.x );
  4954. target.addScaledVector( v2, _v3$2.y );
  4955. target.addScaledVector( v3, _v3$2.z );
  4956. return target;
  4957. }
  4958. static isFrontFacing( a, b, c, direction ) {
  4959. _v0$1.subVectors( c, b );
  4960. _v1$3.subVectors( a, b );
  4961. // strictly front facing
  4962. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4963. }
  4964. set( a, b, c ) {
  4965. this.a.copy( a );
  4966. this.b.copy( b );
  4967. this.c.copy( c );
  4968. return this;
  4969. }
  4970. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4971. this.a.copy( points[ i0 ] );
  4972. this.b.copy( points[ i1 ] );
  4973. this.c.copy( points[ i2 ] );
  4974. return this;
  4975. }
  4976. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4977. this.a.fromBufferAttribute( attribute, i0 );
  4978. this.b.fromBufferAttribute( attribute, i1 );
  4979. this.c.fromBufferAttribute( attribute, i2 );
  4980. return this;
  4981. }
  4982. clone() {
  4983. return new this.constructor().copy( this );
  4984. }
  4985. copy( triangle ) {
  4986. this.a.copy( triangle.a );
  4987. this.b.copy( triangle.b );
  4988. this.c.copy( triangle.c );
  4989. return this;
  4990. }
  4991. getArea() {
  4992. _v0$1.subVectors( this.c, this.b );
  4993. _v1$3.subVectors( this.a, this.b );
  4994. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4995. }
  4996. getMidpoint( target ) {
  4997. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4998. }
  4999. getNormal( target ) {
  5000. return Triangle.getNormal( this.a, this.b, this.c, target );
  5001. }
  5002. getPlane( target ) {
  5003. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5004. }
  5005. getBarycoord( point, target ) {
  5006. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5007. }
  5008. getInterpolation( point, v1, v2, v3, target ) {
  5009. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5010. }
  5011. containsPoint( point ) {
  5012. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5013. }
  5014. isFrontFacing( direction ) {
  5015. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5016. }
  5017. intersectsBox( box ) {
  5018. return box.intersectsTriangle( this );
  5019. }
  5020. closestPointToPoint( p, target ) {
  5021. const a = this.a, b = this.b, c = this.c;
  5022. let v, w;
  5023. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5024. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5025. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5026. // basically, we're distinguishing which of the voronoi regions of the triangle
  5027. // the point lies in with the minimum amount of redundant computation.
  5028. _vab.subVectors( b, a );
  5029. _vac.subVectors( c, a );
  5030. _vap.subVectors( p, a );
  5031. const d1 = _vab.dot( _vap );
  5032. const d2 = _vac.dot( _vap );
  5033. if ( d1 <= 0 && d2 <= 0 ) {
  5034. // vertex region of A; barycentric coords (1, 0, 0)
  5035. return target.copy( a );
  5036. }
  5037. _vbp.subVectors( p, b );
  5038. const d3 = _vab.dot( _vbp );
  5039. const d4 = _vac.dot( _vbp );
  5040. if ( d3 >= 0 && d4 <= d3 ) {
  5041. // vertex region of B; barycentric coords (0, 1, 0)
  5042. return target.copy( b );
  5043. }
  5044. const vc = d1 * d4 - d3 * d2;
  5045. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5046. v = d1 / ( d1 - d3 );
  5047. // edge region of AB; barycentric coords (1-v, v, 0)
  5048. return target.copy( a ).addScaledVector( _vab, v );
  5049. }
  5050. _vcp.subVectors( p, c );
  5051. const d5 = _vab.dot( _vcp );
  5052. const d6 = _vac.dot( _vcp );
  5053. if ( d6 >= 0 && d5 <= d6 ) {
  5054. // vertex region of C; barycentric coords (0, 0, 1)
  5055. return target.copy( c );
  5056. }
  5057. const vb = d5 * d2 - d1 * d6;
  5058. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5059. w = d2 / ( d2 - d6 );
  5060. // edge region of AC; barycentric coords (1-w, 0, w)
  5061. return target.copy( a ).addScaledVector( _vac, w );
  5062. }
  5063. const va = d3 * d6 - d5 * d4;
  5064. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5065. _vbc.subVectors( c, b );
  5066. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5067. // edge region of BC; barycentric coords (0, 1-w, w)
  5068. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5069. }
  5070. // face region
  5071. const denom = 1 / ( va + vb + vc );
  5072. // u = va * denom
  5073. v = vb * denom;
  5074. w = vc * denom;
  5075. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5076. }
  5077. equals( triangle ) {
  5078. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5079. }
  5080. }
  5081. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5082. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5083. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5084. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5085. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5086. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5087. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5088. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5089. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5090. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5091. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5092. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5093. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5094. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5095. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5096. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5097. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5098. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5099. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5100. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5101. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5102. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5103. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5104. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5105. const _hslA = { h: 0, s: 0, l: 0 };
  5106. const _hslB = { h: 0, s: 0, l: 0 };
  5107. function hue2rgb( p, q, t ) {
  5108. if ( t < 0 ) t += 1;
  5109. if ( t > 1 ) t -= 1;
  5110. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5111. if ( t < 1 / 2 ) return q;
  5112. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5113. return p;
  5114. }
  5115. class Color {
  5116. constructor( r, g, b ) {
  5117. this.isColor = true;
  5118. this.r = 1;
  5119. this.g = 1;
  5120. this.b = 1;
  5121. return this.set( r, g, b );
  5122. }
  5123. set( r, g, b ) {
  5124. if ( g === undefined && b === undefined ) {
  5125. // r is THREE.Color, hex or string
  5126. const value = r;
  5127. if ( value && value.isColor ) {
  5128. this.copy( value );
  5129. } else if ( typeof value === 'number' ) {
  5130. this.setHex( value );
  5131. } else if ( typeof value === 'string' ) {
  5132. this.setStyle( value );
  5133. }
  5134. } else {
  5135. this.setRGB( r, g, b );
  5136. }
  5137. return this;
  5138. }
  5139. setScalar( scalar ) {
  5140. this.r = scalar;
  5141. this.g = scalar;
  5142. this.b = scalar;
  5143. return this;
  5144. }
  5145. setHex( hex, colorSpace = SRGBColorSpace ) {
  5146. hex = Math.floor( hex );
  5147. this.r = ( hex >> 16 & 255 ) / 255;
  5148. this.g = ( hex >> 8 & 255 ) / 255;
  5149. this.b = ( hex & 255 ) / 255;
  5150. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5151. return this;
  5152. }
  5153. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5154. this.r = r;
  5155. this.g = g;
  5156. this.b = b;
  5157. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5158. return this;
  5159. }
  5160. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5161. // h,s,l ranges are in 0.0 - 1.0
  5162. h = euclideanModulo( h, 1 );
  5163. s = clamp$1( s, 0, 1 );
  5164. l = clamp$1( l, 0, 1 );
  5165. if ( s === 0 ) {
  5166. this.r = this.g = this.b = l;
  5167. } else {
  5168. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5169. const q = ( 2 * l ) - p;
  5170. this.r = hue2rgb( q, p, h + 1 / 3 );
  5171. this.g = hue2rgb( q, p, h );
  5172. this.b = hue2rgb( q, p, h - 1 / 3 );
  5173. }
  5174. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5175. return this;
  5176. }
  5177. setStyle( style, colorSpace = SRGBColorSpace ) {
  5178. function handleAlpha( string ) {
  5179. if ( string === undefined ) return;
  5180. if ( parseFloat( string ) < 1 ) {
  5181. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5182. }
  5183. }
  5184. let m;
  5185. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5186. // rgb / hsl
  5187. let color;
  5188. const name = m[ 1 ];
  5189. const components = m[ 2 ];
  5190. switch ( name ) {
  5191. case 'rgb':
  5192. case 'rgba':
  5193. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5194. // rgb(255,0,0) rgba(255,0,0,0.5)
  5195. handleAlpha( color[ 4 ] );
  5196. return this.setRGB(
  5197. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5198. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5199. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5200. colorSpace
  5201. );
  5202. }
  5203. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5204. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5205. handleAlpha( color[ 4 ] );
  5206. return this.setRGB(
  5207. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5208. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5209. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5210. colorSpace
  5211. );
  5212. }
  5213. break;
  5214. case 'hsl':
  5215. case 'hsla':
  5216. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5217. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5218. handleAlpha( color[ 4 ] );
  5219. return this.setHSL(
  5220. parseFloat( color[ 1 ] ) / 360,
  5221. parseFloat( color[ 2 ] ) / 100,
  5222. parseFloat( color[ 3 ] ) / 100,
  5223. colorSpace
  5224. );
  5225. }
  5226. break;
  5227. default:
  5228. console.warn( 'THREE.Color: Unknown color model ' + style );
  5229. }
  5230. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5231. // hex color
  5232. const hex = m[ 1 ];
  5233. const size = hex.length;
  5234. if ( size === 3 ) {
  5235. // #ff0
  5236. return this.setRGB(
  5237. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5238. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5239. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5240. colorSpace
  5241. );
  5242. } else if ( size === 6 ) {
  5243. // #ff0000
  5244. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5245. } else {
  5246. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5247. }
  5248. } else if ( style && style.length > 0 ) {
  5249. return this.setColorName( style, colorSpace );
  5250. }
  5251. return this;
  5252. }
  5253. setColorName( style, colorSpace = SRGBColorSpace ) {
  5254. // color keywords
  5255. const hex = _colorKeywords[ style.toLowerCase() ];
  5256. if ( hex !== undefined ) {
  5257. // red
  5258. this.setHex( hex, colorSpace );
  5259. } else {
  5260. // unknown color
  5261. console.warn( 'THREE.Color: Unknown color ' + style );
  5262. }
  5263. return this;
  5264. }
  5265. clone() {
  5266. return new this.constructor( this.r, this.g, this.b );
  5267. }
  5268. copy( color ) {
  5269. this.r = color.r;
  5270. this.g = color.g;
  5271. this.b = color.b;
  5272. return this;
  5273. }
  5274. copySRGBToLinear( color ) {
  5275. this.r = SRGBToLinear( color.r );
  5276. this.g = SRGBToLinear( color.g );
  5277. this.b = SRGBToLinear( color.b );
  5278. return this;
  5279. }
  5280. copyLinearToSRGB( color ) {
  5281. this.r = LinearToSRGB( color.r );
  5282. this.g = LinearToSRGB( color.g );
  5283. this.b = LinearToSRGB( color.b );
  5284. return this;
  5285. }
  5286. convertSRGBToLinear() {
  5287. this.copySRGBToLinear( this );
  5288. return this;
  5289. }
  5290. convertLinearToSRGB() {
  5291. this.copyLinearToSRGB( this );
  5292. return this;
  5293. }
  5294. getHex( colorSpace = SRGBColorSpace ) {
  5295. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5296. 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 ) );
  5297. }
  5298. getHexString( colorSpace = SRGBColorSpace ) {
  5299. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5300. }
  5301. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5302. // h,s,l ranges are in 0.0 - 1.0
  5303. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5304. const r = _color.r, g = _color.g, b = _color.b;
  5305. const max = Math.max( r, g, b );
  5306. const min = Math.min( r, g, b );
  5307. let hue, saturation;
  5308. const lightness = ( min + max ) / 2.0;
  5309. if ( min === max ) {
  5310. hue = 0;
  5311. saturation = 0;
  5312. } else {
  5313. const delta = max - min;
  5314. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5315. switch ( max ) {
  5316. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5317. case g: hue = ( b - r ) / delta + 2; break;
  5318. case b: hue = ( r - g ) / delta + 4; break;
  5319. }
  5320. hue /= 6;
  5321. }
  5322. target.h = hue;
  5323. target.s = saturation;
  5324. target.l = lightness;
  5325. return target;
  5326. }
  5327. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5328. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5329. target.r = _color.r;
  5330. target.g = _color.g;
  5331. target.b = _color.b;
  5332. return target;
  5333. }
  5334. getStyle( colorSpace = SRGBColorSpace ) {
  5335. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5336. const r = _color.r, g = _color.g, b = _color.b;
  5337. if ( colorSpace !== SRGBColorSpace ) {
  5338. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5339. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5340. }
  5341. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5342. }
  5343. offsetHSL( h, s, l ) {
  5344. this.getHSL( _hslA );
  5345. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5346. }
  5347. add( color ) {
  5348. this.r += color.r;
  5349. this.g += color.g;
  5350. this.b += color.b;
  5351. return this;
  5352. }
  5353. addColors( color1, color2 ) {
  5354. this.r = color1.r + color2.r;
  5355. this.g = color1.g + color2.g;
  5356. this.b = color1.b + color2.b;
  5357. return this;
  5358. }
  5359. addScalar( s ) {
  5360. this.r += s;
  5361. this.g += s;
  5362. this.b += s;
  5363. return this;
  5364. }
  5365. sub( color ) {
  5366. this.r = Math.max( 0, this.r - color.r );
  5367. this.g = Math.max( 0, this.g - color.g );
  5368. this.b = Math.max( 0, this.b - color.b );
  5369. return this;
  5370. }
  5371. multiply( color ) {
  5372. this.r *= color.r;
  5373. this.g *= color.g;
  5374. this.b *= color.b;
  5375. return this;
  5376. }
  5377. multiplyScalar( s ) {
  5378. this.r *= s;
  5379. this.g *= s;
  5380. this.b *= s;
  5381. return this;
  5382. }
  5383. lerp( color, alpha ) {
  5384. this.r += ( color.r - this.r ) * alpha;
  5385. this.g += ( color.g - this.g ) * alpha;
  5386. this.b += ( color.b - this.b ) * alpha;
  5387. return this;
  5388. }
  5389. lerpColors( color1, color2, alpha ) {
  5390. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5391. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5392. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5393. return this;
  5394. }
  5395. lerpHSL( color, alpha ) {
  5396. this.getHSL( _hslA );
  5397. color.getHSL( _hslB );
  5398. const h = lerp( _hslA.h, _hslB.h, alpha );
  5399. const s = lerp( _hslA.s, _hslB.s, alpha );
  5400. const l = lerp( _hslA.l, _hslB.l, alpha );
  5401. this.setHSL( h, s, l );
  5402. return this;
  5403. }
  5404. setFromVector3( v ) {
  5405. this.r = v.x;
  5406. this.g = v.y;
  5407. this.b = v.z;
  5408. return this;
  5409. }
  5410. applyMatrix3( m ) {
  5411. const r = this.r, g = this.g, b = this.b;
  5412. const e = m.elements;
  5413. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5414. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5415. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5416. return this;
  5417. }
  5418. equals( c ) {
  5419. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5420. }
  5421. fromArray( array, offset = 0 ) {
  5422. this.r = array[ offset ];
  5423. this.g = array[ offset + 1 ];
  5424. this.b = array[ offset + 2 ];
  5425. return this;
  5426. }
  5427. toArray( array = [], offset = 0 ) {
  5428. array[ offset ] = this.r;
  5429. array[ offset + 1 ] = this.g;
  5430. array[ offset + 2 ] = this.b;
  5431. return array;
  5432. }
  5433. fromBufferAttribute( attribute, index ) {
  5434. this.r = attribute.getX( index );
  5435. this.g = attribute.getY( index );
  5436. this.b = attribute.getZ( index );
  5437. return this;
  5438. }
  5439. toJSON() {
  5440. return this.getHex();
  5441. }
  5442. *[ Symbol.iterator ]() {
  5443. yield this.r;
  5444. yield this.g;
  5445. yield this.b;
  5446. }
  5447. }
  5448. const _color = /*@__PURE__*/ new Color();
  5449. Color.NAMES = _colorKeywords;
  5450. let _materialId = 0;
  5451. class Material extends EventDispatcher {
  5452. constructor() {
  5453. super();
  5454. this.isMaterial = true;
  5455. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5456. this.uuid = generateUUID();
  5457. this.name = '';
  5458. this.type = 'Material';
  5459. this.blending = NormalBlending;
  5460. this.side = FrontSide;
  5461. this.vertexColors = false;
  5462. this.opacity = 1;
  5463. this.transparent = false;
  5464. this.alphaHash = false;
  5465. this.blendSrc = SrcAlphaFactor;
  5466. this.blendDst = OneMinusSrcAlphaFactor;
  5467. this.blendEquation = AddEquation;
  5468. this.blendSrcAlpha = null;
  5469. this.blendDstAlpha = null;
  5470. this.blendEquationAlpha = null;
  5471. this.blendColor = new Color( 0, 0, 0 );
  5472. this.blendAlpha = 0;
  5473. this.depthFunc = LessEqualDepth;
  5474. this.depthTest = true;
  5475. this.depthWrite = true;
  5476. this.stencilWriteMask = 0xff;
  5477. this.stencilFunc = AlwaysStencilFunc;
  5478. this.stencilRef = 0;
  5479. this.stencilFuncMask = 0xff;
  5480. this.stencilFail = KeepStencilOp;
  5481. this.stencilZFail = KeepStencilOp;
  5482. this.stencilZPass = KeepStencilOp;
  5483. this.stencilWrite = false;
  5484. this.clippingPlanes = null;
  5485. this.clipIntersection = false;
  5486. this.clipShadows = false;
  5487. this.shadowSide = null;
  5488. this.colorWrite = true;
  5489. this.precision = null; // override the renderer's default precision for this material
  5490. this.polygonOffset = false;
  5491. this.polygonOffsetFactor = 0;
  5492. this.polygonOffsetUnits = 0;
  5493. this.dithering = false;
  5494. this.alphaToCoverage = false;
  5495. this.premultipliedAlpha = false;
  5496. this.forceSinglePass = false;
  5497. this.visible = true;
  5498. this.toneMapped = true;
  5499. this.userData = {};
  5500. this.version = 0;
  5501. this._alphaTest = 0;
  5502. }
  5503. get alphaTest() {
  5504. return this._alphaTest;
  5505. }
  5506. set alphaTest( value ) {
  5507. if ( this._alphaTest > 0 !== value > 0 ) {
  5508. this.version ++;
  5509. }
  5510. this._alphaTest = value;
  5511. }
  5512. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5513. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5514. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5515. customProgramCacheKey() {
  5516. return this.onBeforeCompile.toString();
  5517. }
  5518. setValues( values ) {
  5519. if ( values === undefined ) return;
  5520. for ( const key in values ) {
  5521. const newValue = values[ key ];
  5522. if ( newValue === undefined ) {
  5523. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5524. continue;
  5525. }
  5526. const currentValue = this[ key ];
  5527. if ( currentValue === undefined ) {
  5528. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5529. continue;
  5530. }
  5531. if ( currentValue && currentValue.isColor ) {
  5532. currentValue.set( newValue );
  5533. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5534. currentValue.copy( newValue );
  5535. } else {
  5536. this[ key ] = newValue;
  5537. }
  5538. }
  5539. }
  5540. toJSON( meta ) {
  5541. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5542. if ( isRootObject ) {
  5543. meta = {
  5544. textures: {},
  5545. images: {}
  5546. };
  5547. }
  5548. const data = {
  5549. metadata: {
  5550. version: 4.6,
  5551. type: 'Material',
  5552. generator: 'Material.toJSON'
  5553. }
  5554. };
  5555. // standard Material serialization
  5556. data.uuid = this.uuid;
  5557. data.type = this.type;
  5558. if ( this.name !== '' ) data.name = this.name;
  5559. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5560. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5561. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5562. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5563. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5564. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5565. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5566. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5567. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5568. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5569. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5570. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5571. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5572. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5573. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5574. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5575. }
  5576. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5577. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5578. }
  5579. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5580. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5581. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5582. }
  5583. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5584. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5585. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5586. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5587. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5588. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5589. }
  5590. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5591. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5592. }
  5593. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5594. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5595. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5596. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5597. }
  5598. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5599. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5600. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5601. if ( this.lightMap && this.lightMap.isTexture ) {
  5602. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5603. data.lightMapIntensity = this.lightMapIntensity;
  5604. }
  5605. if ( this.aoMap && this.aoMap.isTexture ) {
  5606. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5607. data.aoMapIntensity = this.aoMapIntensity;
  5608. }
  5609. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5610. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5611. data.bumpScale = this.bumpScale;
  5612. }
  5613. if ( this.normalMap && this.normalMap.isTexture ) {
  5614. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5615. data.normalMapType = this.normalMapType;
  5616. data.normalScale = this.normalScale.toArray();
  5617. }
  5618. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5619. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5620. data.displacementScale = this.displacementScale;
  5621. data.displacementBias = this.displacementBias;
  5622. }
  5623. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5624. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5625. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5626. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5627. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5628. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5629. if ( this.envMap && this.envMap.isTexture ) {
  5630. data.envMap = this.envMap.toJSON( meta ).uuid;
  5631. if ( this.combine !== undefined ) data.combine = this.combine;
  5632. }
  5633. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5634. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5635. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5636. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5637. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5638. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5639. }
  5640. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5641. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5642. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5643. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5644. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5645. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5646. if ( this.size !== undefined ) data.size = this.size;
  5647. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5648. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5649. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5650. if ( this.side !== FrontSide ) data.side = this.side;
  5651. if ( this.vertexColors === true ) data.vertexColors = true;
  5652. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5653. if ( this.transparent === true ) data.transparent = true;
  5654. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5655. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5656. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5657. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5658. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5659. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5660. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5661. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5662. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5663. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5664. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5665. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5666. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5667. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5668. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5669. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5670. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5671. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5672. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5673. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5674. // rotation (SpriteMaterial)
  5675. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5676. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5677. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5678. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5679. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5680. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5681. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5682. if ( this.scale !== undefined ) data.scale = this.scale;
  5683. if ( this.dithering === true ) data.dithering = true;
  5684. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5685. if ( this.alphaHash === true ) data.alphaHash = true;
  5686. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5687. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5688. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5689. if ( this.wireframe === true ) data.wireframe = true;
  5690. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5691. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5692. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5693. if ( this.flatShading === true ) data.flatShading = true;
  5694. if ( this.visible === false ) data.visible = false;
  5695. if ( this.toneMapped === false ) data.toneMapped = false;
  5696. if ( this.fog === false ) data.fog = false;
  5697. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5698. // TODO: Copied from Object3D.toJSON
  5699. function extractFromCache( cache ) {
  5700. const values = [];
  5701. for ( const key in cache ) {
  5702. const data = cache[ key ];
  5703. delete data.metadata;
  5704. values.push( data );
  5705. }
  5706. return values;
  5707. }
  5708. if ( isRootObject ) {
  5709. const textures = extractFromCache( meta.textures );
  5710. const images = extractFromCache( meta.images );
  5711. if ( textures.length > 0 ) data.textures = textures;
  5712. if ( images.length > 0 ) data.images = images;
  5713. }
  5714. return data;
  5715. }
  5716. clone() {
  5717. return new this.constructor().copy( this );
  5718. }
  5719. copy( source ) {
  5720. this.name = source.name;
  5721. this.blending = source.blending;
  5722. this.side = source.side;
  5723. this.vertexColors = source.vertexColors;
  5724. this.opacity = source.opacity;
  5725. this.transparent = source.transparent;
  5726. this.blendSrc = source.blendSrc;
  5727. this.blendDst = source.blendDst;
  5728. this.blendEquation = source.blendEquation;
  5729. this.blendSrcAlpha = source.blendSrcAlpha;
  5730. this.blendDstAlpha = source.blendDstAlpha;
  5731. this.blendEquationAlpha = source.blendEquationAlpha;
  5732. this.blendColor.copy( source.blendColor );
  5733. this.blendAlpha = source.blendAlpha;
  5734. this.depthFunc = source.depthFunc;
  5735. this.depthTest = source.depthTest;
  5736. this.depthWrite = source.depthWrite;
  5737. this.stencilWriteMask = source.stencilWriteMask;
  5738. this.stencilFunc = source.stencilFunc;
  5739. this.stencilRef = source.stencilRef;
  5740. this.stencilFuncMask = source.stencilFuncMask;
  5741. this.stencilFail = source.stencilFail;
  5742. this.stencilZFail = source.stencilZFail;
  5743. this.stencilZPass = source.stencilZPass;
  5744. this.stencilWrite = source.stencilWrite;
  5745. const srcPlanes = source.clippingPlanes;
  5746. let dstPlanes = null;
  5747. if ( srcPlanes !== null ) {
  5748. const n = srcPlanes.length;
  5749. dstPlanes = new Array( n );
  5750. for ( let i = 0; i !== n; ++ i ) {
  5751. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5752. }
  5753. }
  5754. this.clippingPlanes = dstPlanes;
  5755. this.clipIntersection = source.clipIntersection;
  5756. this.clipShadows = source.clipShadows;
  5757. this.shadowSide = source.shadowSide;
  5758. this.colorWrite = source.colorWrite;
  5759. this.precision = source.precision;
  5760. this.polygonOffset = source.polygonOffset;
  5761. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5762. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5763. this.dithering = source.dithering;
  5764. this.alphaTest = source.alphaTest;
  5765. this.alphaHash = source.alphaHash;
  5766. this.alphaToCoverage = source.alphaToCoverage;
  5767. this.premultipliedAlpha = source.premultipliedAlpha;
  5768. this.forceSinglePass = source.forceSinglePass;
  5769. this.visible = source.visible;
  5770. this.toneMapped = source.toneMapped;
  5771. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5772. return this;
  5773. }
  5774. dispose() {
  5775. this.dispatchEvent( { type: 'dispose' } );
  5776. }
  5777. set needsUpdate( value ) {
  5778. if ( value === true ) this.version ++;
  5779. }
  5780. onBuild( /* shaderobject, renderer */ ) {
  5781. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5782. }
  5783. }
  5784. class MeshBasicMaterial extends Material {
  5785. constructor( parameters ) {
  5786. super();
  5787. this.isMeshBasicMaterial = true;
  5788. this.type = 'MeshBasicMaterial';
  5789. this.color = new Color( 0xffffff ); // emissive
  5790. this.map = null;
  5791. this.lightMap = null;
  5792. this.lightMapIntensity = 1.0;
  5793. this.aoMap = null;
  5794. this.aoMapIntensity = 1.0;
  5795. this.specularMap = null;
  5796. this.alphaMap = null;
  5797. this.envMap = null;
  5798. this.envMapRotation = new Euler();
  5799. this.combine = MultiplyOperation;
  5800. this.reflectivity = 1;
  5801. this.refractionRatio = 0.98;
  5802. this.wireframe = false;
  5803. this.wireframeLinewidth = 1;
  5804. this.wireframeLinecap = 'round';
  5805. this.wireframeLinejoin = 'round';
  5806. this.fog = true;
  5807. this.setValues( parameters );
  5808. }
  5809. copy( source ) {
  5810. super.copy( source );
  5811. this.color.copy( source.color );
  5812. this.map = source.map;
  5813. this.lightMap = source.lightMap;
  5814. this.lightMapIntensity = source.lightMapIntensity;
  5815. this.aoMap = source.aoMap;
  5816. this.aoMapIntensity = source.aoMapIntensity;
  5817. this.specularMap = source.specularMap;
  5818. this.alphaMap = source.alphaMap;
  5819. this.envMap = source.envMap;
  5820. this.envMapRotation.copy( source.envMapRotation );
  5821. this.combine = source.combine;
  5822. this.reflectivity = source.reflectivity;
  5823. this.refractionRatio = source.refractionRatio;
  5824. this.wireframe = source.wireframe;
  5825. this.wireframeLinewidth = source.wireframeLinewidth;
  5826. this.wireframeLinecap = source.wireframeLinecap;
  5827. this.wireframeLinejoin = source.wireframeLinejoin;
  5828. this.fog = source.fog;
  5829. return this;
  5830. }
  5831. }
  5832. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5833. const _tables = /*@__PURE__*/ _generateTables();
  5834. function _generateTables() {
  5835. // float32 to float16 helpers
  5836. const buffer = new ArrayBuffer( 4 );
  5837. const floatView = new Float32Array( buffer );
  5838. const uint32View = new Uint32Array( buffer );
  5839. const baseTable = new Uint32Array( 512 );
  5840. const shiftTable = new Uint32Array( 512 );
  5841. for ( let i = 0; i < 256; ++ i ) {
  5842. const e = i - 127;
  5843. // very small number (0, -0)
  5844. if ( e < - 27 ) {
  5845. baseTable[ i ] = 0x0000;
  5846. baseTable[ i | 0x100 ] = 0x8000;
  5847. shiftTable[ i ] = 24;
  5848. shiftTable[ i | 0x100 ] = 24;
  5849. // small number (denorm)
  5850. } else if ( e < - 14 ) {
  5851. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5852. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5853. shiftTable[ i ] = - e - 1;
  5854. shiftTable[ i | 0x100 ] = - e - 1;
  5855. // normal number
  5856. } else if ( e <= 15 ) {
  5857. baseTable[ i ] = ( e + 15 ) << 10;
  5858. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5859. shiftTable[ i ] = 13;
  5860. shiftTable[ i | 0x100 ] = 13;
  5861. // large number (Infinity, -Infinity)
  5862. } else if ( e < 128 ) {
  5863. baseTable[ i ] = 0x7c00;
  5864. baseTable[ i | 0x100 ] = 0xfc00;
  5865. shiftTable[ i ] = 24;
  5866. shiftTable[ i | 0x100 ] = 24;
  5867. // stay (NaN, Infinity, -Infinity)
  5868. } else {
  5869. baseTable[ i ] = 0x7c00;
  5870. baseTable[ i | 0x100 ] = 0xfc00;
  5871. shiftTable[ i ] = 13;
  5872. shiftTable[ i | 0x100 ] = 13;
  5873. }
  5874. }
  5875. // float16 to float32 helpers
  5876. const mantissaTable = new Uint32Array( 2048 );
  5877. const exponentTable = new Uint32Array( 64 );
  5878. const offsetTable = new Uint32Array( 64 );
  5879. for ( let i = 1; i < 1024; ++ i ) {
  5880. let m = i << 13; // zero pad mantissa bits
  5881. let e = 0; // zero exponent
  5882. // normalized
  5883. while ( ( m & 0x00800000 ) === 0 ) {
  5884. m <<= 1;
  5885. e -= 0x00800000; // decrement exponent
  5886. }
  5887. m &= ~ 0x00800000; // clear leading 1 bit
  5888. e += 0x38800000; // adjust bias
  5889. mantissaTable[ i ] = m | e;
  5890. }
  5891. for ( let i = 1024; i < 2048; ++ i ) {
  5892. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5893. }
  5894. for ( let i = 1; i < 31; ++ i ) {
  5895. exponentTable[ i ] = i << 23;
  5896. }
  5897. exponentTable[ 31 ] = 0x47800000;
  5898. exponentTable[ 32 ] = 0x80000000;
  5899. for ( let i = 33; i < 63; ++ i ) {
  5900. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5901. }
  5902. exponentTable[ 63 ] = 0xc7800000;
  5903. for ( let i = 1; i < 64; ++ i ) {
  5904. if ( i !== 32 ) {
  5905. offsetTable[ i ] = 1024;
  5906. }
  5907. }
  5908. return {
  5909. floatView: floatView,
  5910. uint32View: uint32View,
  5911. baseTable: baseTable,
  5912. shiftTable: shiftTable,
  5913. mantissaTable: mantissaTable,
  5914. exponentTable: exponentTable,
  5915. offsetTable: offsetTable
  5916. };
  5917. }
  5918. // float32 to float16
  5919. function toHalfFloat( val ) {
  5920. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5921. val = clamp$1( val, - 65504, 65504 );
  5922. _tables.floatView[ 0 ] = val;
  5923. const f = _tables.uint32View[ 0 ];
  5924. const e = ( f >> 23 ) & 0x1ff;
  5925. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5926. }
  5927. // float16 to float32
  5928. function fromHalfFloat( val ) {
  5929. const m = val >> 10;
  5930. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5931. return _tables.floatView[ 0 ];
  5932. }
  5933. const DataUtils = {
  5934. toHalfFloat: toHalfFloat,
  5935. fromHalfFloat: fromHalfFloat,
  5936. };
  5937. const _vector$9 = /*@__PURE__*/ new Vector3();
  5938. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5939. class BufferAttribute {
  5940. constructor( array, itemSize, normalized = false ) {
  5941. if ( Array.isArray( array ) ) {
  5942. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5943. }
  5944. this.isBufferAttribute = true;
  5945. this.name = '';
  5946. this.array = array;
  5947. this.itemSize = itemSize;
  5948. this.count = array !== undefined ? array.length / itemSize : 0;
  5949. this.normalized = normalized;
  5950. this.usage = StaticDrawUsage;
  5951. this.updateRanges = [];
  5952. this.gpuType = FloatType;
  5953. this.version = 0;
  5954. }
  5955. onUploadCallback() {}
  5956. set needsUpdate( value ) {
  5957. if ( value === true ) this.version ++;
  5958. }
  5959. setUsage( value ) {
  5960. this.usage = value;
  5961. return this;
  5962. }
  5963. addUpdateRange( start, count ) {
  5964. this.updateRanges.push( { start, count } );
  5965. }
  5966. clearUpdateRanges() {
  5967. this.updateRanges.length = 0;
  5968. }
  5969. copy( source ) {
  5970. this.name = source.name;
  5971. this.array = new source.array.constructor( source.array );
  5972. this.itemSize = source.itemSize;
  5973. this.count = source.count;
  5974. this.normalized = source.normalized;
  5975. this.usage = source.usage;
  5976. this.gpuType = source.gpuType;
  5977. return this;
  5978. }
  5979. copyAt( index1, attribute, index2 ) {
  5980. index1 *= this.itemSize;
  5981. index2 *= attribute.itemSize;
  5982. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5983. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5984. }
  5985. return this;
  5986. }
  5987. copyArray( array ) {
  5988. this.array.set( array );
  5989. return this;
  5990. }
  5991. applyMatrix3( m ) {
  5992. if ( this.itemSize === 2 ) {
  5993. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5994. _vector2$1.fromBufferAttribute( this, i );
  5995. _vector2$1.applyMatrix3( m );
  5996. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5997. }
  5998. } else if ( this.itemSize === 3 ) {
  5999. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6000. _vector$9.fromBufferAttribute( this, i );
  6001. _vector$9.applyMatrix3( m );
  6002. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6003. }
  6004. }
  6005. return this;
  6006. }
  6007. applyMatrix4( m ) {
  6008. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6009. _vector$9.fromBufferAttribute( this, i );
  6010. _vector$9.applyMatrix4( m );
  6011. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6012. }
  6013. return this;
  6014. }
  6015. applyNormalMatrix( m ) {
  6016. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6017. _vector$9.fromBufferAttribute( this, i );
  6018. _vector$9.applyNormalMatrix( m );
  6019. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6020. }
  6021. return this;
  6022. }
  6023. transformDirection( m ) {
  6024. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6025. _vector$9.fromBufferAttribute( this, i );
  6026. _vector$9.transformDirection( m );
  6027. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6028. }
  6029. return this;
  6030. }
  6031. set( value, offset = 0 ) {
  6032. // Matching BufferAttribute constructor, do not normalize the array.
  6033. this.array.set( value, offset );
  6034. return this;
  6035. }
  6036. getComponent( index, component ) {
  6037. let value = this.array[ index * this.itemSize + component ];
  6038. if ( this.normalized ) value = denormalize( value, this.array );
  6039. return value;
  6040. }
  6041. setComponent( index, component, value ) {
  6042. if ( this.normalized ) value = normalize$1( value, this.array );
  6043. this.array[ index * this.itemSize + component ] = value;
  6044. return this;
  6045. }
  6046. getX( index ) {
  6047. let x = this.array[ index * this.itemSize ];
  6048. if ( this.normalized ) x = denormalize( x, this.array );
  6049. return x;
  6050. }
  6051. setX( index, x ) {
  6052. if ( this.normalized ) x = normalize$1( x, this.array );
  6053. this.array[ index * this.itemSize ] = x;
  6054. return this;
  6055. }
  6056. getY( index ) {
  6057. let y = this.array[ index * this.itemSize + 1 ];
  6058. if ( this.normalized ) y = denormalize( y, this.array );
  6059. return y;
  6060. }
  6061. setY( index, y ) {
  6062. if ( this.normalized ) y = normalize$1( y, this.array );
  6063. this.array[ index * this.itemSize + 1 ] = y;
  6064. return this;
  6065. }
  6066. getZ( index ) {
  6067. let z = this.array[ index * this.itemSize + 2 ];
  6068. if ( this.normalized ) z = denormalize( z, this.array );
  6069. return z;
  6070. }
  6071. setZ( index, z ) {
  6072. if ( this.normalized ) z = normalize$1( z, this.array );
  6073. this.array[ index * this.itemSize + 2 ] = z;
  6074. return this;
  6075. }
  6076. getW( index ) {
  6077. let w = this.array[ index * this.itemSize + 3 ];
  6078. if ( this.normalized ) w = denormalize( w, this.array );
  6079. return w;
  6080. }
  6081. setW( index, w ) {
  6082. if ( this.normalized ) w = normalize$1( w, this.array );
  6083. this.array[ index * this.itemSize + 3 ] = w;
  6084. return this;
  6085. }
  6086. setXY( index, x, y ) {
  6087. index *= this.itemSize;
  6088. if ( this.normalized ) {
  6089. x = normalize$1( x, this.array );
  6090. y = normalize$1( y, this.array );
  6091. }
  6092. this.array[ index + 0 ] = x;
  6093. this.array[ index + 1 ] = y;
  6094. return this;
  6095. }
  6096. setXYZ( index, x, y, z ) {
  6097. index *= this.itemSize;
  6098. if ( this.normalized ) {
  6099. x = normalize$1( x, this.array );
  6100. y = normalize$1( y, this.array );
  6101. z = normalize$1( z, this.array );
  6102. }
  6103. this.array[ index + 0 ] = x;
  6104. this.array[ index + 1 ] = y;
  6105. this.array[ index + 2 ] = z;
  6106. return this;
  6107. }
  6108. setXYZW( index, x, y, z, w ) {
  6109. index *= this.itemSize;
  6110. if ( this.normalized ) {
  6111. x = normalize$1( x, this.array );
  6112. y = normalize$1( y, this.array );
  6113. z = normalize$1( z, this.array );
  6114. w = normalize$1( w, this.array );
  6115. }
  6116. this.array[ index + 0 ] = x;
  6117. this.array[ index + 1 ] = y;
  6118. this.array[ index + 2 ] = z;
  6119. this.array[ index + 3 ] = w;
  6120. return this;
  6121. }
  6122. onUpload( callback ) {
  6123. this.onUploadCallback = callback;
  6124. return this;
  6125. }
  6126. clone() {
  6127. return new this.constructor( this.array, this.itemSize ).copy( this );
  6128. }
  6129. toJSON() {
  6130. const data = {
  6131. itemSize: this.itemSize,
  6132. type: this.array.constructor.name,
  6133. array: Array.from( this.array ),
  6134. normalized: this.normalized
  6135. };
  6136. if ( this.name !== '' ) data.name = this.name;
  6137. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6138. return data;
  6139. }
  6140. }
  6141. //
  6142. class Int8BufferAttribute extends BufferAttribute {
  6143. constructor( array, itemSize, normalized ) {
  6144. super( new Int8Array( array ), itemSize, normalized );
  6145. }
  6146. }
  6147. class Uint8BufferAttribute extends BufferAttribute {
  6148. constructor( array, itemSize, normalized ) {
  6149. super( new Uint8Array( array ), itemSize, normalized );
  6150. }
  6151. }
  6152. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6153. constructor( array, itemSize, normalized ) {
  6154. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6155. }
  6156. }
  6157. class Int16BufferAttribute extends BufferAttribute {
  6158. constructor( array, itemSize, normalized ) {
  6159. super( new Int16Array( array ), itemSize, normalized );
  6160. }
  6161. }
  6162. class Uint16BufferAttribute extends BufferAttribute {
  6163. constructor( array, itemSize, normalized ) {
  6164. super( new Uint16Array( array ), itemSize, normalized );
  6165. }
  6166. }
  6167. class Int32BufferAttribute extends BufferAttribute {
  6168. constructor( array, itemSize, normalized ) {
  6169. super( new Int32Array( array ), itemSize, normalized );
  6170. }
  6171. }
  6172. class Uint32BufferAttribute extends BufferAttribute {
  6173. constructor( array, itemSize, normalized ) {
  6174. super( new Uint32Array( array ), itemSize, normalized );
  6175. }
  6176. }
  6177. class Float16BufferAttribute extends BufferAttribute {
  6178. constructor( array, itemSize, normalized ) {
  6179. super( new Uint16Array( array ), itemSize, normalized );
  6180. this.isFloat16BufferAttribute = true;
  6181. }
  6182. getX( index ) {
  6183. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6184. if ( this.normalized ) x = denormalize( x, this.array );
  6185. return x;
  6186. }
  6187. setX( index, x ) {
  6188. if ( this.normalized ) x = normalize$1( x, this.array );
  6189. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6190. return this;
  6191. }
  6192. getY( index ) {
  6193. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6194. if ( this.normalized ) y = denormalize( y, this.array );
  6195. return y;
  6196. }
  6197. setY( index, y ) {
  6198. if ( this.normalized ) y = normalize$1( y, this.array );
  6199. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6200. return this;
  6201. }
  6202. getZ( index ) {
  6203. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6204. if ( this.normalized ) z = denormalize( z, this.array );
  6205. return z;
  6206. }
  6207. setZ( index, z ) {
  6208. if ( this.normalized ) z = normalize$1( z, this.array );
  6209. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6210. return this;
  6211. }
  6212. getW( index ) {
  6213. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6214. if ( this.normalized ) w = denormalize( w, this.array );
  6215. return w;
  6216. }
  6217. setW( index, w ) {
  6218. if ( this.normalized ) w = normalize$1( w, this.array );
  6219. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6220. return this;
  6221. }
  6222. setXY( index, x, y ) {
  6223. index *= this.itemSize;
  6224. if ( this.normalized ) {
  6225. x = normalize$1( x, this.array );
  6226. y = normalize$1( y, this.array );
  6227. }
  6228. this.array[ index + 0 ] = toHalfFloat( x );
  6229. this.array[ index + 1 ] = toHalfFloat( y );
  6230. return this;
  6231. }
  6232. setXYZ( index, x, y, z ) {
  6233. index *= this.itemSize;
  6234. if ( this.normalized ) {
  6235. x = normalize$1( x, this.array );
  6236. y = normalize$1( y, this.array );
  6237. z = normalize$1( z, this.array );
  6238. }
  6239. this.array[ index + 0 ] = toHalfFloat( x );
  6240. this.array[ index + 1 ] = toHalfFloat( y );
  6241. this.array[ index + 2 ] = toHalfFloat( z );
  6242. return this;
  6243. }
  6244. setXYZW( index, x, y, z, w ) {
  6245. index *= this.itemSize;
  6246. if ( this.normalized ) {
  6247. x = normalize$1( x, this.array );
  6248. y = normalize$1( y, this.array );
  6249. z = normalize$1( z, this.array );
  6250. w = normalize$1( w, this.array );
  6251. }
  6252. this.array[ index + 0 ] = toHalfFloat( x );
  6253. this.array[ index + 1 ] = toHalfFloat( y );
  6254. this.array[ index + 2 ] = toHalfFloat( z );
  6255. this.array[ index + 3 ] = toHalfFloat( w );
  6256. return this;
  6257. }
  6258. }
  6259. class Float32BufferAttribute extends BufferAttribute {
  6260. constructor( array, itemSize, normalized ) {
  6261. super( new Float32Array( array ), itemSize, normalized );
  6262. }
  6263. }
  6264. let _id$9 = 0;
  6265. const _m1 = /*@__PURE__*/ new Matrix4();
  6266. const _obj = /*@__PURE__*/ new Object3D();
  6267. const _offset = /*@__PURE__*/ new Vector3();
  6268. const _box$2 = /*@__PURE__*/ new Box3();
  6269. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6270. const _vector$8 = /*@__PURE__*/ new Vector3();
  6271. class BufferGeometry extends EventDispatcher {
  6272. constructor() {
  6273. super();
  6274. this.isBufferGeometry = true;
  6275. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6276. this.uuid = generateUUID();
  6277. this.name = '';
  6278. this.type = 'BufferGeometry';
  6279. this.index = null;
  6280. this.attributes = {};
  6281. this.morphAttributes = {};
  6282. this.morphTargetsRelative = false;
  6283. this.groups = [];
  6284. this.boundingBox = null;
  6285. this.boundingSphere = null;
  6286. this.drawRange = { start: 0, count: Infinity };
  6287. this.userData = {};
  6288. }
  6289. getIndex() {
  6290. return this.index;
  6291. }
  6292. setIndex( index ) {
  6293. if ( Array.isArray( index ) ) {
  6294. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6295. } else {
  6296. this.index = index;
  6297. }
  6298. return this;
  6299. }
  6300. getAttribute( name ) {
  6301. return this.attributes[ name ];
  6302. }
  6303. setAttribute( name, attribute ) {
  6304. this.attributes[ name ] = attribute;
  6305. return this;
  6306. }
  6307. deleteAttribute( name ) {
  6308. delete this.attributes[ name ];
  6309. return this;
  6310. }
  6311. hasAttribute( name ) {
  6312. return this.attributes[ name ] !== undefined;
  6313. }
  6314. addGroup( start, count, materialIndex = 0 ) {
  6315. this.groups.push( {
  6316. start: start,
  6317. count: count,
  6318. materialIndex: materialIndex
  6319. } );
  6320. }
  6321. clearGroups() {
  6322. this.groups = [];
  6323. }
  6324. setDrawRange( start, count ) {
  6325. this.drawRange.start = start;
  6326. this.drawRange.count = count;
  6327. }
  6328. applyMatrix4( matrix ) {
  6329. const position = this.attributes.position;
  6330. if ( position !== undefined ) {
  6331. position.applyMatrix4( matrix );
  6332. position.needsUpdate = true;
  6333. }
  6334. const normal = this.attributes.normal;
  6335. if ( normal !== undefined ) {
  6336. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6337. normal.applyNormalMatrix( normalMatrix );
  6338. normal.needsUpdate = true;
  6339. }
  6340. const tangent = this.attributes.tangent;
  6341. if ( tangent !== undefined ) {
  6342. tangent.transformDirection( matrix );
  6343. tangent.needsUpdate = true;
  6344. }
  6345. if ( this.boundingBox !== null ) {
  6346. this.computeBoundingBox();
  6347. }
  6348. if ( this.boundingSphere !== null ) {
  6349. this.computeBoundingSphere();
  6350. }
  6351. return this;
  6352. }
  6353. applyQuaternion( q ) {
  6354. _m1.makeRotationFromQuaternion( q );
  6355. this.applyMatrix4( _m1 );
  6356. return this;
  6357. }
  6358. rotateX( angle ) {
  6359. // rotate geometry around world x-axis
  6360. _m1.makeRotationX( angle );
  6361. this.applyMatrix4( _m1 );
  6362. return this;
  6363. }
  6364. rotateY( angle ) {
  6365. // rotate geometry around world y-axis
  6366. _m1.makeRotationY( angle );
  6367. this.applyMatrix4( _m1 );
  6368. return this;
  6369. }
  6370. rotateZ( angle ) {
  6371. // rotate geometry around world z-axis
  6372. _m1.makeRotationZ( angle );
  6373. this.applyMatrix4( _m1 );
  6374. return this;
  6375. }
  6376. translate( x, y, z ) {
  6377. // translate geometry
  6378. _m1.makeTranslation( x, y, z );
  6379. this.applyMatrix4( _m1 );
  6380. return this;
  6381. }
  6382. scale( x, y, z ) {
  6383. // scale geometry
  6384. _m1.makeScale( x, y, z );
  6385. this.applyMatrix4( _m1 );
  6386. return this;
  6387. }
  6388. lookAt( vector ) {
  6389. _obj.lookAt( vector );
  6390. _obj.updateMatrix();
  6391. this.applyMatrix4( _obj.matrix );
  6392. return this;
  6393. }
  6394. center() {
  6395. this.computeBoundingBox();
  6396. this.boundingBox.getCenter( _offset ).negate();
  6397. this.translate( _offset.x, _offset.y, _offset.z );
  6398. return this;
  6399. }
  6400. setFromPoints( points ) {
  6401. const position = [];
  6402. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6403. const point = points[ i ];
  6404. position.push( point.x, point.y, point.z || 0 );
  6405. }
  6406. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6407. return this;
  6408. }
  6409. computeBoundingBox() {
  6410. if ( this.boundingBox === null ) {
  6411. this.boundingBox = new Box3();
  6412. }
  6413. const position = this.attributes.position;
  6414. const morphAttributesPosition = this.morphAttributes.position;
  6415. if ( position && position.isGLBufferAttribute ) {
  6416. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6417. this.boundingBox.set(
  6418. new Vector3( - Infinity, - Infinity, - Infinity ),
  6419. new Vector3( + Infinity, + Infinity, + Infinity )
  6420. );
  6421. return;
  6422. }
  6423. if ( position !== undefined ) {
  6424. this.boundingBox.setFromBufferAttribute( position );
  6425. // process morph attributes if present
  6426. if ( morphAttributesPosition ) {
  6427. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6428. const morphAttribute = morphAttributesPosition[ i ];
  6429. _box$2.setFromBufferAttribute( morphAttribute );
  6430. if ( this.morphTargetsRelative ) {
  6431. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6432. this.boundingBox.expandByPoint( _vector$8 );
  6433. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6434. this.boundingBox.expandByPoint( _vector$8 );
  6435. } else {
  6436. this.boundingBox.expandByPoint( _box$2.min );
  6437. this.boundingBox.expandByPoint( _box$2.max );
  6438. }
  6439. }
  6440. }
  6441. } else {
  6442. this.boundingBox.makeEmpty();
  6443. }
  6444. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6445. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6446. }
  6447. }
  6448. computeBoundingSphere() {
  6449. if ( this.boundingSphere === null ) {
  6450. this.boundingSphere = new Sphere();
  6451. }
  6452. const position = this.attributes.position;
  6453. const morphAttributesPosition = this.morphAttributes.position;
  6454. if ( position && position.isGLBufferAttribute ) {
  6455. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6456. this.boundingSphere.set( new Vector3(), Infinity );
  6457. return;
  6458. }
  6459. if ( position ) {
  6460. // first, find the center of the bounding sphere
  6461. const center = this.boundingSphere.center;
  6462. _box$2.setFromBufferAttribute( position );
  6463. // process morph attributes if present
  6464. if ( morphAttributesPosition ) {
  6465. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6466. const morphAttribute = morphAttributesPosition[ i ];
  6467. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6468. if ( this.morphTargetsRelative ) {
  6469. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6470. _box$2.expandByPoint( _vector$8 );
  6471. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6472. _box$2.expandByPoint( _vector$8 );
  6473. } else {
  6474. _box$2.expandByPoint( _boxMorphTargets.min );
  6475. _box$2.expandByPoint( _boxMorphTargets.max );
  6476. }
  6477. }
  6478. }
  6479. _box$2.getCenter( center );
  6480. // second, try to find a boundingSphere with a radius smaller than the
  6481. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6482. let maxRadiusSq = 0;
  6483. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6484. _vector$8.fromBufferAttribute( position, i );
  6485. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6486. }
  6487. // process morph attributes if present
  6488. if ( morphAttributesPosition ) {
  6489. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6490. const morphAttribute = morphAttributesPosition[ i ];
  6491. const morphTargetsRelative = this.morphTargetsRelative;
  6492. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6493. _vector$8.fromBufferAttribute( morphAttribute, j );
  6494. if ( morphTargetsRelative ) {
  6495. _offset.fromBufferAttribute( position, j );
  6496. _vector$8.add( _offset );
  6497. }
  6498. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6499. }
  6500. }
  6501. }
  6502. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6503. if ( isNaN( this.boundingSphere.radius ) ) {
  6504. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6505. }
  6506. }
  6507. }
  6508. computeTangents() {
  6509. const index = this.index;
  6510. const attributes = this.attributes;
  6511. // based on http://www.terathon.com/code/tangent.html
  6512. // (per vertex tangents)
  6513. if ( index === null ||
  6514. attributes.position === undefined ||
  6515. attributes.normal === undefined ||
  6516. attributes.uv === undefined ) {
  6517. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6518. return;
  6519. }
  6520. const positionAttribute = attributes.position;
  6521. const normalAttribute = attributes.normal;
  6522. const uvAttribute = attributes.uv;
  6523. if ( this.hasAttribute( 'tangent' ) === false ) {
  6524. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6525. }
  6526. const tangentAttribute = this.getAttribute( 'tangent' );
  6527. const tan1 = [], tan2 = [];
  6528. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6529. tan1[ i ] = new Vector3();
  6530. tan2[ i ] = new Vector3();
  6531. }
  6532. const vA = new Vector3(),
  6533. vB = new Vector3(),
  6534. vC = new Vector3(),
  6535. uvA = new Vector2(),
  6536. uvB = new Vector2(),
  6537. uvC = new Vector2(),
  6538. sdir = new Vector3(),
  6539. tdir = new Vector3();
  6540. function handleTriangle( a, b, c ) {
  6541. vA.fromBufferAttribute( positionAttribute, a );
  6542. vB.fromBufferAttribute( positionAttribute, b );
  6543. vC.fromBufferAttribute( positionAttribute, c );
  6544. uvA.fromBufferAttribute( uvAttribute, a );
  6545. uvB.fromBufferAttribute( uvAttribute, b );
  6546. uvC.fromBufferAttribute( uvAttribute, c );
  6547. vB.sub( vA );
  6548. vC.sub( vA );
  6549. uvB.sub( uvA );
  6550. uvC.sub( uvA );
  6551. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6552. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6553. if ( ! isFinite( r ) ) return;
  6554. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6555. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6556. tan1[ a ].add( sdir );
  6557. tan1[ b ].add( sdir );
  6558. tan1[ c ].add( sdir );
  6559. tan2[ a ].add( tdir );
  6560. tan2[ b ].add( tdir );
  6561. tan2[ c ].add( tdir );
  6562. }
  6563. let groups = this.groups;
  6564. if ( groups.length === 0 ) {
  6565. groups = [ {
  6566. start: 0,
  6567. count: index.count
  6568. } ];
  6569. }
  6570. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6571. const group = groups[ i ];
  6572. const start = group.start;
  6573. const count = group.count;
  6574. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6575. handleTriangle(
  6576. index.getX( j + 0 ),
  6577. index.getX( j + 1 ),
  6578. index.getX( j + 2 )
  6579. );
  6580. }
  6581. }
  6582. const tmp = new Vector3(), tmp2 = new Vector3();
  6583. const n = new Vector3(), n2 = new Vector3();
  6584. function handleVertex( v ) {
  6585. n.fromBufferAttribute( normalAttribute, v );
  6586. n2.copy( n );
  6587. const t = tan1[ v ];
  6588. // Gram-Schmidt orthogonalize
  6589. tmp.copy( t );
  6590. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6591. // Calculate handedness
  6592. tmp2.crossVectors( n2, t );
  6593. const test = tmp2.dot( tan2[ v ] );
  6594. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6595. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6596. }
  6597. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6598. const group = groups[ i ];
  6599. const start = group.start;
  6600. const count = group.count;
  6601. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6602. handleVertex( index.getX( j + 0 ) );
  6603. handleVertex( index.getX( j + 1 ) );
  6604. handleVertex( index.getX( j + 2 ) );
  6605. }
  6606. }
  6607. }
  6608. computeVertexNormals() {
  6609. const index = this.index;
  6610. const positionAttribute = this.getAttribute( 'position' );
  6611. if ( positionAttribute !== undefined ) {
  6612. let normalAttribute = this.getAttribute( 'normal' );
  6613. if ( normalAttribute === undefined ) {
  6614. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6615. this.setAttribute( 'normal', normalAttribute );
  6616. } else {
  6617. // reset existing normals to zero
  6618. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6619. normalAttribute.setXYZ( i, 0, 0, 0 );
  6620. }
  6621. }
  6622. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6623. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6624. const cb = new Vector3(), ab = new Vector3();
  6625. // indexed elements
  6626. if ( index ) {
  6627. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6628. const vA = index.getX( i + 0 );
  6629. const vB = index.getX( i + 1 );
  6630. const vC = index.getX( i + 2 );
  6631. pA.fromBufferAttribute( positionAttribute, vA );
  6632. pB.fromBufferAttribute( positionAttribute, vB );
  6633. pC.fromBufferAttribute( positionAttribute, vC );
  6634. cb.subVectors( pC, pB );
  6635. ab.subVectors( pA, pB );
  6636. cb.cross( ab );
  6637. nA.fromBufferAttribute( normalAttribute, vA );
  6638. nB.fromBufferAttribute( normalAttribute, vB );
  6639. nC.fromBufferAttribute( normalAttribute, vC );
  6640. nA.add( cb );
  6641. nB.add( cb );
  6642. nC.add( cb );
  6643. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6644. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6645. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6646. }
  6647. } else {
  6648. // non-indexed elements (unconnected triangle soup)
  6649. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6650. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6651. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6652. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6653. cb.subVectors( pC, pB );
  6654. ab.subVectors( pA, pB );
  6655. cb.cross( ab );
  6656. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6657. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6658. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6659. }
  6660. }
  6661. this.normalizeNormals();
  6662. normalAttribute.needsUpdate = true;
  6663. }
  6664. }
  6665. normalizeNormals() {
  6666. const normals = this.attributes.normal;
  6667. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6668. _vector$8.fromBufferAttribute( normals, i );
  6669. _vector$8.normalize();
  6670. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6671. }
  6672. }
  6673. toNonIndexed() {
  6674. function convertBufferAttribute( attribute, indices ) {
  6675. const array = attribute.array;
  6676. const itemSize = attribute.itemSize;
  6677. const normalized = attribute.normalized;
  6678. const array2 = new array.constructor( indices.length * itemSize );
  6679. let index = 0, index2 = 0;
  6680. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6681. if ( attribute.isInterleavedBufferAttribute ) {
  6682. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6683. } else {
  6684. index = indices[ i ] * itemSize;
  6685. }
  6686. for ( let j = 0; j < itemSize; j ++ ) {
  6687. array2[ index2 ++ ] = array[ index ++ ];
  6688. }
  6689. }
  6690. return new BufferAttribute( array2, itemSize, normalized );
  6691. }
  6692. //
  6693. if ( this.index === null ) {
  6694. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6695. return this;
  6696. }
  6697. const geometry2 = new BufferGeometry();
  6698. const indices = this.index.array;
  6699. const attributes = this.attributes;
  6700. // attributes
  6701. for ( const name in attributes ) {
  6702. const attribute = attributes[ name ];
  6703. const newAttribute = convertBufferAttribute( attribute, indices );
  6704. geometry2.setAttribute( name, newAttribute );
  6705. }
  6706. // morph attributes
  6707. const morphAttributes = this.morphAttributes;
  6708. for ( const name in morphAttributes ) {
  6709. const morphArray = [];
  6710. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6711. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6712. const attribute = morphAttribute[ i ];
  6713. const newAttribute = convertBufferAttribute( attribute, indices );
  6714. morphArray.push( newAttribute );
  6715. }
  6716. geometry2.morphAttributes[ name ] = morphArray;
  6717. }
  6718. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6719. // groups
  6720. const groups = this.groups;
  6721. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6722. const group = groups[ i ];
  6723. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6724. }
  6725. return geometry2;
  6726. }
  6727. toJSON() {
  6728. const data = {
  6729. metadata: {
  6730. version: 4.6,
  6731. type: 'BufferGeometry',
  6732. generator: 'BufferGeometry.toJSON'
  6733. }
  6734. };
  6735. // standard BufferGeometry serialization
  6736. data.uuid = this.uuid;
  6737. data.type = this.type;
  6738. if ( this.name !== '' ) data.name = this.name;
  6739. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6740. if ( this.parameters !== undefined ) {
  6741. const parameters = this.parameters;
  6742. for ( const key in parameters ) {
  6743. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6744. }
  6745. return data;
  6746. }
  6747. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6748. data.data = { attributes: {} };
  6749. const index = this.index;
  6750. if ( index !== null ) {
  6751. data.data.index = {
  6752. type: index.array.constructor.name,
  6753. array: Array.prototype.slice.call( index.array )
  6754. };
  6755. }
  6756. const attributes = this.attributes;
  6757. for ( const key in attributes ) {
  6758. const attribute = attributes[ key ];
  6759. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6760. }
  6761. const morphAttributes = {};
  6762. let hasMorphAttributes = false;
  6763. for ( const key in this.morphAttributes ) {
  6764. const attributeArray = this.morphAttributes[ key ];
  6765. const array = [];
  6766. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6767. const attribute = attributeArray[ i ];
  6768. array.push( attribute.toJSON( data.data ) );
  6769. }
  6770. if ( array.length > 0 ) {
  6771. morphAttributes[ key ] = array;
  6772. hasMorphAttributes = true;
  6773. }
  6774. }
  6775. if ( hasMorphAttributes ) {
  6776. data.data.morphAttributes = morphAttributes;
  6777. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6778. }
  6779. const groups = this.groups;
  6780. if ( groups.length > 0 ) {
  6781. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6782. }
  6783. const boundingSphere = this.boundingSphere;
  6784. if ( boundingSphere !== null ) {
  6785. data.data.boundingSphere = {
  6786. center: boundingSphere.center.toArray(),
  6787. radius: boundingSphere.radius
  6788. };
  6789. }
  6790. return data;
  6791. }
  6792. clone() {
  6793. return new this.constructor().copy( this );
  6794. }
  6795. copy( source ) {
  6796. // reset
  6797. this.index = null;
  6798. this.attributes = {};
  6799. this.morphAttributes = {};
  6800. this.groups = [];
  6801. this.boundingBox = null;
  6802. this.boundingSphere = null;
  6803. // used for storing cloned, shared data
  6804. const data = {};
  6805. // name
  6806. this.name = source.name;
  6807. // index
  6808. const index = source.index;
  6809. if ( index !== null ) {
  6810. this.setIndex( index.clone( data ) );
  6811. }
  6812. // attributes
  6813. const attributes = source.attributes;
  6814. for ( const name in attributes ) {
  6815. const attribute = attributes[ name ];
  6816. this.setAttribute( name, attribute.clone( data ) );
  6817. }
  6818. // morph attributes
  6819. const morphAttributes = source.morphAttributes;
  6820. for ( const name in morphAttributes ) {
  6821. const array = [];
  6822. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6823. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6824. array.push( morphAttribute[ i ].clone( data ) );
  6825. }
  6826. this.morphAttributes[ name ] = array;
  6827. }
  6828. this.morphTargetsRelative = source.morphTargetsRelative;
  6829. // groups
  6830. const groups = source.groups;
  6831. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6832. const group = groups[ i ];
  6833. this.addGroup( group.start, group.count, group.materialIndex );
  6834. }
  6835. // bounding box
  6836. const boundingBox = source.boundingBox;
  6837. if ( boundingBox !== null ) {
  6838. this.boundingBox = boundingBox.clone();
  6839. }
  6840. // bounding sphere
  6841. const boundingSphere = source.boundingSphere;
  6842. if ( boundingSphere !== null ) {
  6843. this.boundingSphere = boundingSphere.clone();
  6844. }
  6845. // draw range
  6846. this.drawRange.start = source.drawRange.start;
  6847. this.drawRange.count = source.drawRange.count;
  6848. // user data
  6849. this.userData = source.userData;
  6850. return this;
  6851. }
  6852. dispose() {
  6853. this.dispatchEvent( { type: 'dispose' } );
  6854. }
  6855. }
  6856. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6857. const _ray$3 = /*@__PURE__*/ new Ray();
  6858. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6859. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6860. const _vA$1 = /*@__PURE__*/ new Vector3();
  6861. const _vB$1 = /*@__PURE__*/ new Vector3();
  6862. const _vC$1 = /*@__PURE__*/ new Vector3();
  6863. const _tempA = /*@__PURE__*/ new Vector3();
  6864. const _morphA = /*@__PURE__*/ new Vector3();
  6865. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6866. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6867. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6868. const _normalA = /*@__PURE__*/ new Vector3();
  6869. const _normalB = /*@__PURE__*/ new Vector3();
  6870. const _normalC = /*@__PURE__*/ new Vector3();
  6871. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6872. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6873. class Mesh extends Object3D {
  6874. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6875. super();
  6876. this.isMesh = true;
  6877. this.type = 'Mesh';
  6878. this.geometry = geometry;
  6879. this.material = material;
  6880. this.updateMorphTargets();
  6881. }
  6882. copy( source, recursive ) {
  6883. super.copy( source, recursive );
  6884. if ( source.morphTargetInfluences !== undefined ) {
  6885. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6886. }
  6887. if ( source.morphTargetDictionary !== undefined ) {
  6888. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6889. }
  6890. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6891. this.geometry = source.geometry;
  6892. return this;
  6893. }
  6894. updateMorphTargets() {
  6895. const geometry = this.geometry;
  6896. const morphAttributes = geometry.morphAttributes;
  6897. const keys = Object.keys( morphAttributes );
  6898. if ( keys.length > 0 ) {
  6899. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6900. if ( morphAttribute !== undefined ) {
  6901. this.morphTargetInfluences = [];
  6902. this.morphTargetDictionary = {};
  6903. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6904. const name = morphAttribute[ m ].name || String( m );
  6905. this.morphTargetInfluences.push( 0 );
  6906. this.morphTargetDictionary[ name ] = m;
  6907. }
  6908. }
  6909. }
  6910. }
  6911. getVertexPosition( index, target ) {
  6912. const geometry = this.geometry;
  6913. const position = geometry.attributes.position;
  6914. const morphPosition = geometry.morphAttributes.position;
  6915. const morphTargetsRelative = geometry.morphTargetsRelative;
  6916. target.fromBufferAttribute( position, index );
  6917. const morphInfluences = this.morphTargetInfluences;
  6918. if ( morphPosition && morphInfluences ) {
  6919. _morphA.set( 0, 0, 0 );
  6920. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6921. const influence = morphInfluences[ i ];
  6922. const morphAttribute = morphPosition[ i ];
  6923. if ( influence === 0 ) continue;
  6924. _tempA.fromBufferAttribute( morphAttribute, index );
  6925. if ( morphTargetsRelative ) {
  6926. _morphA.addScaledVector( _tempA, influence );
  6927. } else {
  6928. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6929. }
  6930. }
  6931. target.add( _morphA );
  6932. }
  6933. return target;
  6934. }
  6935. raycast( raycaster, intersects ) {
  6936. const geometry = this.geometry;
  6937. const material = this.material;
  6938. const matrixWorld = this.matrixWorld;
  6939. if ( material === undefined ) return;
  6940. // test with bounding sphere in world space
  6941. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6942. _sphere$6.copy( geometry.boundingSphere );
  6943. _sphere$6.applyMatrix4( matrixWorld );
  6944. // check distance from ray origin to bounding sphere
  6945. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6946. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6947. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6948. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6949. }
  6950. // convert ray to local space of mesh
  6951. _inverseMatrix$3.copy( matrixWorld ).invert();
  6952. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6953. // test with bounding box in local space
  6954. if ( geometry.boundingBox !== null ) {
  6955. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6956. }
  6957. // test for intersections with geometry
  6958. this._computeIntersections( raycaster, intersects, _ray$3 );
  6959. }
  6960. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6961. let intersection;
  6962. const geometry = this.geometry;
  6963. const material = this.material;
  6964. const index = geometry.index;
  6965. const position = geometry.attributes.position;
  6966. const uv = geometry.attributes.uv;
  6967. const uv1 = geometry.attributes.uv1;
  6968. const normal = geometry.attributes.normal;
  6969. const groups = geometry.groups;
  6970. const drawRange = geometry.drawRange;
  6971. if ( index !== null ) {
  6972. // indexed buffer geometry
  6973. if ( Array.isArray( material ) ) {
  6974. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6975. const group = groups[ i ];
  6976. const groupMaterial = material[ group.materialIndex ];
  6977. const start = Math.max( group.start, drawRange.start );
  6978. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6979. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6980. const a = index.getX( j );
  6981. const b = index.getX( j + 1 );
  6982. const c = index.getX( j + 2 );
  6983. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6984. if ( intersection ) {
  6985. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6986. intersection.face.materialIndex = group.materialIndex;
  6987. intersects.push( intersection );
  6988. }
  6989. }
  6990. }
  6991. } else {
  6992. const start = Math.max( 0, drawRange.start );
  6993. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6994. for ( let i = start, il = end; i < il; i += 3 ) {
  6995. const a = index.getX( i );
  6996. const b = index.getX( i + 1 );
  6997. const c = index.getX( i + 2 );
  6998. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6999. if ( intersection ) {
  7000. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7001. intersects.push( intersection );
  7002. }
  7003. }
  7004. }
  7005. } else if ( position !== undefined ) {
  7006. // non-indexed buffer geometry
  7007. if ( Array.isArray( material ) ) {
  7008. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7009. const group = groups[ i ];
  7010. const groupMaterial = material[ group.materialIndex ];
  7011. const start = Math.max( group.start, drawRange.start );
  7012. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7013. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7014. const a = j;
  7015. const b = j + 1;
  7016. const c = j + 2;
  7017. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7018. if ( intersection ) {
  7019. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7020. intersection.face.materialIndex = group.materialIndex;
  7021. intersects.push( intersection );
  7022. }
  7023. }
  7024. }
  7025. } else {
  7026. const start = Math.max( 0, drawRange.start );
  7027. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7028. for ( let i = start, il = end; i < il; i += 3 ) {
  7029. const a = i;
  7030. const b = i + 1;
  7031. const c = i + 2;
  7032. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7033. if ( intersection ) {
  7034. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7035. intersects.push( intersection );
  7036. }
  7037. }
  7038. }
  7039. }
  7040. }
  7041. }
  7042. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7043. let intersect;
  7044. if ( material.side === BackSide ) {
  7045. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7046. } else {
  7047. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7048. }
  7049. if ( intersect === null ) return null;
  7050. _intersectionPointWorld.copy( point );
  7051. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7052. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7053. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7054. return {
  7055. distance: distance,
  7056. point: _intersectionPointWorld.clone(),
  7057. object: object
  7058. };
  7059. }
  7060. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7061. object.getVertexPosition( a, _vA$1 );
  7062. object.getVertexPosition( b, _vB$1 );
  7063. object.getVertexPosition( c, _vC$1 );
  7064. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7065. if ( intersection ) {
  7066. if ( uv ) {
  7067. _uvA$1.fromBufferAttribute( uv, a );
  7068. _uvB$1.fromBufferAttribute( uv, b );
  7069. _uvC$1.fromBufferAttribute( uv, c );
  7070. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7071. }
  7072. if ( uv1 ) {
  7073. _uvA$1.fromBufferAttribute( uv1, a );
  7074. _uvB$1.fromBufferAttribute( uv1, b );
  7075. _uvC$1.fromBufferAttribute( uv1, c );
  7076. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7077. }
  7078. if ( normal ) {
  7079. _normalA.fromBufferAttribute( normal, a );
  7080. _normalB.fromBufferAttribute( normal, b );
  7081. _normalC.fromBufferAttribute( normal, c );
  7082. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7083. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7084. intersection.normal.multiplyScalar( - 1 );
  7085. }
  7086. }
  7087. const face = {
  7088. a: a,
  7089. b: b,
  7090. c: c,
  7091. normal: new Vector3(),
  7092. materialIndex: 0
  7093. };
  7094. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7095. intersection.face = face;
  7096. }
  7097. return intersection;
  7098. }
  7099. class BoxGeometry extends BufferGeometry {
  7100. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7101. super();
  7102. this.type = 'BoxGeometry';
  7103. this.parameters = {
  7104. width: width,
  7105. height: height,
  7106. depth: depth,
  7107. widthSegments: widthSegments,
  7108. heightSegments: heightSegments,
  7109. depthSegments: depthSegments
  7110. };
  7111. const scope = this;
  7112. // segments
  7113. widthSegments = Math.floor( widthSegments );
  7114. heightSegments = Math.floor( heightSegments );
  7115. depthSegments = Math.floor( depthSegments );
  7116. // buffers
  7117. const indices = [];
  7118. const vertices = [];
  7119. const normals = [];
  7120. const uvs = [];
  7121. // helper variables
  7122. let numberOfVertices = 0;
  7123. let groupStart = 0;
  7124. // build each side of the box geometry
  7125. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7126. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7127. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7128. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7129. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7130. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7131. // build geometry
  7132. this.setIndex( indices );
  7133. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7134. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7135. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7136. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7137. const segmentWidth = width / gridX;
  7138. const segmentHeight = height / gridY;
  7139. const widthHalf = width / 2;
  7140. const heightHalf = height / 2;
  7141. const depthHalf = depth / 2;
  7142. const gridX1 = gridX + 1;
  7143. const gridY1 = gridY + 1;
  7144. let vertexCounter = 0;
  7145. let groupCount = 0;
  7146. const vector = new Vector3();
  7147. // generate vertices, normals and uvs
  7148. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7149. const y = iy * segmentHeight - heightHalf;
  7150. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7151. const x = ix * segmentWidth - widthHalf;
  7152. // set values to correct vector component
  7153. vector[ u ] = x * udir;
  7154. vector[ v ] = y * vdir;
  7155. vector[ w ] = depthHalf;
  7156. // now apply vector to vertex buffer
  7157. vertices.push( vector.x, vector.y, vector.z );
  7158. // set values to correct vector component
  7159. vector[ u ] = 0;
  7160. vector[ v ] = 0;
  7161. vector[ w ] = depth > 0 ? 1 : - 1;
  7162. // now apply vector to normal buffer
  7163. normals.push( vector.x, vector.y, vector.z );
  7164. // uvs
  7165. uvs.push( ix / gridX );
  7166. uvs.push( 1 - ( iy / gridY ) );
  7167. // counters
  7168. vertexCounter += 1;
  7169. }
  7170. }
  7171. // indices
  7172. // 1. you need three indices to draw a single face
  7173. // 2. a single segment consists of two faces
  7174. // 3. so we need to generate six (2*3) indices per segment
  7175. for ( let iy = 0; iy < gridY; iy ++ ) {
  7176. for ( let ix = 0; ix < gridX; ix ++ ) {
  7177. const a = numberOfVertices + ix + gridX1 * iy;
  7178. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7179. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7180. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7181. // faces
  7182. indices.push( a, b, d );
  7183. indices.push( b, c, d );
  7184. // increase counter
  7185. groupCount += 6;
  7186. }
  7187. }
  7188. // add a group to the geometry. this will ensure multi material support
  7189. scope.addGroup( groupStart, groupCount, materialIndex );
  7190. // calculate new start value for groups
  7191. groupStart += groupCount;
  7192. // update total number of vertices
  7193. numberOfVertices += vertexCounter;
  7194. }
  7195. }
  7196. copy( source ) {
  7197. super.copy( source );
  7198. this.parameters = Object.assign( {}, source.parameters );
  7199. return this;
  7200. }
  7201. static fromJSON( data ) {
  7202. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7203. }
  7204. }
  7205. /**
  7206. * Uniform Utilities
  7207. */
  7208. function cloneUniforms( src ) {
  7209. const dst = {};
  7210. for ( const u in src ) {
  7211. dst[ u ] = {};
  7212. for ( const p in src[ u ] ) {
  7213. const property = src[ u ][ p ];
  7214. if ( property && ( property.isColor ||
  7215. property.isMatrix3 || property.isMatrix4 ||
  7216. property.isVector2 || property.isVector3 || property.isVector4 ||
  7217. property.isTexture || property.isQuaternion ) ) {
  7218. if ( property.isRenderTargetTexture ) {
  7219. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7220. dst[ u ][ p ] = null;
  7221. } else {
  7222. dst[ u ][ p ] = property.clone();
  7223. }
  7224. } else if ( Array.isArray( property ) ) {
  7225. dst[ u ][ p ] = property.slice();
  7226. } else {
  7227. dst[ u ][ p ] = property;
  7228. }
  7229. }
  7230. }
  7231. return dst;
  7232. }
  7233. function cloneUniformsGroups( src ) {
  7234. const dst = [];
  7235. for ( let u = 0; u < src.length; u ++ ) {
  7236. dst.push( src[ u ].clone() );
  7237. }
  7238. return dst;
  7239. }
  7240. var default_vertex = /* glsl */`
  7241. void main() {
  7242. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7243. }
  7244. `;
  7245. var default_fragment = /* glsl */`
  7246. void main() {
  7247. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7248. }
  7249. `;
  7250. class ShaderMaterial extends Material {
  7251. constructor( parameters ) {
  7252. super();
  7253. this.isShaderMaterial = true;
  7254. this.type = 'ShaderMaterial';
  7255. this.defines = {};
  7256. this.uniforms = {};
  7257. this.uniformsGroups = [];
  7258. this.vertexShader = default_vertex;
  7259. this.fragmentShader = default_fragment;
  7260. this.linewidth = 1;
  7261. this.wireframe = false;
  7262. this.wireframeLinewidth = 1;
  7263. this.fog = false; // set to use scene fog
  7264. this.lights = false; // set to use scene lights
  7265. this.clipping = false; // set to use user-defined clipping planes
  7266. this.forceSinglePass = true;
  7267. this.extensions = {
  7268. clipCullDistance: false, // set to use vertex shader clipping
  7269. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7270. };
  7271. // When rendered geometry doesn't include these attributes but the material does,
  7272. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7273. this.defaultAttributeValues = {
  7274. 'color': [ 1, 1, 1 ],
  7275. 'uv': [ 0, 0 ],
  7276. 'uv1': [ 0, 0 ]
  7277. };
  7278. this.index0AttributeName = undefined;
  7279. this.uniformsNeedUpdate = false;
  7280. this.glslVersion = null;
  7281. if ( parameters !== undefined ) {
  7282. this.setValues( parameters );
  7283. }
  7284. }
  7285. copy( source ) {
  7286. super.copy( source );
  7287. this.fragmentShader = source.fragmentShader;
  7288. this.vertexShader = source.vertexShader;
  7289. this.uniforms = cloneUniforms( source.uniforms );
  7290. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7291. this.defines = Object.assign( {}, source.defines );
  7292. this.wireframe = source.wireframe;
  7293. this.wireframeLinewidth = source.wireframeLinewidth;
  7294. this.fog = source.fog;
  7295. this.lights = source.lights;
  7296. this.clipping = source.clipping;
  7297. this.extensions = Object.assign( {}, source.extensions );
  7298. this.glslVersion = source.glslVersion;
  7299. return this;
  7300. }
  7301. toJSON( meta ) {
  7302. const data = super.toJSON( meta );
  7303. data.glslVersion = this.glslVersion;
  7304. data.uniforms = {};
  7305. for ( const name in this.uniforms ) {
  7306. const uniform = this.uniforms[ name ];
  7307. const value = uniform.value;
  7308. if ( value && value.isTexture ) {
  7309. data.uniforms[ name ] = {
  7310. type: 't',
  7311. value: value.toJSON( meta ).uuid
  7312. };
  7313. } else if ( value && value.isColor ) {
  7314. data.uniforms[ name ] = {
  7315. type: 'c',
  7316. value: value.getHex()
  7317. };
  7318. } else if ( value && value.isVector2 ) {
  7319. data.uniforms[ name ] = {
  7320. type: 'v2',
  7321. value: value.toArray()
  7322. };
  7323. } else if ( value && value.isVector3 ) {
  7324. data.uniforms[ name ] = {
  7325. type: 'v3',
  7326. value: value.toArray()
  7327. };
  7328. } else if ( value && value.isVector4 ) {
  7329. data.uniforms[ name ] = {
  7330. type: 'v4',
  7331. value: value.toArray()
  7332. };
  7333. } else if ( value && value.isMatrix3 ) {
  7334. data.uniforms[ name ] = {
  7335. type: 'm3',
  7336. value: value.toArray()
  7337. };
  7338. } else if ( value && value.isMatrix4 ) {
  7339. data.uniforms[ name ] = {
  7340. type: 'm4',
  7341. value: value.toArray()
  7342. };
  7343. } else {
  7344. data.uniforms[ name ] = {
  7345. value: value
  7346. };
  7347. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7348. }
  7349. }
  7350. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7351. data.vertexShader = this.vertexShader;
  7352. data.fragmentShader = this.fragmentShader;
  7353. data.lights = this.lights;
  7354. data.clipping = this.clipping;
  7355. const extensions = {};
  7356. for ( const key in this.extensions ) {
  7357. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7358. }
  7359. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7360. return data;
  7361. }
  7362. }
  7363. class Camera extends Object3D {
  7364. constructor() {
  7365. super();
  7366. this.isCamera = true;
  7367. this.type = 'Camera';
  7368. this.matrixWorldInverse = new Matrix4();
  7369. this.projectionMatrix = new Matrix4();
  7370. this.projectionMatrixInverse = new Matrix4();
  7371. this.coordinateSystem = WebGLCoordinateSystem;
  7372. }
  7373. copy( source, recursive ) {
  7374. super.copy( source, recursive );
  7375. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7376. this.projectionMatrix.copy( source.projectionMatrix );
  7377. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7378. this.coordinateSystem = source.coordinateSystem;
  7379. return this;
  7380. }
  7381. getWorldDirection( target ) {
  7382. return super.getWorldDirection( target ).negate();
  7383. }
  7384. updateMatrixWorld( force ) {
  7385. super.updateMatrixWorld( force );
  7386. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7387. }
  7388. updateWorldMatrix( updateParents, updateChildren ) {
  7389. super.updateWorldMatrix( updateParents, updateChildren );
  7390. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7391. }
  7392. clone() {
  7393. return new this.constructor().copy( this );
  7394. }
  7395. }
  7396. const _v3$1 = /*@__PURE__*/ new Vector3();
  7397. const _minTarget = /*@__PURE__*/ new Vector2();
  7398. const _maxTarget = /*@__PURE__*/ new Vector2();
  7399. class PerspectiveCamera extends Camera {
  7400. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7401. super();
  7402. this.isPerspectiveCamera = true;
  7403. this.type = 'PerspectiveCamera';
  7404. this.fov = fov;
  7405. this.zoom = 1;
  7406. this.near = near;
  7407. this.far = far;
  7408. this.focus = 10;
  7409. this.aspect = aspect;
  7410. this.view = null;
  7411. this.filmGauge = 35; // width of the film (default in millimeters)
  7412. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7413. this.updateProjectionMatrix();
  7414. }
  7415. copy( source, recursive ) {
  7416. super.copy( source, recursive );
  7417. this.fov = source.fov;
  7418. this.zoom = source.zoom;
  7419. this.near = source.near;
  7420. this.far = source.far;
  7421. this.focus = source.focus;
  7422. this.aspect = source.aspect;
  7423. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7424. this.filmGauge = source.filmGauge;
  7425. this.filmOffset = source.filmOffset;
  7426. return this;
  7427. }
  7428. /**
  7429. * Sets the FOV by focal length in respect to the current .filmGauge.
  7430. *
  7431. * The default film gauge is 35, so that the focal length can be specified for
  7432. * a 35mm (full frame) camera.
  7433. *
  7434. * Values for focal length and film gauge must have the same unit.
  7435. */
  7436. setFocalLength( focalLength ) {
  7437. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7438. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7439. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7440. this.updateProjectionMatrix();
  7441. }
  7442. /**
  7443. * Calculates the focal length from the current .fov and .filmGauge.
  7444. */
  7445. getFocalLength() {
  7446. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7447. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7448. }
  7449. getEffectiveFOV() {
  7450. return RAD2DEG * 2 * Math.atan(
  7451. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7452. }
  7453. getFilmWidth() {
  7454. // film not completely covered in portrait format (aspect < 1)
  7455. return this.filmGauge * Math.min( this.aspect, 1 );
  7456. }
  7457. getFilmHeight() {
  7458. // film not completely covered in landscape format (aspect > 1)
  7459. return this.filmGauge / Math.max( this.aspect, 1 );
  7460. }
  7461. /**
  7462. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7463. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7464. */
  7465. getViewBounds( distance, minTarget, maxTarget ) {
  7466. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7467. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7468. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7469. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7470. }
  7471. /**
  7472. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7473. * Copies the result into the target Vector2, where x is width and y is height.
  7474. */
  7475. getViewSize( distance, target ) {
  7476. this.getViewBounds( distance, _minTarget, _maxTarget );
  7477. return target.subVectors( _maxTarget, _minTarget );
  7478. }
  7479. /**
  7480. * Sets an offset in a larger frustum. This is useful for multi-window or
  7481. * multi-monitor/multi-machine setups.
  7482. *
  7483. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7484. * the monitors are in grid like this
  7485. *
  7486. * +---+---+---+
  7487. * | A | B | C |
  7488. * +---+---+---+
  7489. * | D | E | F |
  7490. * +---+---+---+
  7491. *
  7492. * then for each monitor you would call it like this
  7493. *
  7494. * const w = 1920;
  7495. * const h = 1080;
  7496. * const fullWidth = w * 3;
  7497. * const fullHeight = h * 2;
  7498. *
  7499. * --A--
  7500. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7501. * --B--
  7502. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7503. * --C--
  7504. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7505. * --D--
  7506. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7507. * --E--
  7508. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7509. * --F--
  7510. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7511. *
  7512. * Note there is no reason monitors have to be the same size or in a grid.
  7513. */
  7514. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7515. this.aspect = fullWidth / fullHeight;
  7516. if ( this.view === null ) {
  7517. this.view = {
  7518. enabled: true,
  7519. fullWidth: 1,
  7520. fullHeight: 1,
  7521. offsetX: 0,
  7522. offsetY: 0,
  7523. width: 1,
  7524. height: 1
  7525. };
  7526. }
  7527. this.view.enabled = true;
  7528. this.view.fullWidth = fullWidth;
  7529. this.view.fullHeight = fullHeight;
  7530. this.view.offsetX = x;
  7531. this.view.offsetY = y;
  7532. this.view.width = width;
  7533. this.view.height = height;
  7534. this.updateProjectionMatrix();
  7535. }
  7536. clearViewOffset() {
  7537. if ( this.view !== null ) {
  7538. this.view.enabled = false;
  7539. }
  7540. this.updateProjectionMatrix();
  7541. }
  7542. updateProjectionMatrix() {
  7543. const near = this.near;
  7544. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7545. let height = 2 * top;
  7546. let width = this.aspect * height;
  7547. let left = - 0.5 * width;
  7548. const view = this.view;
  7549. if ( this.view !== null && this.view.enabled ) {
  7550. const fullWidth = view.fullWidth,
  7551. fullHeight = view.fullHeight;
  7552. left += view.offsetX * width / fullWidth;
  7553. top -= view.offsetY * height / fullHeight;
  7554. width *= view.width / fullWidth;
  7555. height *= view.height / fullHeight;
  7556. }
  7557. const skew = this.filmOffset;
  7558. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7559. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7560. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7561. }
  7562. toJSON( meta ) {
  7563. const data = super.toJSON( meta );
  7564. data.object.fov = this.fov;
  7565. data.object.zoom = this.zoom;
  7566. data.object.near = this.near;
  7567. data.object.far = this.far;
  7568. data.object.focus = this.focus;
  7569. data.object.aspect = this.aspect;
  7570. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7571. data.object.filmGauge = this.filmGauge;
  7572. data.object.filmOffset = this.filmOffset;
  7573. return data;
  7574. }
  7575. }
  7576. const fov = - 90; // negative fov is not an error
  7577. const aspect = 1;
  7578. class CubeCamera extends Object3D {
  7579. constructor( near, far, renderTarget ) {
  7580. super();
  7581. this.type = 'CubeCamera';
  7582. this.renderTarget = renderTarget;
  7583. this.coordinateSystem = null;
  7584. this.activeMipmapLevel = 0;
  7585. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7586. cameraPX.layers = this.layers;
  7587. this.add( cameraPX );
  7588. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7589. cameraNX.layers = this.layers;
  7590. this.add( cameraNX );
  7591. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7592. cameraPY.layers = this.layers;
  7593. this.add( cameraPY );
  7594. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7595. cameraNY.layers = this.layers;
  7596. this.add( cameraNY );
  7597. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7598. cameraPZ.layers = this.layers;
  7599. this.add( cameraPZ );
  7600. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7601. cameraNZ.layers = this.layers;
  7602. this.add( cameraNZ );
  7603. }
  7604. updateCoordinateSystem() {
  7605. const coordinateSystem = this.coordinateSystem;
  7606. const cameras = this.children.concat();
  7607. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7608. for ( const camera of cameras ) this.remove( camera );
  7609. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7610. cameraPX.up.set( 0, 1, 0 );
  7611. cameraPX.lookAt( 1, 0, 0 );
  7612. cameraNX.up.set( 0, 1, 0 );
  7613. cameraNX.lookAt( - 1, 0, 0 );
  7614. cameraPY.up.set( 0, 0, - 1 );
  7615. cameraPY.lookAt( 0, 1, 0 );
  7616. cameraNY.up.set( 0, 0, 1 );
  7617. cameraNY.lookAt( 0, - 1, 0 );
  7618. cameraPZ.up.set( 0, 1, 0 );
  7619. cameraPZ.lookAt( 0, 0, 1 );
  7620. cameraNZ.up.set( 0, 1, 0 );
  7621. cameraNZ.lookAt( 0, 0, - 1 );
  7622. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7623. cameraPX.up.set( 0, - 1, 0 );
  7624. cameraPX.lookAt( - 1, 0, 0 );
  7625. cameraNX.up.set( 0, - 1, 0 );
  7626. cameraNX.lookAt( 1, 0, 0 );
  7627. cameraPY.up.set( 0, 0, 1 );
  7628. cameraPY.lookAt( 0, 1, 0 );
  7629. cameraNY.up.set( 0, 0, - 1 );
  7630. cameraNY.lookAt( 0, - 1, 0 );
  7631. cameraPZ.up.set( 0, - 1, 0 );
  7632. cameraPZ.lookAt( 0, 0, 1 );
  7633. cameraNZ.up.set( 0, - 1, 0 );
  7634. cameraNZ.lookAt( 0, 0, - 1 );
  7635. } else {
  7636. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7637. }
  7638. for ( const camera of cameras ) {
  7639. this.add( camera );
  7640. camera.updateMatrixWorld();
  7641. }
  7642. }
  7643. update( renderer, scene ) {
  7644. if ( this.parent === null ) this.updateMatrixWorld();
  7645. const { renderTarget, activeMipmapLevel } = this;
  7646. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7647. this.coordinateSystem = renderer.coordinateSystem;
  7648. this.updateCoordinateSystem();
  7649. }
  7650. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7651. const currentRenderTarget = renderer.getRenderTarget();
  7652. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7653. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7654. const currentXrEnabled = renderer.xr.enabled;
  7655. renderer.xr.enabled = false;
  7656. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7657. renderTarget.texture.generateMipmaps = false;
  7658. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7659. renderer.render( scene, cameraPX );
  7660. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7661. renderer.render( scene, cameraNX );
  7662. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7663. renderer.render( scene, cameraPY );
  7664. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7665. renderer.render( scene, cameraNY );
  7666. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7667. renderer.render( scene, cameraPZ );
  7668. // mipmaps are generated during the last call of render()
  7669. // at this point, all sides of the cube render target are defined
  7670. renderTarget.texture.generateMipmaps = generateMipmaps;
  7671. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7672. renderer.render( scene, cameraNZ );
  7673. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7674. renderer.xr.enabled = currentXrEnabled;
  7675. renderTarget.texture.needsPMREMUpdate = true;
  7676. }
  7677. }
  7678. class CubeTexture extends Texture {
  7679. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7680. images = images !== undefined ? images : [];
  7681. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7682. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7683. this.isCubeTexture = true;
  7684. this.flipY = false;
  7685. }
  7686. get images() {
  7687. return this.image;
  7688. }
  7689. set images( value ) {
  7690. this.image = value;
  7691. }
  7692. }
  7693. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7694. constructor( size = 1, options = {} ) {
  7695. super( size, size, options );
  7696. this.isWebGLCubeRenderTarget = true;
  7697. const image = { width: size, height: size, depth: 1 };
  7698. const images = [ image, image, image, image, image, image ];
  7699. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7700. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7701. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7702. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7703. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7704. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7705. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7706. this.texture.isRenderTargetTexture = true;
  7707. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7708. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7709. }
  7710. fromEquirectangularTexture( renderer, texture ) {
  7711. this.texture.type = texture.type;
  7712. this.texture.colorSpace = texture.colorSpace;
  7713. this.texture.generateMipmaps = texture.generateMipmaps;
  7714. this.texture.minFilter = texture.minFilter;
  7715. this.texture.magFilter = texture.magFilter;
  7716. const shader = {
  7717. uniforms: {
  7718. tEquirect: { value: null },
  7719. },
  7720. vertexShader: /* glsl */`
  7721. varying vec3 vWorldDirection;
  7722. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7723. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7724. }
  7725. void main() {
  7726. vWorldDirection = transformDirection( position, modelMatrix );
  7727. #include <begin_vertex>
  7728. #include <project_vertex>
  7729. }
  7730. `,
  7731. fragmentShader: /* glsl */`
  7732. uniform sampler2D tEquirect;
  7733. varying vec3 vWorldDirection;
  7734. #include <common>
  7735. void main() {
  7736. vec3 direction = normalize( vWorldDirection );
  7737. vec2 sampleUV = equirectUv( direction );
  7738. gl_FragColor = texture2D( tEquirect, sampleUV );
  7739. }
  7740. `
  7741. };
  7742. const geometry = new BoxGeometry( 5, 5, 5 );
  7743. const material = new ShaderMaterial( {
  7744. name: 'CubemapFromEquirect',
  7745. uniforms: cloneUniforms( shader.uniforms ),
  7746. vertexShader: shader.vertexShader,
  7747. fragmentShader: shader.fragmentShader,
  7748. side: BackSide,
  7749. blending: NoBlending
  7750. } );
  7751. material.uniforms.tEquirect.value = texture;
  7752. const mesh = new Mesh( geometry, material );
  7753. const currentMinFilter = texture.minFilter;
  7754. // Avoid blurred poles
  7755. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7756. const camera = new CubeCamera( 1, 10, this );
  7757. camera.update( renderer, mesh );
  7758. texture.minFilter = currentMinFilter;
  7759. mesh.geometry.dispose();
  7760. mesh.material.dispose();
  7761. return this;
  7762. }
  7763. clear( renderer, color, depth, stencil ) {
  7764. const currentRenderTarget = renderer.getRenderTarget();
  7765. for ( let i = 0; i < 6; i ++ ) {
  7766. renderer.setRenderTarget( this, i );
  7767. renderer.clear( color, depth, stencil );
  7768. }
  7769. renderer.setRenderTarget( currentRenderTarget );
  7770. }
  7771. }
  7772. class FogExp2 {
  7773. constructor( color, density = 0.00025 ) {
  7774. this.isFogExp2 = true;
  7775. this.name = '';
  7776. this.color = new Color( color );
  7777. this.density = density;
  7778. }
  7779. clone() {
  7780. return new FogExp2( this.color, this.density );
  7781. }
  7782. toJSON( /* meta */ ) {
  7783. return {
  7784. type: 'FogExp2',
  7785. name: this.name,
  7786. color: this.color.getHex(),
  7787. density: this.density
  7788. };
  7789. }
  7790. }
  7791. class Fog {
  7792. constructor( color, near = 1, far = 1000 ) {
  7793. this.isFog = true;
  7794. this.name = '';
  7795. this.color = new Color( color );
  7796. this.near = near;
  7797. this.far = far;
  7798. }
  7799. clone() {
  7800. return new Fog( this.color, this.near, this.far );
  7801. }
  7802. toJSON( /* meta */ ) {
  7803. return {
  7804. type: 'Fog',
  7805. name: this.name,
  7806. color: this.color.getHex(),
  7807. near: this.near,
  7808. far: this.far
  7809. };
  7810. }
  7811. }
  7812. class Scene extends Object3D {
  7813. constructor() {
  7814. super();
  7815. this.isScene = true;
  7816. this.type = 'Scene';
  7817. this.background = null;
  7818. this.environment = null;
  7819. this.fog = null;
  7820. this.backgroundBlurriness = 0;
  7821. this.backgroundIntensity = 1;
  7822. this.backgroundRotation = new Euler();
  7823. this.environmentIntensity = 1;
  7824. this.environmentRotation = new Euler();
  7825. this.overrideMaterial = null;
  7826. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7827. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7828. }
  7829. }
  7830. copy( source, recursive ) {
  7831. super.copy( source, recursive );
  7832. if ( source.background !== null ) this.background = source.background.clone();
  7833. if ( source.environment !== null ) this.environment = source.environment.clone();
  7834. if ( source.fog !== null ) this.fog = source.fog.clone();
  7835. this.backgroundBlurriness = source.backgroundBlurriness;
  7836. this.backgroundIntensity = source.backgroundIntensity;
  7837. this.backgroundRotation.copy( source.backgroundRotation );
  7838. this.environmentIntensity = source.environmentIntensity;
  7839. this.environmentRotation.copy( source.environmentRotation );
  7840. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7841. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7842. return this;
  7843. }
  7844. toJSON( meta ) {
  7845. const data = super.toJSON( meta );
  7846. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7847. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7848. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7849. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7850. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7851. data.object.environmentRotation = this.environmentRotation.toArray();
  7852. return data;
  7853. }
  7854. }
  7855. class InterleavedBuffer {
  7856. constructor( array, stride ) {
  7857. this.isInterleavedBuffer = true;
  7858. this.array = array;
  7859. this.stride = stride;
  7860. this.count = array !== undefined ? array.length / stride : 0;
  7861. this.usage = StaticDrawUsage;
  7862. this.updateRanges = [];
  7863. this.version = 0;
  7864. this.uuid = generateUUID();
  7865. }
  7866. onUploadCallback() {}
  7867. set needsUpdate( value ) {
  7868. if ( value === true ) this.version ++;
  7869. }
  7870. setUsage( value ) {
  7871. this.usage = value;
  7872. return this;
  7873. }
  7874. addUpdateRange( start, count ) {
  7875. this.updateRanges.push( { start, count } );
  7876. }
  7877. clearUpdateRanges() {
  7878. this.updateRanges.length = 0;
  7879. }
  7880. copy( source ) {
  7881. this.array = new source.array.constructor( source.array );
  7882. this.count = source.count;
  7883. this.stride = source.stride;
  7884. this.usage = source.usage;
  7885. return this;
  7886. }
  7887. copyAt( index1, attribute, index2 ) {
  7888. index1 *= this.stride;
  7889. index2 *= attribute.stride;
  7890. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7891. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7892. }
  7893. return this;
  7894. }
  7895. set( value, offset = 0 ) {
  7896. this.array.set( value, offset );
  7897. return this;
  7898. }
  7899. clone( data ) {
  7900. if ( data.arrayBuffers === undefined ) {
  7901. data.arrayBuffers = {};
  7902. }
  7903. if ( this.array.buffer._uuid === undefined ) {
  7904. this.array.buffer._uuid = generateUUID();
  7905. }
  7906. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7907. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7908. }
  7909. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7910. const ib = new this.constructor( array, this.stride );
  7911. ib.setUsage( this.usage );
  7912. return ib;
  7913. }
  7914. onUpload( callback ) {
  7915. this.onUploadCallback = callback;
  7916. return this;
  7917. }
  7918. toJSON( data ) {
  7919. if ( data.arrayBuffers === undefined ) {
  7920. data.arrayBuffers = {};
  7921. }
  7922. // generate UUID for array buffer if necessary
  7923. if ( this.array.buffer._uuid === undefined ) {
  7924. this.array.buffer._uuid = generateUUID();
  7925. }
  7926. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7927. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7928. }
  7929. //
  7930. return {
  7931. uuid: this.uuid,
  7932. buffer: this.array.buffer._uuid,
  7933. type: this.array.constructor.name,
  7934. stride: this.stride
  7935. };
  7936. }
  7937. }
  7938. const _vector$7 = /*@__PURE__*/ new Vector3();
  7939. class InterleavedBufferAttribute {
  7940. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7941. this.isInterleavedBufferAttribute = true;
  7942. this.name = '';
  7943. this.data = interleavedBuffer;
  7944. this.itemSize = itemSize;
  7945. this.offset = offset;
  7946. this.normalized = normalized;
  7947. }
  7948. get count() {
  7949. return this.data.count;
  7950. }
  7951. get array() {
  7952. return this.data.array;
  7953. }
  7954. set needsUpdate( value ) {
  7955. this.data.needsUpdate = value;
  7956. }
  7957. applyMatrix4( m ) {
  7958. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7959. _vector$7.fromBufferAttribute( this, i );
  7960. _vector$7.applyMatrix4( m );
  7961. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7962. }
  7963. return this;
  7964. }
  7965. applyNormalMatrix( m ) {
  7966. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7967. _vector$7.fromBufferAttribute( this, i );
  7968. _vector$7.applyNormalMatrix( m );
  7969. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7970. }
  7971. return this;
  7972. }
  7973. transformDirection( m ) {
  7974. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7975. _vector$7.fromBufferAttribute( this, i );
  7976. _vector$7.transformDirection( m );
  7977. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7978. }
  7979. return this;
  7980. }
  7981. getComponent( index, component ) {
  7982. let value = this.array[ index * this.data.stride + this.offset + component ];
  7983. if ( this.normalized ) value = denormalize( value, this.array );
  7984. return value;
  7985. }
  7986. setComponent( index, component, value ) {
  7987. if ( this.normalized ) value = normalize$1( value, this.array );
  7988. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  7989. return this;
  7990. }
  7991. setX( index, x ) {
  7992. if ( this.normalized ) x = normalize$1( x, this.array );
  7993. this.data.array[ index * this.data.stride + this.offset ] = x;
  7994. return this;
  7995. }
  7996. setY( index, y ) {
  7997. if ( this.normalized ) y = normalize$1( y, this.array );
  7998. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  7999. return this;
  8000. }
  8001. setZ( index, z ) {
  8002. if ( this.normalized ) z = normalize$1( z, this.array );
  8003. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8004. return this;
  8005. }
  8006. setW( index, w ) {
  8007. if ( this.normalized ) w = normalize$1( w, this.array );
  8008. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8009. return this;
  8010. }
  8011. getX( index ) {
  8012. let x = this.data.array[ index * this.data.stride + this.offset ];
  8013. if ( this.normalized ) x = denormalize( x, this.array );
  8014. return x;
  8015. }
  8016. getY( index ) {
  8017. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8018. if ( this.normalized ) y = denormalize( y, this.array );
  8019. return y;
  8020. }
  8021. getZ( index ) {
  8022. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8023. if ( this.normalized ) z = denormalize( z, this.array );
  8024. return z;
  8025. }
  8026. getW( index ) {
  8027. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8028. if ( this.normalized ) w = denormalize( w, this.array );
  8029. return w;
  8030. }
  8031. setXY( index, x, y ) {
  8032. index = index * this.data.stride + this.offset;
  8033. if ( this.normalized ) {
  8034. x = normalize$1( x, this.array );
  8035. y = normalize$1( y, this.array );
  8036. }
  8037. this.data.array[ index + 0 ] = x;
  8038. this.data.array[ index + 1 ] = y;
  8039. return this;
  8040. }
  8041. setXYZ( index, x, y, z ) {
  8042. index = index * this.data.stride + this.offset;
  8043. if ( this.normalized ) {
  8044. x = normalize$1( x, this.array );
  8045. y = normalize$1( y, this.array );
  8046. z = normalize$1( z, this.array );
  8047. }
  8048. this.data.array[ index + 0 ] = x;
  8049. this.data.array[ index + 1 ] = y;
  8050. this.data.array[ index + 2 ] = z;
  8051. return this;
  8052. }
  8053. setXYZW( index, x, y, z, w ) {
  8054. index = index * this.data.stride + this.offset;
  8055. if ( this.normalized ) {
  8056. x = normalize$1( x, this.array );
  8057. y = normalize$1( y, this.array );
  8058. z = normalize$1( z, this.array );
  8059. w = normalize$1( w, this.array );
  8060. }
  8061. this.data.array[ index + 0 ] = x;
  8062. this.data.array[ index + 1 ] = y;
  8063. this.data.array[ index + 2 ] = z;
  8064. this.data.array[ index + 3 ] = w;
  8065. return this;
  8066. }
  8067. clone( data ) {
  8068. if ( data === undefined ) {
  8069. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8070. const array = [];
  8071. for ( let i = 0; i < this.count; i ++ ) {
  8072. const index = i * this.data.stride + this.offset;
  8073. for ( let j = 0; j < this.itemSize; j ++ ) {
  8074. array.push( this.data.array[ index + j ] );
  8075. }
  8076. }
  8077. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8078. } else {
  8079. if ( data.interleavedBuffers === undefined ) {
  8080. data.interleavedBuffers = {};
  8081. }
  8082. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8083. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8084. }
  8085. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8086. }
  8087. }
  8088. toJSON( data ) {
  8089. if ( data === undefined ) {
  8090. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8091. const array = [];
  8092. for ( let i = 0; i < this.count; i ++ ) {
  8093. const index = i * this.data.stride + this.offset;
  8094. for ( let j = 0; j < this.itemSize; j ++ ) {
  8095. array.push( this.data.array[ index + j ] );
  8096. }
  8097. }
  8098. // de-interleave data and save it as an ordinary buffer attribute for now
  8099. return {
  8100. itemSize: this.itemSize,
  8101. type: this.array.constructor.name,
  8102. array: array,
  8103. normalized: this.normalized
  8104. };
  8105. } else {
  8106. // save as true interleaved attribute
  8107. if ( data.interleavedBuffers === undefined ) {
  8108. data.interleavedBuffers = {};
  8109. }
  8110. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8111. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8112. }
  8113. return {
  8114. isInterleavedBufferAttribute: true,
  8115. itemSize: this.itemSize,
  8116. data: this.data.uuid,
  8117. offset: this.offset,
  8118. normalized: this.normalized
  8119. };
  8120. }
  8121. }
  8122. }
  8123. class SpriteMaterial extends Material {
  8124. constructor( parameters ) {
  8125. super();
  8126. this.isSpriteMaterial = true;
  8127. this.type = 'SpriteMaterial';
  8128. this.color = new Color( 0xffffff );
  8129. this.map = null;
  8130. this.alphaMap = null;
  8131. this.rotation = 0;
  8132. this.sizeAttenuation = true;
  8133. this.transparent = true;
  8134. this.fog = true;
  8135. this.setValues( parameters );
  8136. }
  8137. copy( source ) {
  8138. super.copy( source );
  8139. this.color.copy( source.color );
  8140. this.map = source.map;
  8141. this.alphaMap = source.alphaMap;
  8142. this.rotation = source.rotation;
  8143. this.sizeAttenuation = source.sizeAttenuation;
  8144. this.fog = source.fog;
  8145. return this;
  8146. }
  8147. }
  8148. let _geometry$1;
  8149. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8150. const _worldScale = /*@__PURE__*/ new Vector3();
  8151. const _mvPosition = /*@__PURE__*/ new Vector3();
  8152. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8153. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8154. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8155. const _vA = /*@__PURE__*/ new Vector3();
  8156. const _vB = /*@__PURE__*/ new Vector3();
  8157. const _vC = /*@__PURE__*/ new Vector3();
  8158. const _uvA = /*@__PURE__*/ new Vector2();
  8159. const _uvB = /*@__PURE__*/ new Vector2();
  8160. const _uvC = /*@__PURE__*/ new Vector2();
  8161. class Sprite extends Object3D {
  8162. constructor( material = new SpriteMaterial() ) {
  8163. super();
  8164. this.isSprite = true;
  8165. this.type = 'Sprite';
  8166. if ( _geometry$1 === undefined ) {
  8167. _geometry$1 = new BufferGeometry();
  8168. const float32Array = new Float32Array( [
  8169. - 0.5, - 0.5, 0, 0, 0,
  8170. 0.5, - 0.5, 0, 1, 0,
  8171. 0.5, 0.5, 0, 1, 1,
  8172. - 0.5, 0.5, 0, 0, 1
  8173. ] );
  8174. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8175. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8176. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8177. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8178. }
  8179. this.geometry = _geometry$1;
  8180. this.material = material;
  8181. this.center = new Vector2( 0.5, 0.5 );
  8182. }
  8183. raycast( raycaster, intersects ) {
  8184. if ( raycaster.camera === null ) {
  8185. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8186. }
  8187. _worldScale.setFromMatrixScale( this.matrixWorld );
  8188. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8189. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8190. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8191. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8192. _worldScale.multiplyScalar( - _mvPosition.z );
  8193. }
  8194. const rotation = this.material.rotation;
  8195. let sin, cos;
  8196. if ( rotation !== 0 ) {
  8197. cos = Math.cos( rotation );
  8198. sin = Math.sin( rotation );
  8199. }
  8200. const center = this.center;
  8201. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8202. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8203. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8204. _uvA.set( 0, 0 );
  8205. _uvB.set( 1, 0 );
  8206. _uvC.set( 1, 1 );
  8207. // check first triangle
  8208. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8209. if ( intersect === null ) {
  8210. // check second triangle
  8211. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8212. _uvB.set( 0, 1 );
  8213. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8214. if ( intersect === null ) {
  8215. return;
  8216. }
  8217. }
  8218. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8219. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8220. intersects.push( {
  8221. distance: distance,
  8222. point: _intersectPoint.clone(),
  8223. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8224. face: null,
  8225. object: this
  8226. } );
  8227. }
  8228. copy( source, recursive ) {
  8229. super.copy( source, recursive );
  8230. if ( source.center !== undefined ) this.center.copy( source.center );
  8231. this.material = source.material;
  8232. return this;
  8233. }
  8234. }
  8235. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8236. // compute position in camera space
  8237. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8238. // to check if rotation is not zero
  8239. if ( sin !== undefined ) {
  8240. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8241. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8242. } else {
  8243. _rotatedPosition.copy( _alignedPosition );
  8244. }
  8245. vertexPosition.copy( mvPosition );
  8246. vertexPosition.x += _rotatedPosition.x;
  8247. vertexPosition.y += _rotatedPosition.y;
  8248. // transform to world space
  8249. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8250. }
  8251. const _v1$2 = /*@__PURE__*/ new Vector3();
  8252. const _v2$1 = /*@__PURE__*/ new Vector3();
  8253. class LOD extends Object3D {
  8254. constructor() {
  8255. super();
  8256. this._currentLevel = 0;
  8257. this.type = 'LOD';
  8258. Object.defineProperties( this, {
  8259. levels: {
  8260. enumerable: true,
  8261. value: []
  8262. },
  8263. isLOD: {
  8264. value: true,
  8265. }
  8266. } );
  8267. this.autoUpdate = true;
  8268. }
  8269. copy( source ) {
  8270. super.copy( source, false );
  8271. const levels = source.levels;
  8272. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8273. const level = levels[ i ];
  8274. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8275. }
  8276. this.autoUpdate = source.autoUpdate;
  8277. return this;
  8278. }
  8279. addLevel( object, distance = 0, hysteresis = 0 ) {
  8280. distance = Math.abs( distance );
  8281. const levels = this.levels;
  8282. let l;
  8283. for ( l = 0; l < levels.length; l ++ ) {
  8284. if ( distance < levels[ l ].distance ) {
  8285. break;
  8286. }
  8287. }
  8288. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8289. this.add( object );
  8290. return this;
  8291. }
  8292. getCurrentLevel() {
  8293. return this._currentLevel;
  8294. }
  8295. getObjectForDistance( distance ) {
  8296. const levels = this.levels;
  8297. if ( levels.length > 0 ) {
  8298. let i, l;
  8299. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8300. let levelDistance = levels[ i ].distance;
  8301. if ( levels[ i ].object.visible ) {
  8302. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8303. }
  8304. if ( distance < levelDistance ) {
  8305. break;
  8306. }
  8307. }
  8308. return levels[ i - 1 ].object;
  8309. }
  8310. return null;
  8311. }
  8312. raycast( raycaster, intersects ) {
  8313. const levels = this.levels;
  8314. if ( levels.length > 0 ) {
  8315. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8316. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8317. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8318. }
  8319. }
  8320. update( camera ) {
  8321. const levels = this.levels;
  8322. if ( levels.length > 1 ) {
  8323. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8324. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8325. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8326. levels[ 0 ].object.visible = true;
  8327. let i, l;
  8328. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8329. let levelDistance = levels[ i ].distance;
  8330. if ( levels[ i ].object.visible ) {
  8331. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8332. }
  8333. if ( distance >= levelDistance ) {
  8334. levels[ i - 1 ].object.visible = false;
  8335. levels[ i ].object.visible = true;
  8336. } else {
  8337. break;
  8338. }
  8339. }
  8340. this._currentLevel = i - 1;
  8341. for ( ; i < l; i ++ ) {
  8342. levels[ i ].object.visible = false;
  8343. }
  8344. }
  8345. }
  8346. toJSON( meta ) {
  8347. const data = super.toJSON( meta );
  8348. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8349. data.object.levels = [];
  8350. const levels = this.levels;
  8351. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8352. const level = levels[ i ];
  8353. data.object.levels.push( {
  8354. object: level.object.uuid,
  8355. distance: level.distance,
  8356. hysteresis: level.hysteresis
  8357. } );
  8358. }
  8359. return data;
  8360. }
  8361. }
  8362. const _basePosition = /*@__PURE__*/ new Vector3();
  8363. const _skinIndex = /*@__PURE__*/ new Vector4();
  8364. const _skinWeight = /*@__PURE__*/ new Vector4();
  8365. const _vector3 = /*@__PURE__*/ new Vector3();
  8366. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8367. const _vertex = /*@__PURE__*/ new Vector3();
  8368. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8369. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8370. const _ray$2 = /*@__PURE__*/ new Ray();
  8371. class SkinnedMesh extends Mesh {
  8372. constructor( geometry, material ) {
  8373. super( geometry, material );
  8374. this.isSkinnedMesh = true;
  8375. this.type = 'SkinnedMesh';
  8376. this.bindMode = AttachedBindMode;
  8377. this.bindMatrix = new Matrix4();
  8378. this.bindMatrixInverse = new Matrix4();
  8379. this.boundingBox = null;
  8380. this.boundingSphere = null;
  8381. }
  8382. computeBoundingBox() {
  8383. const geometry = this.geometry;
  8384. if ( this.boundingBox === null ) {
  8385. this.boundingBox = new Box3();
  8386. }
  8387. this.boundingBox.makeEmpty();
  8388. const positionAttribute = geometry.getAttribute( 'position' );
  8389. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8390. this.getVertexPosition( i, _vertex );
  8391. this.boundingBox.expandByPoint( _vertex );
  8392. }
  8393. }
  8394. computeBoundingSphere() {
  8395. const geometry = this.geometry;
  8396. if ( this.boundingSphere === null ) {
  8397. this.boundingSphere = new Sphere();
  8398. }
  8399. this.boundingSphere.makeEmpty();
  8400. const positionAttribute = geometry.getAttribute( 'position' );
  8401. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8402. this.getVertexPosition( i, _vertex );
  8403. this.boundingSphere.expandByPoint( _vertex );
  8404. }
  8405. }
  8406. copy( source, recursive ) {
  8407. super.copy( source, recursive );
  8408. this.bindMode = source.bindMode;
  8409. this.bindMatrix.copy( source.bindMatrix );
  8410. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8411. this.skeleton = source.skeleton;
  8412. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8413. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8414. return this;
  8415. }
  8416. raycast( raycaster, intersects ) {
  8417. const material = this.material;
  8418. const matrixWorld = this.matrixWorld;
  8419. if ( material === undefined ) return;
  8420. // test with bounding sphere in world space
  8421. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8422. _sphere$5.copy( this.boundingSphere );
  8423. _sphere$5.applyMatrix4( matrixWorld );
  8424. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8425. // convert ray to local space of skinned mesh
  8426. _inverseMatrix$2.copy( matrixWorld ).invert();
  8427. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8428. // test with bounding box in local space
  8429. if ( this.boundingBox !== null ) {
  8430. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8431. }
  8432. // test for intersections with geometry
  8433. this._computeIntersections( raycaster, intersects, _ray$2 );
  8434. }
  8435. getVertexPosition( index, target ) {
  8436. super.getVertexPosition( index, target );
  8437. this.applyBoneTransform( index, target );
  8438. return target;
  8439. }
  8440. bind( skeleton, bindMatrix ) {
  8441. this.skeleton = skeleton;
  8442. if ( bindMatrix === undefined ) {
  8443. this.updateMatrixWorld( true );
  8444. this.skeleton.calculateInverses();
  8445. bindMatrix = this.matrixWorld;
  8446. }
  8447. this.bindMatrix.copy( bindMatrix );
  8448. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8449. }
  8450. pose() {
  8451. this.skeleton.pose();
  8452. }
  8453. normalizeSkinWeights() {
  8454. const vector = new Vector4();
  8455. const skinWeight = this.geometry.attributes.skinWeight;
  8456. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8457. vector.fromBufferAttribute( skinWeight, i );
  8458. const scale = 1.0 / vector.manhattanLength();
  8459. if ( scale !== Infinity ) {
  8460. vector.multiplyScalar( scale );
  8461. } else {
  8462. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8463. }
  8464. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8465. }
  8466. }
  8467. updateMatrixWorld( force ) {
  8468. super.updateMatrixWorld( force );
  8469. if ( this.bindMode === AttachedBindMode ) {
  8470. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8471. } else if ( this.bindMode === DetachedBindMode ) {
  8472. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8473. } else {
  8474. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8475. }
  8476. }
  8477. applyBoneTransform( index, vector ) {
  8478. const skeleton = this.skeleton;
  8479. const geometry = this.geometry;
  8480. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8481. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8482. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8483. vector.set( 0, 0, 0 );
  8484. for ( let i = 0; i < 4; i ++ ) {
  8485. const weight = _skinWeight.getComponent( i );
  8486. if ( weight !== 0 ) {
  8487. const boneIndex = _skinIndex.getComponent( i );
  8488. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8489. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8490. }
  8491. }
  8492. return vector.applyMatrix4( this.bindMatrixInverse );
  8493. }
  8494. }
  8495. class Bone extends Object3D {
  8496. constructor() {
  8497. super();
  8498. this.isBone = true;
  8499. this.type = 'Bone';
  8500. }
  8501. }
  8502. class DataTexture extends Texture {
  8503. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8504. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8505. this.isDataTexture = true;
  8506. this.image = { data: data, width: width, height: height };
  8507. this.generateMipmaps = false;
  8508. this.flipY = false;
  8509. this.unpackAlignment = 1;
  8510. }
  8511. }
  8512. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8513. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8514. class Skeleton {
  8515. constructor( bones = [], boneInverses = [] ) {
  8516. this.uuid = generateUUID();
  8517. this.bones = bones.slice( 0 );
  8518. this.boneInverses = boneInverses;
  8519. this.boneMatrices = null;
  8520. this.boneTexture = null;
  8521. this.init();
  8522. }
  8523. init() {
  8524. const bones = this.bones;
  8525. const boneInverses = this.boneInverses;
  8526. this.boneMatrices = new Float32Array( bones.length * 16 );
  8527. // calculate inverse bone matrices if necessary
  8528. if ( boneInverses.length === 0 ) {
  8529. this.calculateInverses();
  8530. } else {
  8531. // handle special case
  8532. if ( bones.length !== boneInverses.length ) {
  8533. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8534. this.boneInverses = [];
  8535. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8536. this.boneInverses.push( new Matrix4() );
  8537. }
  8538. }
  8539. }
  8540. }
  8541. calculateInverses() {
  8542. this.boneInverses.length = 0;
  8543. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8544. const inverse = new Matrix4();
  8545. if ( this.bones[ i ] ) {
  8546. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8547. }
  8548. this.boneInverses.push( inverse );
  8549. }
  8550. }
  8551. pose() {
  8552. // recover the bind-time world matrices
  8553. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8554. const bone = this.bones[ i ];
  8555. if ( bone ) {
  8556. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8557. }
  8558. }
  8559. // compute the local matrices, positions, rotations and scales
  8560. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8561. const bone = this.bones[ i ];
  8562. if ( bone ) {
  8563. if ( bone.parent && bone.parent.isBone ) {
  8564. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8565. bone.matrix.multiply( bone.matrixWorld );
  8566. } else {
  8567. bone.matrix.copy( bone.matrixWorld );
  8568. }
  8569. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8570. }
  8571. }
  8572. }
  8573. update() {
  8574. const bones = this.bones;
  8575. const boneInverses = this.boneInverses;
  8576. const boneMatrices = this.boneMatrices;
  8577. const boneTexture = this.boneTexture;
  8578. // flatten bone matrices to array
  8579. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8580. // compute the offset between the current and the original transform
  8581. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8582. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8583. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8584. }
  8585. if ( boneTexture !== null ) {
  8586. boneTexture.needsUpdate = true;
  8587. }
  8588. }
  8589. clone() {
  8590. return new Skeleton( this.bones, this.boneInverses );
  8591. }
  8592. computeBoneTexture() {
  8593. // layout (1 matrix = 4 pixels)
  8594. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8595. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8596. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8597. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8598. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8599. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8600. size = Math.ceil( size / 4 ) * 4;
  8601. size = Math.max( size, 4 );
  8602. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8603. boneMatrices.set( this.boneMatrices ); // copy current values
  8604. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8605. boneTexture.needsUpdate = true;
  8606. this.boneMatrices = boneMatrices;
  8607. this.boneTexture = boneTexture;
  8608. return this;
  8609. }
  8610. getBoneByName( name ) {
  8611. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8612. const bone = this.bones[ i ];
  8613. if ( bone.name === name ) {
  8614. return bone;
  8615. }
  8616. }
  8617. return undefined;
  8618. }
  8619. dispose( ) {
  8620. if ( this.boneTexture !== null ) {
  8621. this.boneTexture.dispose();
  8622. this.boneTexture = null;
  8623. }
  8624. }
  8625. fromJSON( json, bones ) {
  8626. this.uuid = json.uuid;
  8627. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8628. const uuid = json.bones[ i ];
  8629. let bone = bones[ uuid ];
  8630. if ( bone === undefined ) {
  8631. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8632. bone = new Bone();
  8633. }
  8634. this.bones.push( bone );
  8635. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8636. }
  8637. this.init();
  8638. return this;
  8639. }
  8640. toJSON() {
  8641. const data = {
  8642. metadata: {
  8643. version: 4.6,
  8644. type: 'Skeleton',
  8645. generator: 'Skeleton.toJSON'
  8646. },
  8647. bones: [],
  8648. boneInverses: []
  8649. };
  8650. data.uuid = this.uuid;
  8651. const bones = this.bones;
  8652. const boneInverses = this.boneInverses;
  8653. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8654. const bone = bones[ i ];
  8655. data.bones.push( bone.uuid );
  8656. const boneInverse = boneInverses[ i ];
  8657. data.boneInverses.push( boneInverse.toArray() );
  8658. }
  8659. return data;
  8660. }
  8661. }
  8662. class InstancedBufferAttribute extends BufferAttribute {
  8663. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8664. super( array, itemSize, normalized );
  8665. this.isInstancedBufferAttribute = true;
  8666. this.meshPerAttribute = meshPerAttribute;
  8667. }
  8668. copy( source ) {
  8669. super.copy( source );
  8670. this.meshPerAttribute = source.meshPerAttribute;
  8671. return this;
  8672. }
  8673. toJSON() {
  8674. const data = super.toJSON();
  8675. data.meshPerAttribute = this.meshPerAttribute;
  8676. data.isInstancedBufferAttribute = true;
  8677. return data;
  8678. }
  8679. }
  8680. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8681. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8682. const _instanceIntersects = [];
  8683. const _box3 = /*@__PURE__*/ new Box3();
  8684. const _identity = /*@__PURE__*/ new Matrix4();
  8685. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8686. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8687. class InstancedMesh extends Mesh {
  8688. constructor( geometry, material, count ) {
  8689. super( geometry, material );
  8690. this.isInstancedMesh = true;
  8691. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8692. this.instanceColor = null;
  8693. this.morphTexture = null;
  8694. this.count = count;
  8695. this.boundingBox = null;
  8696. this.boundingSphere = null;
  8697. for ( let i = 0; i < count; i ++ ) {
  8698. this.setMatrixAt( i, _identity );
  8699. }
  8700. }
  8701. computeBoundingBox() {
  8702. const geometry = this.geometry;
  8703. const count = this.count;
  8704. if ( this.boundingBox === null ) {
  8705. this.boundingBox = new Box3();
  8706. }
  8707. if ( geometry.boundingBox === null ) {
  8708. geometry.computeBoundingBox();
  8709. }
  8710. this.boundingBox.makeEmpty();
  8711. for ( let i = 0; i < count; i ++ ) {
  8712. this.getMatrixAt( i, _instanceLocalMatrix );
  8713. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8714. this.boundingBox.union( _box3 );
  8715. }
  8716. }
  8717. computeBoundingSphere() {
  8718. const geometry = this.geometry;
  8719. const count = this.count;
  8720. if ( this.boundingSphere === null ) {
  8721. this.boundingSphere = new Sphere();
  8722. }
  8723. if ( geometry.boundingSphere === null ) {
  8724. geometry.computeBoundingSphere();
  8725. }
  8726. this.boundingSphere.makeEmpty();
  8727. for ( let i = 0; i < count; i ++ ) {
  8728. this.getMatrixAt( i, _instanceLocalMatrix );
  8729. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8730. this.boundingSphere.union( _sphere$4 );
  8731. }
  8732. }
  8733. copy( source, recursive ) {
  8734. super.copy( source, recursive );
  8735. this.instanceMatrix.copy( source.instanceMatrix );
  8736. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8737. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8738. this.count = source.count;
  8739. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8740. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8741. return this;
  8742. }
  8743. getColorAt( index, color ) {
  8744. color.fromArray( this.instanceColor.array, index * 3 );
  8745. }
  8746. getMatrixAt( index, matrix ) {
  8747. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8748. }
  8749. getMorphAt( index, object ) {
  8750. const objectInfluences = object.morphTargetInfluences;
  8751. const array = this.morphTexture.source.data.data;
  8752. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8753. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8754. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8755. objectInfluences[ i ] = array[ dataIndex + i ];
  8756. }
  8757. }
  8758. raycast( raycaster, intersects ) {
  8759. const matrixWorld = this.matrixWorld;
  8760. const raycastTimes = this.count;
  8761. _mesh$1.geometry = this.geometry;
  8762. _mesh$1.material = this.material;
  8763. if ( _mesh$1.material === undefined ) return;
  8764. // test with bounding sphere first
  8765. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8766. _sphere$4.copy( this.boundingSphere );
  8767. _sphere$4.applyMatrix4( matrixWorld );
  8768. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8769. // now test each instance
  8770. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8771. // calculate the world matrix for each instance
  8772. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8773. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8774. // the mesh represents this single instance
  8775. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8776. _mesh$1.raycast( raycaster, _instanceIntersects );
  8777. // process the result of raycast
  8778. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8779. const intersect = _instanceIntersects[ i ];
  8780. intersect.instanceId = instanceId;
  8781. intersect.object = this;
  8782. intersects.push( intersect );
  8783. }
  8784. _instanceIntersects.length = 0;
  8785. }
  8786. }
  8787. setColorAt( index, color ) {
  8788. if ( this.instanceColor === null ) {
  8789. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8790. }
  8791. color.toArray( this.instanceColor.array, index * 3 );
  8792. }
  8793. setMatrixAt( index, matrix ) {
  8794. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8795. }
  8796. setMorphAt( index, object ) {
  8797. const objectInfluences = object.morphTargetInfluences;
  8798. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8799. if ( this.morphTexture === null ) {
  8800. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8801. }
  8802. const array = this.morphTexture.source.data.data;
  8803. let morphInfluencesSum = 0;
  8804. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8805. morphInfluencesSum += objectInfluences[ i ];
  8806. }
  8807. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8808. const dataIndex = len * index;
  8809. array[ dataIndex ] = morphBaseInfluence;
  8810. array.set( objectInfluences, dataIndex + 1 );
  8811. }
  8812. updateMorphTargets() {
  8813. }
  8814. dispose() {
  8815. this.dispatchEvent( { type: 'dispose' } );
  8816. if ( this.morphTexture !== null ) {
  8817. this.morphTexture.dispose();
  8818. this.morphTexture = null;
  8819. }
  8820. return this;
  8821. }
  8822. }
  8823. const _vector1 = /*@__PURE__*/ new Vector3();
  8824. const _vector2 = /*@__PURE__*/ new Vector3();
  8825. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8826. class Plane {
  8827. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8828. this.isPlane = true;
  8829. // normal is assumed to be normalized
  8830. this.normal = normal;
  8831. this.constant = constant;
  8832. }
  8833. set( normal, constant ) {
  8834. this.normal.copy( normal );
  8835. this.constant = constant;
  8836. return this;
  8837. }
  8838. setComponents( x, y, z, w ) {
  8839. this.normal.set( x, y, z );
  8840. this.constant = w;
  8841. return this;
  8842. }
  8843. setFromNormalAndCoplanarPoint( normal, point ) {
  8844. this.normal.copy( normal );
  8845. this.constant = - point.dot( this.normal );
  8846. return this;
  8847. }
  8848. setFromCoplanarPoints( a, b, c ) {
  8849. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8850. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8851. this.setFromNormalAndCoplanarPoint( normal, a );
  8852. return this;
  8853. }
  8854. copy( plane ) {
  8855. this.normal.copy( plane.normal );
  8856. this.constant = plane.constant;
  8857. return this;
  8858. }
  8859. normalize() {
  8860. // Note: will lead to a divide by zero if the plane is invalid.
  8861. const inverseNormalLength = 1.0 / this.normal.length();
  8862. this.normal.multiplyScalar( inverseNormalLength );
  8863. this.constant *= inverseNormalLength;
  8864. return this;
  8865. }
  8866. negate() {
  8867. this.constant *= - 1;
  8868. this.normal.negate();
  8869. return this;
  8870. }
  8871. distanceToPoint( point ) {
  8872. return this.normal.dot( point ) + this.constant;
  8873. }
  8874. distanceToSphere( sphere ) {
  8875. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8876. }
  8877. projectPoint( point, target ) {
  8878. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8879. }
  8880. intersectLine( line, target ) {
  8881. const direction = line.delta( _vector1 );
  8882. const denominator = this.normal.dot( direction );
  8883. if ( denominator === 0 ) {
  8884. // line is coplanar, return origin
  8885. if ( this.distanceToPoint( line.start ) === 0 ) {
  8886. return target.copy( line.start );
  8887. }
  8888. // Unsure if this is the correct method to handle this case.
  8889. return null;
  8890. }
  8891. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8892. if ( t < 0 || t > 1 ) {
  8893. return null;
  8894. }
  8895. return target.copy( line.start ).addScaledVector( direction, t );
  8896. }
  8897. intersectsLine( line ) {
  8898. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8899. const startSign = this.distanceToPoint( line.start );
  8900. const endSign = this.distanceToPoint( line.end );
  8901. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8902. }
  8903. intersectsBox( box ) {
  8904. return box.intersectsPlane( this );
  8905. }
  8906. intersectsSphere( sphere ) {
  8907. return sphere.intersectsPlane( this );
  8908. }
  8909. coplanarPoint( target ) {
  8910. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8911. }
  8912. applyMatrix4( matrix, optionalNormalMatrix ) {
  8913. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8914. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8915. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8916. this.constant = - referencePoint.dot( normal );
  8917. return this;
  8918. }
  8919. translate( offset ) {
  8920. this.constant -= offset.dot( this.normal );
  8921. return this;
  8922. }
  8923. equals( plane ) {
  8924. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8925. }
  8926. clone() {
  8927. return new this.constructor().copy( this );
  8928. }
  8929. }
  8930. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8931. const _vector$6 = /*@__PURE__*/ new Vector3();
  8932. class Frustum {
  8933. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8934. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8935. }
  8936. set( p0, p1, p2, p3, p4, p5 ) {
  8937. const planes = this.planes;
  8938. planes[ 0 ].copy( p0 );
  8939. planes[ 1 ].copy( p1 );
  8940. planes[ 2 ].copy( p2 );
  8941. planes[ 3 ].copy( p3 );
  8942. planes[ 4 ].copy( p4 );
  8943. planes[ 5 ].copy( p5 );
  8944. return this;
  8945. }
  8946. copy( frustum ) {
  8947. const planes = this.planes;
  8948. for ( let i = 0; i < 6; i ++ ) {
  8949. planes[ i ].copy( frustum.planes[ i ] );
  8950. }
  8951. return this;
  8952. }
  8953. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8954. const planes = this.planes;
  8955. const me = m.elements;
  8956. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8957. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8958. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8959. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8960. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8961. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8962. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8963. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8964. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8965. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8966. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8967. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8968. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8969. } else {
  8970. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8971. }
  8972. return this;
  8973. }
  8974. intersectsObject( object ) {
  8975. if ( object.boundingSphere !== undefined ) {
  8976. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8977. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8978. } else {
  8979. const geometry = object.geometry;
  8980. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8981. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8982. }
  8983. return this.intersectsSphere( _sphere$3 );
  8984. }
  8985. intersectsSprite( sprite ) {
  8986. _sphere$3.center.set( 0, 0, 0 );
  8987. _sphere$3.radius = 0.7071067811865476;
  8988. _sphere$3.applyMatrix4( sprite.matrixWorld );
  8989. return this.intersectsSphere( _sphere$3 );
  8990. }
  8991. intersectsSphere( sphere ) {
  8992. const planes = this.planes;
  8993. const center = sphere.center;
  8994. const negRadius = - sphere.radius;
  8995. for ( let i = 0; i < 6; i ++ ) {
  8996. const distance = planes[ i ].distanceToPoint( center );
  8997. if ( distance < negRadius ) {
  8998. return false;
  8999. }
  9000. }
  9001. return true;
  9002. }
  9003. intersectsBox( box ) {
  9004. const planes = this.planes;
  9005. for ( let i = 0; i < 6; i ++ ) {
  9006. const plane = planes[ i ];
  9007. // corner at max distance
  9008. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9009. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9010. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9011. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9012. return false;
  9013. }
  9014. }
  9015. return true;
  9016. }
  9017. containsPoint( point ) {
  9018. const planes = this.planes;
  9019. for ( let i = 0; i < 6; i ++ ) {
  9020. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9021. return false;
  9022. }
  9023. }
  9024. return true;
  9025. }
  9026. clone() {
  9027. return new this.constructor().copy( this );
  9028. }
  9029. }
  9030. function sortOpaque( a, b ) {
  9031. return a.z - b.z;
  9032. }
  9033. function sortTransparent( a, b ) {
  9034. return b.z - a.z;
  9035. }
  9036. class MultiDrawRenderList {
  9037. constructor() {
  9038. this.index = 0;
  9039. this.pool = [];
  9040. this.list = [];
  9041. }
  9042. push( drawRange, z, index ) {
  9043. const pool = this.pool;
  9044. const list = this.list;
  9045. if ( this.index >= pool.length ) {
  9046. pool.push( {
  9047. start: - 1,
  9048. count: - 1,
  9049. z: - 1,
  9050. index: - 1,
  9051. } );
  9052. }
  9053. const item = pool[ this.index ];
  9054. list.push( item );
  9055. this.index ++;
  9056. item.start = drawRange.start;
  9057. item.count = drawRange.count;
  9058. item.z = z;
  9059. item.index = index;
  9060. }
  9061. reset() {
  9062. this.list.length = 0;
  9063. this.index = 0;
  9064. }
  9065. }
  9066. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9067. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9068. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9069. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9070. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9071. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9072. const _box$1 = /*@__PURE__*/ new Box3();
  9073. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9074. const _vector$5 = /*@__PURE__*/ new Vector3();
  9075. const _forward = /*@__PURE__*/ new Vector3();
  9076. const _temp = /*@__PURE__*/ new Vector3();
  9077. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9078. const _mesh = /*@__PURE__*/ new Mesh();
  9079. const _batchIntersects = [];
  9080. // @TODO: SkinnedMesh support?
  9081. // @TODO: geometry.groups support?
  9082. // @TODO: geometry.drawRange support?
  9083. // @TODO: geometry.morphAttributes support?
  9084. // @TODO: Support uniform parameter per geometry
  9085. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9086. // copies data from attribute "src" into "target" starting at "targetOffset"
  9087. function copyAttributeData( src, target, targetOffset = 0 ) {
  9088. const itemSize = target.itemSize;
  9089. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9090. // use the component getters and setters if the array data cannot
  9091. // be copied directly
  9092. const vertexCount = src.count;
  9093. for ( let i = 0; i < vertexCount; i ++ ) {
  9094. for ( let c = 0; c < itemSize; c ++ ) {
  9095. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9096. }
  9097. }
  9098. } else {
  9099. // faster copy approach using typed array set function
  9100. target.array.set( src.array, targetOffset * itemSize );
  9101. }
  9102. target.needsUpdate = true;
  9103. }
  9104. class BatchedMesh extends Mesh {
  9105. get maxInstanceCount() {
  9106. return this._maxInstanceCount;
  9107. }
  9108. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9109. super( new BufferGeometry(), material );
  9110. this.isBatchedMesh = true;
  9111. this.perObjectFrustumCulled = true;
  9112. this.sortObjects = true;
  9113. this.boundingBox = null;
  9114. this.boundingSphere = null;
  9115. this.customSort = null;
  9116. // stores visible, active, and geometry id per object
  9117. this._drawInfo = [];
  9118. // geometry information
  9119. this._drawRanges = [];
  9120. this._reservedRanges = [];
  9121. this._bounds = [];
  9122. this._maxInstanceCount = maxInstanceCount;
  9123. this._maxVertexCount = maxVertexCount;
  9124. this._maxIndexCount = maxIndexCount;
  9125. this._geometryInitialized = false;
  9126. this._geometryCount = 0;
  9127. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9128. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9129. this._multiDrawCount = 0;
  9130. this._multiDrawInstances = null;
  9131. this._visibilityChanged = true;
  9132. // Local matrix per geometry by using data texture
  9133. this._matricesTexture = null;
  9134. this._indirectTexture = null;
  9135. this._colorsTexture = null;
  9136. this._initMatricesTexture();
  9137. this._initIndirectTexture();
  9138. }
  9139. _initMatricesTexture() {
  9140. // layout (1 matrix = 4 pixels)
  9141. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9142. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9143. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9144. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9145. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9146. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9147. size = Math.ceil( size / 4 ) * 4;
  9148. size = Math.max( size, 4 );
  9149. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9150. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9151. this._matricesTexture = matricesTexture;
  9152. }
  9153. _initIndirectTexture() {
  9154. let size = Math.sqrt( this._maxInstanceCount );
  9155. size = Math.ceil( size );
  9156. const indirectArray = new Uint32Array( size * size );
  9157. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9158. this._indirectTexture = indirectTexture;
  9159. }
  9160. _initColorsTexture() {
  9161. let size = Math.sqrt( this._maxInstanceCount );
  9162. size = Math.ceil( size );
  9163. // 4 floats per RGBA pixel initialized to white
  9164. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9165. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9166. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9167. this._colorsTexture = colorsTexture;
  9168. }
  9169. _initializeGeometry( reference ) {
  9170. const geometry = this.geometry;
  9171. const maxVertexCount = this._maxVertexCount;
  9172. const maxIndexCount = this._maxIndexCount;
  9173. if ( this._geometryInitialized === false ) {
  9174. for ( const attributeName in reference.attributes ) {
  9175. const srcAttribute = reference.getAttribute( attributeName );
  9176. const { array, itemSize, normalized } = srcAttribute;
  9177. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9178. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9179. geometry.setAttribute( attributeName, dstAttribute );
  9180. }
  9181. if ( reference.getIndex() !== null ) {
  9182. // Reserve last u16 index for primitive restart.
  9183. const indexArray = maxVertexCount > 65535
  9184. ? new Uint32Array( maxIndexCount )
  9185. : new Uint16Array( maxIndexCount );
  9186. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9187. }
  9188. this._geometryInitialized = true;
  9189. }
  9190. }
  9191. // Make sure the geometry is compatible with the existing combined geometry attributes
  9192. _validateGeometry( geometry ) {
  9193. // check to ensure the geometries are using consistent attributes and indices
  9194. const batchGeometry = this.geometry;
  9195. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9196. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9197. }
  9198. for ( const attributeName in batchGeometry.attributes ) {
  9199. if ( ! geometry.hasAttribute( attributeName ) ) {
  9200. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9201. }
  9202. const srcAttribute = geometry.getAttribute( attributeName );
  9203. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9204. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9205. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9206. }
  9207. }
  9208. }
  9209. setCustomSort( func ) {
  9210. this.customSort = func;
  9211. return this;
  9212. }
  9213. computeBoundingBox() {
  9214. if ( this.boundingBox === null ) {
  9215. this.boundingBox = new Box3();
  9216. }
  9217. const boundingBox = this.boundingBox;
  9218. const drawInfo = this._drawInfo;
  9219. boundingBox.makeEmpty();
  9220. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9221. if ( drawInfo[ i ].active === false ) continue;
  9222. const geometryId = drawInfo[ i ].geometryIndex;
  9223. this.getMatrixAt( i, _matrix$1 );
  9224. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9225. boundingBox.union( _box$1 );
  9226. }
  9227. }
  9228. computeBoundingSphere() {
  9229. if ( this.boundingSphere === null ) {
  9230. this.boundingSphere = new Sphere();
  9231. }
  9232. const boundingSphere = this.boundingSphere;
  9233. const drawInfo = this._drawInfo;
  9234. boundingSphere.makeEmpty();
  9235. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9236. if ( drawInfo[ i ].active === false ) continue;
  9237. const geometryId = drawInfo[ i ].geometryIndex;
  9238. this.getMatrixAt( i, _matrix$1 );
  9239. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9240. boundingSphere.union( _sphere$2 );
  9241. }
  9242. }
  9243. addInstance( geometryId ) {
  9244. // ensure we're not over geometry
  9245. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9246. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9247. }
  9248. this._drawInfo.push( {
  9249. visible: true,
  9250. active: true,
  9251. geometryIndex: geometryId,
  9252. } );
  9253. // initialize the matrix
  9254. const drawId = this._drawInfo.length - 1;
  9255. const matricesTexture = this._matricesTexture;
  9256. const matricesArray = matricesTexture.image.data;
  9257. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9258. matricesTexture.needsUpdate = true;
  9259. const colorsTexture = this._colorsTexture;
  9260. if ( colorsTexture ) {
  9261. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9262. colorsTexture.needsUpdate = true;
  9263. }
  9264. return drawId;
  9265. }
  9266. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9267. this._initializeGeometry( geometry );
  9268. this._validateGeometry( geometry );
  9269. // ensure we're not over geometry
  9270. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9271. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9272. }
  9273. // get the necessary range fo the geometry
  9274. const reservedRange = {
  9275. vertexStart: - 1,
  9276. vertexCount: - 1,
  9277. indexStart: - 1,
  9278. indexCount: - 1,
  9279. };
  9280. let lastRange = null;
  9281. const reservedRanges = this._reservedRanges;
  9282. const drawRanges = this._drawRanges;
  9283. const bounds = this._bounds;
  9284. if ( this._geometryCount !== 0 ) {
  9285. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9286. }
  9287. if ( vertexCount === - 1 ) {
  9288. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9289. } else {
  9290. reservedRange.vertexCount = vertexCount;
  9291. }
  9292. if ( lastRange === null ) {
  9293. reservedRange.vertexStart = 0;
  9294. } else {
  9295. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9296. }
  9297. const index = geometry.getIndex();
  9298. const hasIndex = index !== null;
  9299. if ( hasIndex ) {
  9300. if ( indexCount === - 1 ) {
  9301. reservedRange.indexCount = index.count;
  9302. } else {
  9303. reservedRange.indexCount = indexCount;
  9304. }
  9305. if ( lastRange === null ) {
  9306. reservedRange.indexStart = 0;
  9307. } else {
  9308. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9309. }
  9310. }
  9311. if (
  9312. reservedRange.indexStart !== - 1 &&
  9313. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9314. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9315. ) {
  9316. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9317. }
  9318. // update id
  9319. const geometryId = this._geometryCount;
  9320. this._geometryCount ++;
  9321. // add the reserved range and draw range objects
  9322. reservedRanges.push( reservedRange );
  9323. drawRanges.push( {
  9324. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9325. count: - 1
  9326. } );
  9327. bounds.push( {
  9328. boxInitialized: false,
  9329. box: new Box3(),
  9330. sphereInitialized: false,
  9331. sphere: new Sphere()
  9332. } );
  9333. // update the geometry
  9334. this.setGeometryAt( geometryId, geometry );
  9335. return geometryId;
  9336. }
  9337. setGeometryAt( geometryId, geometry ) {
  9338. if ( geometryId >= this._geometryCount ) {
  9339. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9340. }
  9341. this._validateGeometry( geometry );
  9342. const batchGeometry = this.geometry;
  9343. const hasIndex = batchGeometry.getIndex() !== null;
  9344. const dstIndex = batchGeometry.getIndex();
  9345. const srcIndex = geometry.getIndex();
  9346. const reservedRange = this._reservedRanges[ geometryId ];
  9347. if (
  9348. hasIndex &&
  9349. srcIndex.count > reservedRange.indexCount ||
  9350. geometry.attributes.position.count > reservedRange.vertexCount
  9351. ) {
  9352. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9353. }
  9354. // copy geometry over
  9355. const vertexStart = reservedRange.vertexStart;
  9356. const vertexCount = reservedRange.vertexCount;
  9357. for ( const attributeName in batchGeometry.attributes ) {
  9358. // copy attribute data
  9359. const srcAttribute = geometry.getAttribute( attributeName );
  9360. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9361. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9362. // fill the rest in with zeroes
  9363. const itemSize = srcAttribute.itemSize;
  9364. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9365. const index = vertexStart + i;
  9366. for ( let c = 0; c < itemSize; c ++ ) {
  9367. dstAttribute.setComponent( index, c, 0 );
  9368. }
  9369. }
  9370. dstAttribute.needsUpdate = true;
  9371. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9372. }
  9373. // copy index
  9374. if ( hasIndex ) {
  9375. const indexStart = reservedRange.indexStart;
  9376. // copy index data over
  9377. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9378. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9379. }
  9380. // fill the rest in with zeroes
  9381. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9382. dstIndex.setX( indexStart + i, vertexStart );
  9383. }
  9384. dstIndex.needsUpdate = true;
  9385. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9386. }
  9387. // store the bounding boxes
  9388. const bound = this._bounds[ geometryId ];
  9389. if ( geometry.boundingBox !== null ) {
  9390. bound.box.copy( geometry.boundingBox );
  9391. bound.boxInitialized = true;
  9392. } else {
  9393. bound.boxInitialized = false;
  9394. }
  9395. if ( geometry.boundingSphere !== null ) {
  9396. bound.sphere.copy( geometry.boundingSphere );
  9397. bound.sphereInitialized = true;
  9398. } else {
  9399. bound.sphereInitialized = false;
  9400. }
  9401. // set drawRange count
  9402. const drawRange = this._drawRanges[ geometryId ];
  9403. const posAttr = geometry.getAttribute( 'position' );
  9404. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9405. this._visibilityChanged = true;
  9406. return geometryId;
  9407. }
  9408. /*
  9409. deleteGeometry( geometryId ) {
  9410. // TODO: delete geometry and associated instances
  9411. }
  9412. */
  9413. /*
  9414. deleteInstance( instanceId ) {
  9415. // Note: User needs to call optimize() afterward to pack the data.
  9416. const drawInfo = this._drawInfo;
  9417. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9418. return this;
  9419. }
  9420. drawInfo[ instanceId ].active = false;
  9421. this._visibilityChanged = true;
  9422. return this;
  9423. }
  9424. */
  9425. // get bounding box and compute it if it doesn't exist
  9426. getBoundingBoxAt( geometryId, target ) {
  9427. if ( geometryId >= this._geometryCount ) {
  9428. return null;
  9429. }
  9430. // compute bounding box
  9431. const bound = this._bounds[ geometryId ];
  9432. const box = bound.box;
  9433. const geometry = this.geometry;
  9434. if ( bound.boxInitialized === false ) {
  9435. box.makeEmpty();
  9436. const index = geometry.index;
  9437. const position = geometry.attributes.position;
  9438. const drawRange = this._drawRanges[ geometryId ];
  9439. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9440. let iv = i;
  9441. if ( index ) {
  9442. iv = index.getX( iv );
  9443. }
  9444. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9445. }
  9446. bound.boxInitialized = true;
  9447. }
  9448. target.copy( box );
  9449. return target;
  9450. }
  9451. // get bounding sphere and compute it if it doesn't exist
  9452. getBoundingSphereAt( geometryId, target ) {
  9453. if ( geometryId >= this._geometryCount ) {
  9454. return null;
  9455. }
  9456. // compute bounding sphere
  9457. const bound = this._bounds[ geometryId ];
  9458. const sphere = bound.sphere;
  9459. const geometry = this.geometry;
  9460. if ( bound.sphereInitialized === false ) {
  9461. sphere.makeEmpty();
  9462. this.getBoundingBoxAt( geometryId, _box$1 );
  9463. _box$1.getCenter( sphere.center );
  9464. const index = geometry.index;
  9465. const position = geometry.attributes.position;
  9466. const drawRange = this._drawRanges[ geometryId ];
  9467. let maxRadiusSq = 0;
  9468. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9469. let iv = i;
  9470. if ( index ) {
  9471. iv = index.getX( iv );
  9472. }
  9473. _vector$5.fromBufferAttribute( position, iv );
  9474. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9475. }
  9476. sphere.radius = Math.sqrt( maxRadiusSq );
  9477. bound.sphereInitialized = true;
  9478. }
  9479. target.copy( sphere );
  9480. return target;
  9481. }
  9482. setMatrixAt( instanceId, matrix ) {
  9483. // @TODO: Map geometryId to index of the arrays because
  9484. // optimize() can make geometryId mismatch the index
  9485. const drawInfo = this._drawInfo;
  9486. const matricesTexture = this._matricesTexture;
  9487. const matricesArray = this._matricesTexture.image.data;
  9488. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9489. return this;
  9490. }
  9491. matrix.toArray( matricesArray, instanceId * 16 );
  9492. matricesTexture.needsUpdate = true;
  9493. return this;
  9494. }
  9495. getMatrixAt( instanceId, matrix ) {
  9496. const drawInfo = this._drawInfo;
  9497. const matricesArray = this._matricesTexture.image.data;
  9498. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9499. return null;
  9500. }
  9501. return matrix.fromArray( matricesArray, instanceId * 16 );
  9502. }
  9503. setColorAt( instanceId, color ) {
  9504. if ( this._colorsTexture === null ) {
  9505. this._initColorsTexture();
  9506. }
  9507. // @TODO: Map id to index of the arrays because
  9508. // optimize() can make id mismatch the index
  9509. const colorsTexture = this._colorsTexture;
  9510. const colorsArray = this._colorsTexture.image.data;
  9511. const drawInfo = this._drawInfo;
  9512. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9513. return this;
  9514. }
  9515. color.toArray( colorsArray, instanceId * 4 );
  9516. colorsTexture.needsUpdate = true;
  9517. return this;
  9518. }
  9519. getColorAt( instanceId, color ) {
  9520. const colorsArray = this._colorsTexture.image.data;
  9521. const drawInfo = this._drawInfo;
  9522. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9523. return null;
  9524. }
  9525. return color.fromArray( colorsArray, instanceId * 4 );
  9526. }
  9527. setVisibleAt( instanceId, value ) {
  9528. // if the geometry is out of range, not active, or visibility state
  9529. // does not change then return early
  9530. const drawInfo = this._drawInfo;
  9531. if (
  9532. instanceId >= drawInfo.length ||
  9533. drawInfo[ instanceId ].active === false ||
  9534. drawInfo[ instanceId ].visible === value
  9535. ) {
  9536. return this;
  9537. }
  9538. drawInfo[ instanceId ].visible = value;
  9539. this._visibilityChanged = true;
  9540. return this;
  9541. }
  9542. getVisibleAt( instanceId ) {
  9543. // return early if the geometry is out of range or not active
  9544. const drawInfo = this._drawInfo;
  9545. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9546. return false;
  9547. }
  9548. return drawInfo[ instanceId ].visible;
  9549. }
  9550. raycast( raycaster, intersects ) {
  9551. const drawInfo = this._drawInfo;
  9552. const drawRanges = this._drawRanges;
  9553. const matrixWorld = this.matrixWorld;
  9554. const batchGeometry = this.geometry;
  9555. // iterate over each geometry
  9556. _mesh.material = this.material;
  9557. _mesh.geometry.index = batchGeometry.index;
  9558. _mesh.geometry.attributes = batchGeometry.attributes;
  9559. if ( _mesh.geometry.boundingBox === null ) {
  9560. _mesh.geometry.boundingBox = new Box3();
  9561. }
  9562. if ( _mesh.geometry.boundingSphere === null ) {
  9563. _mesh.geometry.boundingSphere = new Sphere();
  9564. }
  9565. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9566. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9567. continue;
  9568. }
  9569. const geometryId = drawInfo[ i ].geometryIndex;
  9570. const drawRange = drawRanges[ geometryId ];
  9571. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9572. // ge the intersects
  9573. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9574. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9575. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9576. _mesh.raycast( raycaster, _batchIntersects );
  9577. // add batch id to the intersects
  9578. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9579. const intersect = _batchIntersects[ j ];
  9580. intersect.object = this;
  9581. intersect.batchId = i;
  9582. intersects.push( intersect );
  9583. }
  9584. _batchIntersects.length = 0;
  9585. }
  9586. _mesh.material = null;
  9587. _mesh.geometry.index = null;
  9588. _mesh.geometry.attributes = {};
  9589. _mesh.geometry.setDrawRange( 0, Infinity );
  9590. }
  9591. copy( source ) {
  9592. super.copy( source );
  9593. this.geometry = source.geometry.clone();
  9594. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9595. this.sortObjects = source.sortObjects;
  9596. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9597. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9598. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9599. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9600. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9601. this._bounds = source._bounds.map( bound => ( {
  9602. boxInitialized: bound.boxInitialized,
  9603. box: bound.box.clone(),
  9604. sphereInitialized: bound.sphereInitialized,
  9605. sphere: bound.sphere.clone()
  9606. } ) );
  9607. this._maxInstanceCount = source._maxInstanceCount;
  9608. this._maxVertexCount = source._maxVertexCount;
  9609. this._maxIndexCount = source._maxIndexCount;
  9610. this._geometryInitialized = source._geometryInitialized;
  9611. this._geometryCount = source._geometryCount;
  9612. this._multiDrawCounts = source._multiDrawCounts.slice();
  9613. this._multiDrawStarts = source._multiDrawStarts.slice();
  9614. this._matricesTexture = source._matricesTexture.clone();
  9615. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9616. if ( this._colorsTexture !== null ) {
  9617. this._colorsTexture = source._colorsTexture.clone();
  9618. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9619. }
  9620. return this;
  9621. }
  9622. dispose() {
  9623. // Assuming the geometry is not shared with other meshes
  9624. this.geometry.dispose();
  9625. this._matricesTexture.dispose();
  9626. this._matricesTexture = null;
  9627. this._indirectTexture.dispose();
  9628. this._indirectTexture = null;
  9629. if ( this._colorsTexture !== null ) {
  9630. this._colorsTexture.dispose();
  9631. this._colorsTexture = null;
  9632. }
  9633. return this;
  9634. }
  9635. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9636. // if visibility has not changed and frustum culling and object sorting is not required
  9637. // then skip iterating over all items
  9638. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9639. return;
  9640. }
  9641. // the indexed version of the multi draw function requires specifying the start
  9642. // offset in bytes.
  9643. const index = geometry.getIndex();
  9644. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9645. const drawInfo = this._drawInfo;
  9646. const multiDrawStarts = this._multiDrawStarts;
  9647. const multiDrawCounts = this._multiDrawCounts;
  9648. const drawRanges = this._drawRanges;
  9649. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9650. const indirectTexture = this._indirectTexture;
  9651. const indirectArray = indirectTexture.image.data;
  9652. // prepare the frustum in the local frame
  9653. if ( perObjectFrustumCulled ) {
  9654. _projScreenMatrix$3
  9655. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9656. .multiply( this.matrixWorld );
  9657. _frustum$1.setFromProjectionMatrix(
  9658. _projScreenMatrix$3,
  9659. renderer.coordinateSystem
  9660. );
  9661. }
  9662. let count = 0;
  9663. if ( this.sortObjects ) {
  9664. // get the camera position in the local frame
  9665. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9666. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9667. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9668. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9669. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9670. const geometryId = drawInfo[ i ].geometryIndex;
  9671. // get the bounds in world space
  9672. this.getMatrixAt( i, _matrix$1 );
  9673. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9674. // determine whether the batched geometry is within the frustum
  9675. let culled = false;
  9676. if ( perObjectFrustumCulled ) {
  9677. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9678. }
  9679. if ( ! culled ) {
  9680. // get the distance from camera used for sorting
  9681. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9682. _renderList.push( drawRanges[ geometryId ], z, i );
  9683. }
  9684. }
  9685. }
  9686. // Sort the draw ranges and prep for rendering
  9687. const list = _renderList.list;
  9688. const customSort = this.customSort;
  9689. if ( customSort === null ) {
  9690. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9691. } else {
  9692. customSort.call( this, list, camera );
  9693. }
  9694. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9695. const item = list[ i ];
  9696. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9697. multiDrawCounts[ count ] = item.count;
  9698. indirectArray[ count ] = item.index;
  9699. count ++;
  9700. }
  9701. _renderList.reset();
  9702. } else {
  9703. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9704. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9705. const geometryId = drawInfo[ i ].geometryIndex;
  9706. // determine whether the batched geometry is within the frustum
  9707. let culled = false;
  9708. if ( perObjectFrustumCulled ) {
  9709. // get the bounds in world space
  9710. this.getMatrixAt( i, _matrix$1 );
  9711. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9712. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9713. }
  9714. if ( ! culled ) {
  9715. const range = drawRanges[ geometryId ];
  9716. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9717. multiDrawCounts[ count ] = range.count;
  9718. indirectArray[ count ] = i;
  9719. count ++;
  9720. }
  9721. }
  9722. }
  9723. }
  9724. indirectTexture.needsUpdate = true;
  9725. this._multiDrawCount = count;
  9726. this._visibilityChanged = false;
  9727. }
  9728. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9729. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9730. }
  9731. }
  9732. class LineBasicMaterial extends Material {
  9733. constructor( parameters ) {
  9734. super();
  9735. this.isLineBasicMaterial = true;
  9736. this.type = 'LineBasicMaterial';
  9737. this.color = new Color( 0xffffff );
  9738. this.map = null;
  9739. this.linewidth = 1;
  9740. this.linecap = 'round';
  9741. this.linejoin = 'round';
  9742. this.fog = true;
  9743. this.setValues( parameters );
  9744. }
  9745. copy( source ) {
  9746. super.copy( source );
  9747. this.color.copy( source.color );
  9748. this.map = source.map;
  9749. this.linewidth = source.linewidth;
  9750. this.linecap = source.linecap;
  9751. this.linejoin = source.linejoin;
  9752. this.fog = source.fog;
  9753. return this;
  9754. }
  9755. }
  9756. const _vStart = /*@__PURE__*/ new Vector3();
  9757. const _vEnd = /*@__PURE__*/ new Vector3();
  9758. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9759. const _ray$1 = /*@__PURE__*/ new Ray();
  9760. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9761. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9762. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9763. class Line extends Object3D {
  9764. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9765. super();
  9766. this.isLine = true;
  9767. this.type = 'Line';
  9768. this.geometry = geometry;
  9769. this.material = material;
  9770. this.updateMorphTargets();
  9771. }
  9772. copy( source, recursive ) {
  9773. super.copy( source, recursive );
  9774. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9775. this.geometry = source.geometry;
  9776. return this;
  9777. }
  9778. computeLineDistances() {
  9779. const geometry = this.geometry;
  9780. // we assume non-indexed geometry
  9781. if ( geometry.index === null ) {
  9782. const positionAttribute = geometry.attributes.position;
  9783. const lineDistances = [ 0 ];
  9784. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9785. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9786. _vEnd.fromBufferAttribute( positionAttribute, i );
  9787. lineDistances[ i ] = lineDistances[ i - 1 ];
  9788. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9789. }
  9790. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9791. } else {
  9792. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9793. }
  9794. return this;
  9795. }
  9796. raycast( raycaster, intersects ) {
  9797. const geometry = this.geometry;
  9798. const matrixWorld = this.matrixWorld;
  9799. const threshold = raycaster.params.Line.threshold;
  9800. const drawRange = geometry.drawRange;
  9801. // Checking boundingSphere distance to ray
  9802. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9803. _sphere$1.copy( geometry.boundingSphere );
  9804. _sphere$1.applyMatrix4( matrixWorld );
  9805. _sphere$1.radius += threshold;
  9806. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9807. //
  9808. _inverseMatrix$1.copy( matrixWorld ).invert();
  9809. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9810. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9811. const localThresholdSq = localThreshold * localThreshold;
  9812. const step = this.isLineSegments ? 2 : 1;
  9813. const index = geometry.index;
  9814. const attributes = geometry.attributes;
  9815. const positionAttribute = attributes.position;
  9816. if ( index !== null ) {
  9817. const start = Math.max( 0, drawRange.start );
  9818. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9819. for ( let i = start, l = end - 1; i < l; i += step ) {
  9820. const a = index.getX( i );
  9821. const b = index.getX( i + 1 );
  9822. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9823. if ( intersect ) {
  9824. intersects.push( intersect );
  9825. }
  9826. }
  9827. if ( this.isLineLoop ) {
  9828. const a = index.getX( end - 1 );
  9829. const b = index.getX( start );
  9830. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9831. if ( intersect ) {
  9832. intersects.push( intersect );
  9833. }
  9834. }
  9835. } else {
  9836. const start = Math.max( 0, drawRange.start );
  9837. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9838. for ( let i = start, l = end - 1; i < l; i += step ) {
  9839. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9840. if ( intersect ) {
  9841. intersects.push( intersect );
  9842. }
  9843. }
  9844. if ( this.isLineLoop ) {
  9845. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9846. if ( intersect ) {
  9847. intersects.push( intersect );
  9848. }
  9849. }
  9850. }
  9851. }
  9852. updateMorphTargets() {
  9853. const geometry = this.geometry;
  9854. const morphAttributes = geometry.morphAttributes;
  9855. const keys = Object.keys( morphAttributes );
  9856. if ( keys.length > 0 ) {
  9857. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9858. if ( morphAttribute !== undefined ) {
  9859. this.morphTargetInfluences = [];
  9860. this.morphTargetDictionary = {};
  9861. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9862. const name = morphAttribute[ m ].name || String( m );
  9863. this.morphTargetInfluences.push( 0 );
  9864. this.morphTargetDictionary[ name ] = m;
  9865. }
  9866. }
  9867. }
  9868. }
  9869. }
  9870. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9871. const positionAttribute = object.geometry.attributes.position;
  9872. _vStart.fromBufferAttribute( positionAttribute, a );
  9873. _vEnd.fromBufferAttribute( positionAttribute, b );
  9874. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9875. if ( distSq > thresholdSq ) return;
  9876. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9877. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9878. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9879. return {
  9880. distance: distance,
  9881. // What do we want? intersection point on the ray or on the segment??
  9882. // point: raycaster.ray.at( distance ),
  9883. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9884. index: a,
  9885. face: null,
  9886. faceIndex: null,
  9887. object: object
  9888. };
  9889. }
  9890. const _start = /*@__PURE__*/ new Vector3();
  9891. const _end = /*@__PURE__*/ new Vector3();
  9892. class LineSegments extends Line {
  9893. constructor( geometry, material ) {
  9894. super( geometry, material );
  9895. this.isLineSegments = true;
  9896. this.type = 'LineSegments';
  9897. }
  9898. computeLineDistances() {
  9899. const geometry = this.geometry;
  9900. // we assume non-indexed geometry
  9901. if ( geometry.index === null ) {
  9902. const positionAttribute = geometry.attributes.position;
  9903. const lineDistances = [];
  9904. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9905. _start.fromBufferAttribute( positionAttribute, i );
  9906. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9907. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9908. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9909. }
  9910. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9911. } else {
  9912. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9913. }
  9914. return this;
  9915. }
  9916. }
  9917. class LineLoop extends Line {
  9918. constructor( geometry, material ) {
  9919. super( geometry, material );
  9920. this.isLineLoop = true;
  9921. this.type = 'LineLoop';
  9922. }
  9923. }
  9924. class PointsMaterial extends Material {
  9925. constructor( parameters ) {
  9926. super();
  9927. this.isPointsMaterial = true;
  9928. this.type = 'PointsMaterial';
  9929. this.color = new Color( 0xffffff );
  9930. this.map = null;
  9931. this.alphaMap = null;
  9932. this.size = 1;
  9933. this.sizeAttenuation = true;
  9934. this.fog = true;
  9935. this.setValues( parameters );
  9936. }
  9937. copy( source ) {
  9938. super.copy( source );
  9939. this.color.copy( source.color );
  9940. this.map = source.map;
  9941. this.alphaMap = source.alphaMap;
  9942. this.size = source.size;
  9943. this.sizeAttenuation = source.sizeAttenuation;
  9944. this.fog = source.fog;
  9945. return this;
  9946. }
  9947. }
  9948. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  9949. const _ray = /*@__PURE__*/ new Ray();
  9950. const _sphere = /*@__PURE__*/ new Sphere();
  9951. const _position$2 = /*@__PURE__*/ new Vector3();
  9952. class Points extends Object3D {
  9953. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  9954. super();
  9955. this.isPoints = true;
  9956. this.type = 'Points';
  9957. this.geometry = geometry;
  9958. this.material = material;
  9959. this.updateMorphTargets();
  9960. }
  9961. copy( source, recursive ) {
  9962. super.copy( source, recursive );
  9963. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9964. this.geometry = source.geometry;
  9965. return this;
  9966. }
  9967. raycast( raycaster, intersects ) {
  9968. const geometry = this.geometry;
  9969. const matrixWorld = this.matrixWorld;
  9970. const threshold = raycaster.params.Points.threshold;
  9971. const drawRange = geometry.drawRange;
  9972. // Checking boundingSphere distance to ray
  9973. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9974. _sphere.copy( geometry.boundingSphere );
  9975. _sphere.applyMatrix4( matrixWorld );
  9976. _sphere.radius += threshold;
  9977. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  9978. //
  9979. _inverseMatrix.copy( matrixWorld ).invert();
  9980. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  9981. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9982. const localThresholdSq = localThreshold * localThreshold;
  9983. const index = geometry.index;
  9984. const attributes = geometry.attributes;
  9985. const positionAttribute = attributes.position;
  9986. if ( index !== null ) {
  9987. const start = Math.max( 0, drawRange.start );
  9988. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9989. for ( let i = start, il = end; i < il; i ++ ) {
  9990. const a = index.getX( i );
  9991. _position$2.fromBufferAttribute( positionAttribute, a );
  9992. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  9993. }
  9994. } else {
  9995. const start = Math.max( 0, drawRange.start );
  9996. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9997. for ( let i = start, l = end; i < l; i ++ ) {
  9998. _position$2.fromBufferAttribute( positionAttribute, i );
  9999. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10000. }
  10001. }
  10002. }
  10003. updateMorphTargets() {
  10004. const geometry = this.geometry;
  10005. const morphAttributes = geometry.morphAttributes;
  10006. const keys = Object.keys( morphAttributes );
  10007. if ( keys.length > 0 ) {
  10008. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10009. if ( morphAttribute !== undefined ) {
  10010. this.morphTargetInfluences = [];
  10011. this.morphTargetDictionary = {};
  10012. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10013. const name = morphAttribute[ m ].name || String( m );
  10014. this.morphTargetInfluences.push( 0 );
  10015. this.morphTargetDictionary[ name ] = m;
  10016. }
  10017. }
  10018. }
  10019. }
  10020. }
  10021. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10022. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10023. if ( rayPointDistanceSq < localThresholdSq ) {
  10024. const intersectPoint = new Vector3();
  10025. _ray.closestPointToPoint( point, intersectPoint );
  10026. intersectPoint.applyMatrix4( matrixWorld );
  10027. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10028. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10029. intersects.push( {
  10030. distance: distance,
  10031. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10032. point: intersectPoint,
  10033. index: index,
  10034. face: null,
  10035. object: object
  10036. } );
  10037. }
  10038. }
  10039. class Group extends Object3D {
  10040. constructor() {
  10041. super();
  10042. this.isGroup = true;
  10043. this.type = 'Group';
  10044. }
  10045. }
  10046. class VideoTexture extends Texture {
  10047. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10048. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10049. this.isVideoTexture = true;
  10050. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10051. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10052. this.generateMipmaps = false;
  10053. const scope = this;
  10054. function updateVideo() {
  10055. scope.needsUpdate = true;
  10056. video.requestVideoFrameCallback( updateVideo );
  10057. }
  10058. if ( 'requestVideoFrameCallback' in video ) {
  10059. video.requestVideoFrameCallback( updateVideo );
  10060. }
  10061. }
  10062. clone() {
  10063. return new this.constructor( this.image ).copy( this );
  10064. }
  10065. update() {
  10066. const video = this.image;
  10067. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10068. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10069. this.needsUpdate = true;
  10070. }
  10071. }
  10072. }
  10073. class FramebufferTexture extends Texture {
  10074. constructor( width, height ) {
  10075. super( { width, height } );
  10076. this.isFramebufferTexture = true;
  10077. this.magFilter = NearestFilter;
  10078. this.minFilter = NearestFilter;
  10079. this.generateMipmaps = false;
  10080. this.needsUpdate = true;
  10081. }
  10082. }
  10083. class CompressedTexture extends Texture {
  10084. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10085. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10086. this.isCompressedTexture = true;
  10087. this.image = { width: width, height: height };
  10088. this.mipmaps = mipmaps;
  10089. // no flipping for cube textures
  10090. // (also flipping doesn't work for compressed textures )
  10091. this.flipY = false;
  10092. // can't generate mipmaps for compressed textures
  10093. // mips must be embedded in DDS files
  10094. this.generateMipmaps = false;
  10095. }
  10096. }
  10097. class CompressedArrayTexture extends CompressedTexture {
  10098. constructor( mipmaps, width, height, depth, format, type ) {
  10099. super( mipmaps, width, height, format, type );
  10100. this.isCompressedArrayTexture = true;
  10101. this.image.depth = depth;
  10102. this.wrapR = ClampToEdgeWrapping;
  10103. this.layerUpdates = new Set();
  10104. }
  10105. addLayerUpdate( layerIndex ) {
  10106. this.layerUpdates.add( layerIndex );
  10107. }
  10108. clearLayerUpdates() {
  10109. this.layerUpdates.clear();
  10110. }
  10111. }
  10112. class CompressedCubeTexture extends CompressedTexture {
  10113. constructor( images, format, type ) {
  10114. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10115. this.isCompressedCubeTexture = true;
  10116. this.isCubeTexture = true;
  10117. this.image = images;
  10118. }
  10119. }
  10120. class CanvasTexture extends Texture {
  10121. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10122. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10123. this.isCanvasTexture = true;
  10124. this.needsUpdate = true;
  10125. }
  10126. }
  10127. class DepthTexture extends Texture {
  10128. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10129. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10130. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10131. }
  10132. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10133. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10134. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10135. this.isDepthTexture = true;
  10136. this.image = { width: width, height: height };
  10137. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10138. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10139. this.flipY = false;
  10140. this.generateMipmaps = false;
  10141. this.compareFunction = null;
  10142. }
  10143. copy( source ) {
  10144. super.copy( source );
  10145. this.compareFunction = source.compareFunction;
  10146. return this;
  10147. }
  10148. toJSON( meta ) {
  10149. const data = super.toJSON( meta );
  10150. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10151. return data;
  10152. }
  10153. }
  10154. /**
  10155. * Extensible curve object.
  10156. *
  10157. * Some common of curve methods:
  10158. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10159. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10160. * .getPoints(), .getSpacedPoints()
  10161. * .getLength()
  10162. * .updateArcLengths()
  10163. *
  10164. * This following curves inherit from THREE.Curve:
  10165. *
  10166. * -- 2D curves --
  10167. * THREE.ArcCurve
  10168. * THREE.CubicBezierCurve
  10169. * THREE.EllipseCurve
  10170. * THREE.LineCurve
  10171. * THREE.QuadraticBezierCurve
  10172. * THREE.SplineCurve
  10173. *
  10174. * -- 3D curves --
  10175. * THREE.CatmullRomCurve3
  10176. * THREE.CubicBezierCurve3
  10177. * THREE.LineCurve3
  10178. * THREE.QuadraticBezierCurve3
  10179. *
  10180. * A series of curves can be represented as a THREE.CurvePath.
  10181. *
  10182. **/
  10183. class Curve {
  10184. constructor() {
  10185. this.type = 'Curve';
  10186. this.arcLengthDivisions = 200;
  10187. }
  10188. // Virtual base class method to overwrite and implement in subclasses
  10189. // - t [0 .. 1]
  10190. getPoint( /* t, optionalTarget */ ) {
  10191. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10192. return null;
  10193. }
  10194. // Get point at relative position in curve according to arc length
  10195. // - u [0 .. 1]
  10196. getPointAt( u, optionalTarget ) {
  10197. const t = this.getUtoTmapping( u );
  10198. return this.getPoint( t, optionalTarget );
  10199. }
  10200. // Get sequence of points using getPoint( t )
  10201. getPoints( divisions = 5 ) {
  10202. const points = [];
  10203. for ( let d = 0; d <= divisions; d ++ ) {
  10204. points.push( this.getPoint( d / divisions ) );
  10205. }
  10206. return points;
  10207. }
  10208. // Get sequence of points using getPointAt( u )
  10209. getSpacedPoints( divisions = 5 ) {
  10210. const points = [];
  10211. for ( let d = 0; d <= divisions; d ++ ) {
  10212. points.push( this.getPointAt( d / divisions ) );
  10213. }
  10214. return points;
  10215. }
  10216. // Get total curve arc length
  10217. getLength() {
  10218. const lengths = this.getLengths();
  10219. return lengths[ lengths.length - 1 ];
  10220. }
  10221. // Get list of cumulative segment lengths
  10222. getLengths( divisions = this.arcLengthDivisions ) {
  10223. if ( this.cacheArcLengths &&
  10224. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10225. ! this.needsUpdate ) {
  10226. return this.cacheArcLengths;
  10227. }
  10228. this.needsUpdate = false;
  10229. const cache = [];
  10230. let current, last = this.getPoint( 0 );
  10231. let sum = 0;
  10232. cache.push( 0 );
  10233. for ( let p = 1; p <= divisions; p ++ ) {
  10234. current = this.getPoint( p / divisions );
  10235. sum += current.distanceTo( last );
  10236. cache.push( sum );
  10237. last = current;
  10238. }
  10239. this.cacheArcLengths = cache;
  10240. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10241. }
  10242. updateArcLengths() {
  10243. this.needsUpdate = true;
  10244. this.getLengths();
  10245. }
  10246. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10247. getUtoTmapping( u, distance ) {
  10248. const arcLengths = this.getLengths();
  10249. let i = 0;
  10250. const il = arcLengths.length;
  10251. let targetArcLength; // The targeted u distance value to get
  10252. if ( distance ) {
  10253. targetArcLength = distance;
  10254. } else {
  10255. targetArcLength = u * arcLengths[ il - 1 ];
  10256. }
  10257. // binary search for the index with largest value smaller than target u distance
  10258. let low = 0, high = il - 1, comparison;
  10259. while ( low <= high ) {
  10260. 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
  10261. comparison = arcLengths[ i ] - targetArcLength;
  10262. if ( comparison < 0 ) {
  10263. low = i + 1;
  10264. } else if ( comparison > 0 ) {
  10265. high = i - 1;
  10266. } else {
  10267. high = i;
  10268. break;
  10269. // DONE
  10270. }
  10271. }
  10272. i = high;
  10273. if ( arcLengths[ i ] === targetArcLength ) {
  10274. return i / ( il - 1 );
  10275. }
  10276. // we could get finer grain at lengths, or use simple interpolation between two points
  10277. const lengthBefore = arcLengths[ i ];
  10278. const lengthAfter = arcLengths[ i + 1 ];
  10279. const segmentLength = lengthAfter - lengthBefore;
  10280. // determine where we are between the 'before' and 'after' points
  10281. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10282. // add that fractional amount to t
  10283. const t = ( i + segmentFraction ) / ( il - 1 );
  10284. return t;
  10285. }
  10286. // Returns a unit vector tangent at t
  10287. // In case any sub curve does not implement its tangent derivation,
  10288. // 2 points a small delta apart will be used to find its gradient
  10289. // which seems to give a reasonable approximation
  10290. getTangent( t, optionalTarget ) {
  10291. const delta = 0.0001;
  10292. let t1 = t - delta;
  10293. let t2 = t + delta;
  10294. // Capping in case of danger
  10295. if ( t1 < 0 ) t1 = 0;
  10296. if ( t2 > 1 ) t2 = 1;
  10297. const pt1 = this.getPoint( t1 );
  10298. const pt2 = this.getPoint( t2 );
  10299. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10300. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10301. return tangent;
  10302. }
  10303. getTangentAt( u, optionalTarget ) {
  10304. const t = this.getUtoTmapping( u );
  10305. return this.getTangent( t, optionalTarget );
  10306. }
  10307. computeFrenetFrames( segments, closed ) {
  10308. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10309. const normal = new Vector3();
  10310. const tangents = [];
  10311. const normals = [];
  10312. const binormals = [];
  10313. const vec = new Vector3();
  10314. const mat = new Matrix4();
  10315. // compute the tangent vectors for each segment on the curve
  10316. for ( let i = 0; i <= segments; i ++ ) {
  10317. const u = i / segments;
  10318. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10319. }
  10320. // select an initial normal vector perpendicular to the first tangent vector,
  10321. // and in the direction of the minimum tangent xyz component
  10322. normals[ 0 ] = new Vector3();
  10323. binormals[ 0 ] = new Vector3();
  10324. let min = Number.MAX_VALUE;
  10325. const tx = Math.abs( tangents[ 0 ].x );
  10326. const ty = Math.abs( tangents[ 0 ].y );
  10327. const tz = Math.abs( tangents[ 0 ].z );
  10328. if ( tx <= min ) {
  10329. min = tx;
  10330. normal.set( 1, 0, 0 );
  10331. }
  10332. if ( ty <= min ) {
  10333. min = ty;
  10334. normal.set( 0, 1, 0 );
  10335. }
  10336. if ( tz <= min ) {
  10337. normal.set( 0, 0, 1 );
  10338. }
  10339. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10340. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10341. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10342. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10343. for ( let i = 1; i <= segments; i ++ ) {
  10344. normals[ i ] = normals[ i - 1 ].clone();
  10345. binormals[ i ] = binormals[ i - 1 ].clone();
  10346. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10347. if ( vec.length() > Number.EPSILON ) {
  10348. vec.normalize();
  10349. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10350. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10351. }
  10352. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10353. }
  10354. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10355. if ( closed === true ) {
  10356. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10357. theta /= segments;
  10358. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10359. theta = - theta;
  10360. }
  10361. for ( let i = 1; i <= segments; i ++ ) {
  10362. // twist a little...
  10363. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10364. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10365. }
  10366. }
  10367. return {
  10368. tangents: tangents,
  10369. normals: normals,
  10370. binormals: binormals
  10371. };
  10372. }
  10373. clone() {
  10374. return new this.constructor().copy( this );
  10375. }
  10376. copy( source ) {
  10377. this.arcLengthDivisions = source.arcLengthDivisions;
  10378. return this;
  10379. }
  10380. toJSON() {
  10381. const data = {
  10382. metadata: {
  10383. version: 4.6,
  10384. type: 'Curve',
  10385. generator: 'Curve.toJSON'
  10386. }
  10387. };
  10388. data.arcLengthDivisions = this.arcLengthDivisions;
  10389. data.type = this.type;
  10390. return data;
  10391. }
  10392. fromJSON( json ) {
  10393. this.arcLengthDivisions = json.arcLengthDivisions;
  10394. return this;
  10395. }
  10396. }
  10397. class EllipseCurve extends Curve {
  10398. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10399. super();
  10400. this.isEllipseCurve = true;
  10401. this.type = 'EllipseCurve';
  10402. this.aX = aX;
  10403. this.aY = aY;
  10404. this.xRadius = xRadius;
  10405. this.yRadius = yRadius;
  10406. this.aStartAngle = aStartAngle;
  10407. this.aEndAngle = aEndAngle;
  10408. this.aClockwise = aClockwise;
  10409. this.aRotation = aRotation;
  10410. }
  10411. getPoint( t, optionalTarget = new Vector2() ) {
  10412. const point = optionalTarget;
  10413. const twoPi = Math.PI * 2;
  10414. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10415. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10416. // ensures that deltaAngle is 0 .. 2 PI
  10417. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10418. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10419. if ( deltaAngle < Number.EPSILON ) {
  10420. if ( samePoints ) {
  10421. deltaAngle = 0;
  10422. } else {
  10423. deltaAngle = twoPi;
  10424. }
  10425. }
  10426. if ( this.aClockwise === true && ! samePoints ) {
  10427. if ( deltaAngle === twoPi ) {
  10428. deltaAngle = - twoPi;
  10429. } else {
  10430. deltaAngle = deltaAngle - twoPi;
  10431. }
  10432. }
  10433. const angle = this.aStartAngle + t * deltaAngle;
  10434. let x = this.aX + this.xRadius * Math.cos( angle );
  10435. let y = this.aY + this.yRadius * Math.sin( angle );
  10436. if ( this.aRotation !== 0 ) {
  10437. const cos = Math.cos( this.aRotation );
  10438. const sin = Math.sin( this.aRotation );
  10439. const tx = x - this.aX;
  10440. const ty = y - this.aY;
  10441. // Rotate the point about the center of the ellipse.
  10442. x = tx * cos - ty * sin + this.aX;
  10443. y = tx * sin + ty * cos + this.aY;
  10444. }
  10445. return point.set( x, y );
  10446. }
  10447. copy( source ) {
  10448. super.copy( source );
  10449. this.aX = source.aX;
  10450. this.aY = source.aY;
  10451. this.xRadius = source.xRadius;
  10452. this.yRadius = source.yRadius;
  10453. this.aStartAngle = source.aStartAngle;
  10454. this.aEndAngle = source.aEndAngle;
  10455. this.aClockwise = source.aClockwise;
  10456. this.aRotation = source.aRotation;
  10457. return this;
  10458. }
  10459. toJSON() {
  10460. const data = super.toJSON();
  10461. data.aX = this.aX;
  10462. data.aY = this.aY;
  10463. data.xRadius = this.xRadius;
  10464. data.yRadius = this.yRadius;
  10465. data.aStartAngle = this.aStartAngle;
  10466. data.aEndAngle = this.aEndAngle;
  10467. data.aClockwise = this.aClockwise;
  10468. data.aRotation = this.aRotation;
  10469. return data;
  10470. }
  10471. fromJSON( json ) {
  10472. super.fromJSON( json );
  10473. this.aX = json.aX;
  10474. this.aY = json.aY;
  10475. this.xRadius = json.xRadius;
  10476. this.yRadius = json.yRadius;
  10477. this.aStartAngle = json.aStartAngle;
  10478. this.aEndAngle = json.aEndAngle;
  10479. this.aClockwise = json.aClockwise;
  10480. this.aRotation = json.aRotation;
  10481. return this;
  10482. }
  10483. }
  10484. class ArcCurve extends EllipseCurve {
  10485. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10486. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10487. this.isArcCurve = true;
  10488. this.type = 'ArcCurve';
  10489. }
  10490. }
  10491. /**
  10492. * Centripetal CatmullRom Curve - which is useful for avoiding
  10493. * cusps and self-intersections in non-uniform catmull rom curves.
  10494. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10495. *
  10496. * curve.type accepts centripetal(default), chordal and catmullrom
  10497. * curve.tension is used for catmullrom which defaults to 0.5
  10498. */
  10499. /*
  10500. Based on an optimized c++ solution in
  10501. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10502. - http://ideone.com/NoEbVM
  10503. This CubicPoly class could be used for reusing some variables and calculations,
  10504. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10505. which can be placed in CurveUtils.
  10506. */
  10507. function CubicPoly() {
  10508. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10509. /*
  10510. * Compute coefficients for a cubic polynomial
  10511. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10512. * such that
  10513. * p(0) = x0, p(1) = x1
  10514. * and
  10515. * p'(0) = t0, p'(1) = t1.
  10516. */
  10517. function init( x0, x1, t0, t1 ) {
  10518. c0 = x0;
  10519. c1 = t0;
  10520. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10521. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10522. }
  10523. return {
  10524. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10525. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10526. },
  10527. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10528. // compute tangents when parameterized in [t1,t2]
  10529. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10530. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10531. // rescale tangents for parametrization in [0,1]
  10532. t1 *= dt1;
  10533. t2 *= dt1;
  10534. init( x1, x2, t1, t2 );
  10535. },
  10536. calc: function ( t ) {
  10537. const t2 = t * t;
  10538. const t3 = t2 * t;
  10539. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10540. }
  10541. };
  10542. }
  10543. //
  10544. const tmp = /*@__PURE__*/ new Vector3();
  10545. const px = /*@__PURE__*/ new CubicPoly();
  10546. const py = /*@__PURE__*/ new CubicPoly();
  10547. const pz = /*@__PURE__*/ new CubicPoly();
  10548. class CatmullRomCurve3 extends Curve {
  10549. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10550. super();
  10551. this.isCatmullRomCurve3 = true;
  10552. this.type = 'CatmullRomCurve3';
  10553. this.points = points;
  10554. this.closed = closed;
  10555. this.curveType = curveType;
  10556. this.tension = tension;
  10557. }
  10558. getPoint( t, optionalTarget = new Vector3() ) {
  10559. const point = optionalTarget;
  10560. const points = this.points;
  10561. const l = points.length;
  10562. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10563. let intPoint = Math.floor( p );
  10564. let weight = p - intPoint;
  10565. if ( this.closed ) {
  10566. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10567. } else if ( weight === 0 && intPoint === l - 1 ) {
  10568. intPoint = l - 2;
  10569. weight = 1;
  10570. }
  10571. let p0, p3; // 4 points (p1 & p2 defined below)
  10572. if ( this.closed || intPoint > 0 ) {
  10573. p0 = points[ ( intPoint - 1 ) % l ];
  10574. } else {
  10575. // extrapolate first point
  10576. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10577. p0 = tmp;
  10578. }
  10579. const p1 = points[ intPoint % l ];
  10580. const p2 = points[ ( intPoint + 1 ) % l ];
  10581. if ( this.closed || intPoint + 2 < l ) {
  10582. p3 = points[ ( intPoint + 2 ) % l ];
  10583. } else {
  10584. // extrapolate last point
  10585. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10586. p3 = tmp;
  10587. }
  10588. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10589. // init Centripetal / Chordal Catmull-Rom
  10590. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10591. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10592. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10593. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10594. // safety check for repeated points
  10595. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10596. if ( dt0 < 1e-4 ) dt0 = dt1;
  10597. if ( dt2 < 1e-4 ) dt2 = dt1;
  10598. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10599. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10600. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10601. } else if ( this.curveType === 'catmullrom' ) {
  10602. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10603. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10604. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10605. }
  10606. point.set(
  10607. px.calc( weight ),
  10608. py.calc( weight ),
  10609. pz.calc( weight )
  10610. );
  10611. return point;
  10612. }
  10613. copy( source ) {
  10614. super.copy( source );
  10615. this.points = [];
  10616. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10617. const point = source.points[ i ];
  10618. this.points.push( point.clone() );
  10619. }
  10620. this.closed = source.closed;
  10621. this.curveType = source.curveType;
  10622. this.tension = source.tension;
  10623. return this;
  10624. }
  10625. toJSON() {
  10626. const data = super.toJSON();
  10627. data.points = [];
  10628. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10629. const point = this.points[ i ];
  10630. data.points.push( point.toArray() );
  10631. }
  10632. data.closed = this.closed;
  10633. data.curveType = this.curveType;
  10634. data.tension = this.tension;
  10635. return data;
  10636. }
  10637. fromJSON( json ) {
  10638. super.fromJSON( json );
  10639. this.points = [];
  10640. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10641. const point = json.points[ i ];
  10642. this.points.push( new Vector3().fromArray( point ) );
  10643. }
  10644. this.closed = json.closed;
  10645. this.curveType = json.curveType;
  10646. this.tension = json.tension;
  10647. return this;
  10648. }
  10649. }
  10650. /**
  10651. * Bezier Curves formulas obtained from
  10652. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10653. */
  10654. function CatmullRom( t, p0, p1, p2, p3 ) {
  10655. const v0 = ( p2 - p0 ) * 0.5;
  10656. const v1 = ( p3 - p1 ) * 0.5;
  10657. const t2 = t * t;
  10658. const t3 = t * t2;
  10659. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10660. }
  10661. //
  10662. function QuadraticBezierP0( t, p ) {
  10663. const k = 1 - t;
  10664. return k * k * p;
  10665. }
  10666. function QuadraticBezierP1( t, p ) {
  10667. return 2 * ( 1 - t ) * t * p;
  10668. }
  10669. function QuadraticBezierP2( t, p ) {
  10670. return t * t * p;
  10671. }
  10672. function QuadraticBezier( t, p0, p1, p2 ) {
  10673. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10674. QuadraticBezierP2( t, p2 );
  10675. }
  10676. //
  10677. function CubicBezierP0( t, p ) {
  10678. const k = 1 - t;
  10679. return k * k * k * p;
  10680. }
  10681. function CubicBezierP1( t, p ) {
  10682. const k = 1 - t;
  10683. return 3 * k * k * t * p;
  10684. }
  10685. function CubicBezierP2( t, p ) {
  10686. return 3 * ( 1 - t ) * t * t * p;
  10687. }
  10688. function CubicBezierP3( t, p ) {
  10689. return t * t * t * p;
  10690. }
  10691. function CubicBezier( t, p0, p1, p2, p3 ) {
  10692. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10693. CubicBezierP3( t, p3 );
  10694. }
  10695. class CubicBezierCurve extends Curve {
  10696. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10697. super();
  10698. this.isCubicBezierCurve = true;
  10699. this.type = 'CubicBezierCurve';
  10700. this.v0 = v0;
  10701. this.v1 = v1;
  10702. this.v2 = v2;
  10703. this.v3 = v3;
  10704. }
  10705. getPoint( t, optionalTarget = new Vector2() ) {
  10706. const point = optionalTarget;
  10707. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10708. point.set(
  10709. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10710. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10711. );
  10712. return point;
  10713. }
  10714. copy( source ) {
  10715. super.copy( source );
  10716. this.v0.copy( source.v0 );
  10717. this.v1.copy( source.v1 );
  10718. this.v2.copy( source.v2 );
  10719. this.v3.copy( source.v3 );
  10720. return this;
  10721. }
  10722. toJSON() {
  10723. const data = super.toJSON();
  10724. data.v0 = this.v0.toArray();
  10725. data.v1 = this.v1.toArray();
  10726. data.v2 = this.v2.toArray();
  10727. data.v3 = this.v3.toArray();
  10728. return data;
  10729. }
  10730. fromJSON( json ) {
  10731. super.fromJSON( json );
  10732. this.v0.fromArray( json.v0 );
  10733. this.v1.fromArray( json.v1 );
  10734. this.v2.fromArray( json.v2 );
  10735. this.v3.fromArray( json.v3 );
  10736. return this;
  10737. }
  10738. }
  10739. class CubicBezierCurve3 extends Curve {
  10740. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10741. super();
  10742. this.isCubicBezierCurve3 = true;
  10743. this.type = 'CubicBezierCurve3';
  10744. this.v0 = v0;
  10745. this.v1 = v1;
  10746. this.v2 = v2;
  10747. this.v3 = v3;
  10748. }
  10749. getPoint( t, optionalTarget = new Vector3() ) {
  10750. const point = optionalTarget;
  10751. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10752. point.set(
  10753. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10754. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10755. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10756. );
  10757. return point;
  10758. }
  10759. copy( source ) {
  10760. super.copy( source );
  10761. this.v0.copy( source.v0 );
  10762. this.v1.copy( source.v1 );
  10763. this.v2.copy( source.v2 );
  10764. this.v3.copy( source.v3 );
  10765. return this;
  10766. }
  10767. toJSON() {
  10768. const data = super.toJSON();
  10769. data.v0 = this.v0.toArray();
  10770. data.v1 = this.v1.toArray();
  10771. data.v2 = this.v2.toArray();
  10772. data.v3 = this.v3.toArray();
  10773. return data;
  10774. }
  10775. fromJSON( json ) {
  10776. super.fromJSON( json );
  10777. this.v0.fromArray( json.v0 );
  10778. this.v1.fromArray( json.v1 );
  10779. this.v2.fromArray( json.v2 );
  10780. this.v3.fromArray( json.v3 );
  10781. return this;
  10782. }
  10783. }
  10784. class LineCurve extends Curve {
  10785. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10786. super();
  10787. this.isLineCurve = true;
  10788. this.type = 'LineCurve';
  10789. this.v1 = v1;
  10790. this.v2 = v2;
  10791. }
  10792. getPoint( t, optionalTarget = new Vector2() ) {
  10793. const point = optionalTarget;
  10794. if ( t === 1 ) {
  10795. point.copy( this.v2 );
  10796. } else {
  10797. point.copy( this.v2 ).sub( this.v1 );
  10798. point.multiplyScalar( t ).add( this.v1 );
  10799. }
  10800. return point;
  10801. }
  10802. // Line curve is linear, so we can overwrite default getPointAt
  10803. getPointAt( u, optionalTarget ) {
  10804. return this.getPoint( u, optionalTarget );
  10805. }
  10806. getTangent( t, optionalTarget = new Vector2() ) {
  10807. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10808. }
  10809. getTangentAt( u, optionalTarget ) {
  10810. return this.getTangent( u, optionalTarget );
  10811. }
  10812. copy( source ) {
  10813. super.copy( source );
  10814. this.v1.copy( source.v1 );
  10815. this.v2.copy( source.v2 );
  10816. return this;
  10817. }
  10818. toJSON() {
  10819. const data = super.toJSON();
  10820. data.v1 = this.v1.toArray();
  10821. data.v2 = this.v2.toArray();
  10822. return data;
  10823. }
  10824. fromJSON( json ) {
  10825. super.fromJSON( json );
  10826. this.v1.fromArray( json.v1 );
  10827. this.v2.fromArray( json.v2 );
  10828. return this;
  10829. }
  10830. }
  10831. class LineCurve3 extends Curve {
  10832. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10833. super();
  10834. this.isLineCurve3 = true;
  10835. this.type = 'LineCurve3';
  10836. this.v1 = v1;
  10837. this.v2 = v2;
  10838. }
  10839. getPoint( t, optionalTarget = new Vector3() ) {
  10840. const point = optionalTarget;
  10841. if ( t === 1 ) {
  10842. point.copy( this.v2 );
  10843. } else {
  10844. point.copy( this.v2 ).sub( this.v1 );
  10845. point.multiplyScalar( t ).add( this.v1 );
  10846. }
  10847. return point;
  10848. }
  10849. // Line curve is linear, so we can overwrite default getPointAt
  10850. getPointAt( u, optionalTarget ) {
  10851. return this.getPoint( u, optionalTarget );
  10852. }
  10853. getTangent( t, optionalTarget = new Vector3() ) {
  10854. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10855. }
  10856. getTangentAt( u, optionalTarget ) {
  10857. return this.getTangent( u, optionalTarget );
  10858. }
  10859. copy( source ) {
  10860. super.copy( source );
  10861. this.v1.copy( source.v1 );
  10862. this.v2.copy( source.v2 );
  10863. return this;
  10864. }
  10865. toJSON() {
  10866. const data = super.toJSON();
  10867. data.v1 = this.v1.toArray();
  10868. data.v2 = this.v2.toArray();
  10869. return data;
  10870. }
  10871. fromJSON( json ) {
  10872. super.fromJSON( json );
  10873. this.v1.fromArray( json.v1 );
  10874. this.v2.fromArray( json.v2 );
  10875. return this;
  10876. }
  10877. }
  10878. class QuadraticBezierCurve extends Curve {
  10879. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10880. super();
  10881. this.isQuadraticBezierCurve = true;
  10882. this.type = 'QuadraticBezierCurve';
  10883. this.v0 = v0;
  10884. this.v1 = v1;
  10885. this.v2 = v2;
  10886. }
  10887. getPoint( t, optionalTarget = new Vector2() ) {
  10888. const point = optionalTarget;
  10889. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10890. point.set(
  10891. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10892. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10893. );
  10894. return point;
  10895. }
  10896. copy( source ) {
  10897. super.copy( source );
  10898. this.v0.copy( source.v0 );
  10899. this.v1.copy( source.v1 );
  10900. this.v2.copy( source.v2 );
  10901. return this;
  10902. }
  10903. toJSON() {
  10904. const data = super.toJSON();
  10905. data.v0 = this.v0.toArray();
  10906. data.v1 = this.v1.toArray();
  10907. data.v2 = this.v2.toArray();
  10908. return data;
  10909. }
  10910. fromJSON( json ) {
  10911. super.fromJSON( json );
  10912. this.v0.fromArray( json.v0 );
  10913. this.v1.fromArray( json.v1 );
  10914. this.v2.fromArray( json.v2 );
  10915. return this;
  10916. }
  10917. }
  10918. class QuadraticBezierCurve3 extends Curve {
  10919. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10920. super();
  10921. this.isQuadraticBezierCurve3 = true;
  10922. this.type = 'QuadraticBezierCurve3';
  10923. this.v0 = v0;
  10924. this.v1 = v1;
  10925. this.v2 = v2;
  10926. }
  10927. getPoint( t, optionalTarget = new Vector3() ) {
  10928. const point = optionalTarget;
  10929. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10930. point.set(
  10931. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10932. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10933. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10934. );
  10935. return point;
  10936. }
  10937. copy( source ) {
  10938. super.copy( source );
  10939. this.v0.copy( source.v0 );
  10940. this.v1.copy( source.v1 );
  10941. this.v2.copy( source.v2 );
  10942. return this;
  10943. }
  10944. toJSON() {
  10945. const data = super.toJSON();
  10946. data.v0 = this.v0.toArray();
  10947. data.v1 = this.v1.toArray();
  10948. data.v2 = this.v2.toArray();
  10949. return data;
  10950. }
  10951. fromJSON( json ) {
  10952. super.fromJSON( json );
  10953. this.v0.fromArray( json.v0 );
  10954. this.v1.fromArray( json.v1 );
  10955. this.v2.fromArray( json.v2 );
  10956. return this;
  10957. }
  10958. }
  10959. class SplineCurve extends Curve {
  10960. constructor( points = [] ) {
  10961. super();
  10962. this.isSplineCurve = true;
  10963. this.type = 'SplineCurve';
  10964. this.points = points;
  10965. }
  10966. getPoint( t, optionalTarget = new Vector2() ) {
  10967. const point = optionalTarget;
  10968. const points = this.points;
  10969. const p = ( points.length - 1 ) * t;
  10970. const intPoint = Math.floor( p );
  10971. const weight = p - intPoint;
  10972. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  10973. const p1 = points[ intPoint ];
  10974. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  10975. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  10976. point.set(
  10977. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  10978. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  10979. );
  10980. return point;
  10981. }
  10982. copy( source ) {
  10983. super.copy( source );
  10984. this.points = [];
  10985. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10986. const point = source.points[ i ];
  10987. this.points.push( point.clone() );
  10988. }
  10989. return this;
  10990. }
  10991. toJSON() {
  10992. const data = super.toJSON();
  10993. data.points = [];
  10994. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10995. const point = this.points[ i ];
  10996. data.points.push( point.toArray() );
  10997. }
  10998. return data;
  10999. }
  11000. fromJSON( json ) {
  11001. super.fromJSON( json );
  11002. this.points = [];
  11003. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11004. const point = json.points[ i ];
  11005. this.points.push( new Vector2().fromArray( point ) );
  11006. }
  11007. return this;
  11008. }
  11009. }
  11010. var Curves = /*#__PURE__*/Object.freeze({
  11011. __proto__: null,
  11012. ArcCurve: ArcCurve,
  11013. CatmullRomCurve3: CatmullRomCurve3,
  11014. CubicBezierCurve: CubicBezierCurve,
  11015. CubicBezierCurve3: CubicBezierCurve3,
  11016. EllipseCurve: EllipseCurve,
  11017. LineCurve: LineCurve,
  11018. LineCurve3: LineCurve3,
  11019. QuadraticBezierCurve: QuadraticBezierCurve,
  11020. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11021. SplineCurve: SplineCurve
  11022. });
  11023. /**************************************************************
  11024. * Curved Path - a curve path is simply a array of connected
  11025. * curves, but retains the api of a curve
  11026. **************************************************************/
  11027. class CurvePath extends Curve {
  11028. constructor() {
  11029. super();
  11030. this.type = 'CurvePath';
  11031. this.curves = [];
  11032. this.autoClose = false; // Automatically closes the path
  11033. }
  11034. add( curve ) {
  11035. this.curves.push( curve );
  11036. }
  11037. closePath() {
  11038. // Add a line curve if start and end of lines are not connected
  11039. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11040. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11041. if ( ! startPoint.equals( endPoint ) ) {
  11042. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11043. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11044. }
  11045. return this;
  11046. }
  11047. // To get accurate point with reference to
  11048. // entire path distance at time t,
  11049. // following has to be done:
  11050. // 1. Length of each sub path have to be known
  11051. // 2. Locate and identify type of curve
  11052. // 3. Get t for the curve
  11053. // 4. Return curve.getPointAt(t')
  11054. getPoint( t, optionalTarget ) {
  11055. const d = t * this.getLength();
  11056. const curveLengths = this.getCurveLengths();
  11057. let i = 0;
  11058. // To think about boundaries points.
  11059. while ( i < curveLengths.length ) {
  11060. if ( curveLengths[ i ] >= d ) {
  11061. const diff = curveLengths[ i ] - d;
  11062. const curve = this.curves[ i ];
  11063. const segmentLength = curve.getLength();
  11064. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11065. return curve.getPointAt( u, optionalTarget );
  11066. }
  11067. i ++;
  11068. }
  11069. return null;
  11070. // loop where sum != 0, sum > d , sum+1 <d
  11071. }
  11072. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11073. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11074. // getPoint() depends on getLength
  11075. getLength() {
  11076. const lens = this.getCurveLengths();
  11077. return lens[ lens.length - 1 ];
  11078. }
  11079. // cacheLengths must be recalculated.
  11080. updateArcLengths() {
  11081. this.needsUpdate = true;
  11082. this.cacheLengths = null;
  11083. this.getCurveLengths();
  11084. }
  11085. // Compute lengths and cache them
  11086. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11087. getCurveLengths() {
  11088. // We use cache values if curves and cache array are same length
  11089. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11090. return this.cacheLengths;
  11091. }
  11092. // Get length of sub-curve
  11093. // Push sums into cached array
  11094. const lengths = [];
  11095. let sums = 0;
  11096. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11097. sums += this.curves[ i ].getLength();
  11098. lengths.push( sums );
  11099. }
  11100. this.cacheLengths = lengths;
  11101. return lengths;
  11102. }
  11103. getSpacedPoints( divisions = 40 ) {
  11104. const points = [];
  11105. for ( let i = 0; i <= divisions; i ++ ) {
  11106. points.push( this.getPoint( i / divisions ) );
  11107. }
  11108. if ( this.autoClose ) {
  11109. points.push( points[ 0 ] );
  11110. }
  11111. return points;
  11112. }
  11113. getPoints( divisions = 12 ) {
  11114. const points = [];
  11115. let last;
  11116. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11117. const curve = curves[ i ];
  11118. const resolution = curve.isEllipseCurve ? divisions * 2
  11119. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11120. : curve.isSplineCurve ? divisions * curve.points.length
  11121. : divisions;
  11122. const pts = curve.getPoints( resolution );
  11123. for ( let j = 0; j < pts.length; j ++ ) {
  11124. const point = pts[ j ];
  11125. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11126. points.push( point );
  11127. last = point;
  11128. }
  11129. }
  11130. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11131. points.push( points[ 0 ] );
  11132. }
  11133. return points;
  11134. }
  11135. copy( source ) {
  11136. super.copy( source );
  11137. this.curves = [];
  11138. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11139. const curve = source.curves[ i ];
  11140. this.curves.push( curve.clone() );
  11141. }
  11142. this.autoClose = source.autoClose;
  11143. return this;
  11144. }
  11145. toJSON() {
  11146. const data = super.toJSON();
  11147. data.autoClose = this.autoClose;
  11148. data.curves = [];
  11149. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11150. const curve = this.curves[ i ];
  11151. data.curves.push( curve.toJSON() );
  11152. }
  11153. return data;
  11154. }
  11155. fromJSON( json ) {
  11156. super.fromJSON( json );
  11157. this.autoClose = json.autoClose;
  11158. this.curves = [];
  11159. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11160. const curve = json.curves[ i ];
  11161. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11162. }
  11163. return this;
  11164. }
  11165. }
  11166. class Path extends CurvePath {
  11167. constructor( points ) {
  11168. super();
  11169. this.type = 'Path';
  11170. this.currentPoint = new Vector2();
  11171. if ( points ) {
  11172. this.setFromPoints( points );
  11173. }
  11174. }
  11175. setFromPoints( points ) {
  11176. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11177. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11178. this.lineTo( points[ i ].x, points[ i ].y );
  11179. }
  11180. return this;
  11181. }
  11182. moveTo( x, y ) {
  11183. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11184. return this;
  11185. }
  11186. lineTo( x, y ) {
  11187. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11188. this.curves.push( curve );
  11189. this.currentPoint.set( x, y );
  11190. return this;
  11191. }
  11192. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11193. const curve = new QuadraticBezierCurve(
  11194. this.currentPoint.clone(),
  11195. new Vector2( aCPx, aCPy ),
  11196. new Vector2( aX, aY )
  11197. );
  11198. this.curves.push( curve );
  11199. this.currentPoint.set( aX, aY );
  11200. return this;
  11201. }
  11202. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11203. const curve = new CubicBezierCurve(
  11204. this.currentPoint.clone(),
  11205. new Vector2( aCP1x, aCP1y ),
  11206. new Vector2( aCP2x, aCP2y ),
  11207. new Vector2( aX, aY )
  11208. );
  11209. this.curves.push( curve );
  11210. this.currentPoint.set( aX, aY );
  11211. return this;
  11212. }
  11213. splineThru( pts /*Array of Vector*/ ) {
  11214. const npts = [ this.currentPoint.clone() ].concat( pts );
  11215. const curve = new SplineCurve( npts );
  11216. this.curves.push( curve );
  11217. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11218. return this;
  11219. }
  11220. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11221. const x0 = this.currentPoint.x;
  11222. const y0 = this.currentPoint.y;
  11223. this.absarc( aX + x0, aY + y0, aRadius,
  11224. aStartAngle, aEndAngle, aClockwise );
  11225. return this;
  11226. }
  11227. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11228. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11229. return this;
  11230. }
  11231. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11232. const x0 = this.currentPoint.x;
  11233. const y0 = this.currentPoint.y;
  11234. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11235. return this;
  11236. }
  11237. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11238. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11239. if ( this.curves.length > 0 ) {
  11240. // if a previous curve is present, attempt to join
  11241. const firstPoint = curve.getPoint( 0 );
  11242. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11243. this.lineTo( firstPoint.x, firstPoint.y );
  11244. }
  11245. }
  11246. this.curves.push( curve );
  11247. const lastPoint = curve.getPoint( 1 );
  11248. this.currentPoint.copy( lastPoint );
  11249. return this;
  11250. }
  11251. copy( source ) {
  11252. super.copy( source );
  11253. this.currentPoint.copy( source.currentPoint );
  11254. return this;
  11255. }
  11256. toJSON() {
  11257. const data = super.toJSON();
  11258. data.currentPoint = this.currentPoint.toArray();
  11259. return data;
  11260. }
  11261. fromJSON( json ) {
  11262. super.fromJSON( json );
  11263. this.currentPoint.fromArray( json.currentPoint );
  11264. return this;
  11265. }
  11266. }
  11267. class LatheGeometry extends BufferGeometry {
  11268. 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 ) {
  11269. super();
  11270. this.type = 'LatheGeometry';
  11271. this.parameters = {
  11272. points: points,
  11273. segments: segments,
  11274. phiStart: phiStart,
  11275. phiLength: phiLength
  11276. };
  11277. segments = Math.floor( segments );
  11278. // clamp phiLength so it's in range of [ 0, 2PI ]
  11279. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11280. // buffers
  11281. const indices = [];
  11282. const vertices = [];
  11283. const uvs = [];
  11284. const initNormals = [];
  11285. const normals = [];
  11286. // helper variables
  11287. const inverseSegments = 1.0 / segments;
  11288. const vertex = new Vector3();
  11289. const uv = new Vector2();
  11290. const normal = new Vector3();
  11291. const curNormal = new Vector3();
  11292. const prevNormal = new Vector3();
  11293. let dx = 0;
  11294. let dy = 0;
  11295. // pre-compute normals for initial "meridian"
  11296. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11297. switch ( j ) {
  11298. case 0: // special handling for 1st vertex on path
  11299. dx = points[ j + 1 ].x - points[ j ].x;
  11300. dy = points[ j + 1 ].y - points[ j ].y;
  11301. normal.x = dy * 1.0;
  11302. normal.y = - dx;
  11303. normal.z = dy * 0.0;
  11304. prevNormal.copy( normal );
  11305. normal.normalize();
  11306. initNormals.push( normal.x, normal.y, normal.z );
  11307. break;
  11308. case ( points.length - 1 ): // special handling for last Vertex on path
  11309. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11310. break;
  11311. default: // default handling for all vertices in between
  11312. dx = points[ j + 1 ].x - points[ j ].x;
  11313. dy = points[ j + 1 ].y - points[ j ].y;
  11314. normal.x = dy * 1.0;
  11315. normal.y = - dx;
  11316. normal.z = dy * 0.0;
  11317. curNormal.copy( normal );
  11318. normal.x += prevNormal.x;
  11319. normal.y += prevNormal.y;
  11320. normal.z += prevNormal.z;
  11321. normal.normalize();
  11322. initNormals.push( normal.x, normal.y, normal.z );
  11323. prevNormal.copy( curNormal );
  11324. }
  11325. }
  11326. // generate vertices, uvs and normals
  11327. for ( let i = 0; i <= segments; i ++ ) {
  11328. const phi = phiStart + i * inverseSegments * phiLength;
  11329. const sin = Math.sin( phi );
  11330. const cos = Math.cos( phi );
  11331. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11332. // vertex
  11333. vertex.x = points[ j ].x * sin;
  11334. vertex.y = points[ j ].y;
  11335. vertex.z = points[ j ].x * cos;
  11336. vertices.push( vertex.x, vertex.y, vertex.z );
  11337. // uv
  11338. uv.x = i / segments;
  11339. uv.y = j / ( points.length - 1 );
  11340. uvs.push( uv.x, uv.y );
  11341. // normal
  11342. const x = initNormals[ 3 * j + 0 ] * sin;
  11343. const y = initNormals[ 3 * j + 1 ];
  11344. const z = initNormals[ 3 * j + 0 ] * cos;
  11345. normals.push( x, y, z );
  11346. }
  11347. }
  11348. // indices
  11349. for ( let i = 0; i < segments; i ++ ) {
  11350. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11351. const base = j + i * points.length;
  11352. const a = base;
  11353. const b = base + points.length;
  11354. const c = base + points.length + 1;
  11355. const d = base + 1;
  11356. // faces
  11357. indices.push( a, b, d );
  11358. indices.push( c, d, b );
  11359. }
  11360. }
  11361. // build geometry
  11362. this.setIndex( indices );
  11363. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11364. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11365. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11366. }
  11367. copy( source ) {
  11368. super.copy( source );
  11369. this.parameters = Object.assign( {}, source.parameters );
  11370. return this;
  11371. }
  11372. static fromJSON( data ) {
  11373. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11374. }
  11375. }
  11376. class CapsuleGeometry extends LatheGeometry {
  11377. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11378. const path = new Path();
  11379. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11380. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11381. super( path.getPoints( capSegments ), radialSegments );
  11382. this.type = 'CapsuleGeometry';
  11383. this.parameters = {
  11384. radius: radius,
  11385. length: length,
  11386. capSegments: capSegments,
  11387. radialSegments: radialSegments,
  11388. };
  11389. }
  11390. static fromJSON( data ) {
  11391. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11392. }
  11393. }
  11394. class CircleGeometry extends BufferGeometry {
  11395. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11396. super();
  11397. this.type = 'CircleGeometry';
  11398. this.parameters = {
  11399. radius: radius,
  11400. segments: segments,
  11401. thetaStart: thetaStart,
  11402. thetaLength: thetaLength
  11403. };
  11404. segments = Math.max( 3, segments );
  11405. // buffers
  11406. const indices = [];
  11407. const vertices = [];
  11408. const normals = [];
  11409. const uvs = [];
  11410. // helper variables
  11411. const vertex = new Vector3();
  11412. const uv = new Vector2();
  11413. // center point
  11414. vertices.push( 0, 0, 0 );
  11415. normals.push( 0, 0, 1 );
  11416. uvs.push( 0.5, 0.5 );
  11417. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11418. const segment = thetaStart + s / segments * thetaLength;
  11419. // vertex
  11420. vertex.x = radius * Math.cos( segment );
  11421. vertex.y = radius * Math.sin( segment );
  11422. vertices.push( vertex.x, vertex.y, vertex.z );
  11423. // normal
  11424. normals.push( 0, 0, 1 );
  11425. // uvs
  11426. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11427. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11428. uvs.push( uv.x, uv.y );
  11429. }
  11430. // indices
  11431. for ( let i = 1; i <= segments; i ++ ) {
  11432. indices.push( i, i + 1, 0 );
  11433. }
  11434. // build geometry
  11435. this.setIndex( indices );
  11436. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11437. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11438. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11439. }
  11440. copy( source ) {
  11441. super.copy( source );
  11442. this.parameters = Object.assign( {}, source.parameters );
  11443. return this;
  11444. }
  11445. static fromJSON( data ) {
  11446. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11447. }
  11448. }
  11449. class CylinderGeometry extends BufferGeometry {
  11450. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11451. super();
  11452. this.type = 'CylinderGeometry';
  11453. this.parameters = {
  11454. radiusTop: radiusTop,
  11455. radiusBottom: radiusBottom,
  11456. height: height,
  11457. radialSegments: radialSegments,
  11458. heightSegments: heightSegments,
  11459. openEnded: openEnded,
  11460. thetaStart: thetaStart,
  11461. thetaLength: thetaLength
  11462. };
  11463. const scope = this;
  11464. radialSegments = Math.floor( radialSegments );
  11465. heightSegments = Math.floor( heightSegments );
  11466. // buffers
  11467. const indices = [];
  11468. const vertices = [];
  11469. const normals = [];
  11470. const uvs = [];
  11471. // helper variables
  11472. let index = 0;
  11473. const indexArray = [];
  11474. const halfHeight = height / 2;
  11475. let groupStart = 0;
  11476. // generate geometry
  11477. generateTorso();
  11478. if ( openEnded === false ) {
  11479. if ( radiusTop > 0 ) generateCap( true );
  11480. if ( radiusBottom > 0 ) generateCap( false );
  11481. }
  11482. // build geometry
  11483. this.setIndex( indices );
  11484. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11485. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11486. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11487. function generateTorso() {
  11488. const normal = new Vector3();
  11489. const vertex = new Vector3();
  11490. let groupCount = 0;
  11491. // this will be used to calculate the normal
  11492. const slope = ( radiusBottom - radiusTop ) / height;
  11493. // generate vertices, normals and uvs
  11494. for ( let y = 0; y <= heightSegments; y ++ ) {
  11495. const indexRow = [];
  11496. const v = y / heightSegments;
  11497. // calculate the radius of the current row
  11498. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11499. for ( let x = 0; x <= radialSegments; x ++ ) {
  11500. const u = x / radialSegments;
  11501. const theta = u * thetaLength + thetaStart;
  11502. const sinTheta = Math.sin( theta );
  11503. const cosTheta = Math.cos( theta );
  11504. // vertex
  11505. vertex.x = radius * sinTheta;
  11506. vertex.y = - v * height + halfHeight;
  11507. vertex.z = radius * cosTheta;
  11508. vertices.push( vertex.x, vertex.y, vertex.z );
  11509. // normal
  11510. normal.set( sinTheta, slope, cosTheta ).normalize();
  11511. normals.push( normal.x, normal.y, normal.z );
  11512. // uv
  11513. uvs.push( u, 1 - v );
  11514. // save index of vertex in respective row
  11515. indexRow.push( index ++ );
  11516. }
  11517. // now save vertices of the row in our index array
  11518. indexArray.push( indexRow );
  11519. }
  11520. // generate indices
  11521. for ( let x = 0; x < radialSegments; x ++ ) {
  11522. for ( let y = 0; y < heightSegments; y ++ ) {
  11523. // we use the index array to access the correct indices
  11524. const a = indexArray[ y ][ x ];
  11525. const b = indexArray[ y + 1 ][ x ];
  11526. const c = indexArray[ y + 1 ][ x + 1 ];
  11527. const d = indexArray[ y ][ x + 1 ];
  11528. // faces
  11529. indices.push( a, b, d );
  11530. indices.push( b, c, d );
  11531. // update group counter
  11532. groupCount += 6;
  11533. }
  11534. }
  11535. // add a group to the geometry. this will ensure multi material support
  11536. scope.addGroup( groupStart, groupCount, 0 );
  11537. // calculate new start value for groups
  11538. groupStart += groupCount;
  11539. }
  11540. function generateCap( top ) {
  11541. // save the index of the first center vertex
  11542. const centerIndexStart = index;
  11543. const uv = new Vector2();
  11544. const vertex = new Vector3();
  11545. let groupCount = 0;
  11546. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11547. const sign = ( top === true ) ? 1 : - 1;
  11548. // first we generate the center vertex data of the cap.
  11549. // because the geometry needs one set of uvs per face,
  11550. // we must generate a center vertex per face/segment
  11551. for ( let x = 1; x <= radialSegments; x ++ ) {
  11552. // vertex
  11553. vertices.push( 0, halfHeight * sign, 0 );
  11554. // normal
  11555. normals.push( 0, sign, 0 );
  11556. // uv
  11557. uvs.push( 0.5, 0.5 );
  11558. // increase index
  11559. index ++;
  11560. }
  11561. // save the index of the last center vertex
  11562. const centerIndexEnd = index;
  11563. // now we generate the surrounding vertices, normals and uvs
  11564. for ( let x = 0; x <= radialSegments; x ++ ) {
  11565. const u = x / radialSegments;
  11566. const theta = u * thetaLength + thetaStart;
  11567. const cosTheta = Math.cos( theta );
  11568. const sinTheta = Math.sin( theta );
  11569. // vertex
  11570. vertex.x = radius * sinTheta;
  11571. vertex.y = halfHeight * sign;
  11572. vertex.z = radius * cosTheta;
  11573. vertices.push( vertex.x, vertex.y, vertex.z );
  11574. // normal
  11575. normals.push( 0, sign, 0 );
  11576. // uv
  11577. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11578. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11579. uvs.push( uv.x, uv.y );
  11580. // increase index
  11581. index ++;
  11582. }
  11583. // generate indices
  11584. for ( let x = 0; x < radialSegments; x ++ ) {
  11585. const c = centerIndexStart + x;
  11586. const i = centerIndexEnd + x;
  11587. if ( top === true ) {
  11588. // face top
  11589. indices.push( i, i + 1, c );
  11590. } else {
  11591. // face bottom
  11592. indices.push( i + 1, i, c );
  11593. }
  11594. groupCount += 3;
  11595. }
  11596. // add a group to the geometry. this will ensure multi material support
  11597. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11598. // calculate new start value for groups
  11599. groupStart += groupCount;
  11600. }
  11601. }
  11602. copy( source ) {
  11603. super.copy( source );
  11604. this.parameters = Object.assign( {}, source.parameters );
  11605. return this;
  11606. }
  11607. static fromJSON( data ) {
  11608. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11609. }
  11610. }
  11611. class ConeGeometry extends CylinderGeometry {
  11612. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11613. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11614. this.type = 'ConeGeometry';
  11615. this.parameters = {
  11616. radius: radius,
  11617. height: height,
  11618. radialSegments: radialSegments,
  11619. heightSegments: heightSegments,
  11620. openEnded: openEnded,
  11621. thetaStart: thetaStart,
  11622. thetaLength: thetaLength
  11623. };
  11624. }
  11625. static fromJSON( data ) {
  11626. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11627. }
  11628. }
  11629. class PolyhedronGeometry extends BufferGeometry {
  11630. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11631. super();
  11632. this.type = 'PolyhedronGeometry';
  11633. this.parameters = {
  11634. vertices: vertices,
  11635. indices: indices,
  11636. radius: radius,
  11637. detail: detail
  11638. };
  11639. // default buffer data
  11640. const vertexBuffer = [];
  11641. const uvBuffer = [];
  11642. // the subdivision creates the vertex buffer data
  11643. subdivide( detail );
  11644. // all vertices should lie on a conceptual sphere with a given radius
  11645. applyRadius( radius );
  11646. // finally, create the uv data
  11647. generateUVs();
  11648. // build non-indexed geometry
  11649. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11650. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11651. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11652. if ( detail === 0 ) {
  11653. this.computeVertexNormals(); // flat normals
  11654. } else {
  11655. this.normalizeNormals(); // smooth normals
  11656. }
  11657. // helper functions
  11658. function subdivide( detail ) {
  11659. const a = new Vector3();
  11660. const b = new Vector3();
  11661. const c = new Vector3();
  11662. // iterate over all faces and apply a subdivision with the given detail value
  11663. for ( let i = 0; i < indices.length; i += 3 ) {
  11664. // get the vertices of the face
  11665. getVertexByIndex( indices[ i + 0 ], a );
  11666. getVertexByIndex( indices[ i + 1 ], b );
  11667. getVertexByIndex( indices[ i + 2 ], c );
  11668. // perform subdivision
  11669. subdivideFace( a, b, c, detail );
  11670. }
  11671. }
  11672. function subdivideFace( a, b, c, detail ) {
  11673. const cols = detail + 1;
  11674. // we use this multidimensional array as a data structure for creating the subdivision
  11675. const v = [];
  11676. // construct all of the vertices for this subdivision
  11677. for ( let i = 0; i <= cols; i ++ ) {
  11678. v[ i ] = [];
  11679. const aj = a.clone().lerp( c, i / cols );
  11680. const bj = b.clone().lerp( c, i / cols );
  11681. const rows = cols - i;
  11682. for ( let j = 0; j <= rows; j ++ ) {
  11683. if ( j === 0 && i === cols ) {
  11684. v[ i ][ j ] = aj;
  11685. } else {
  11686. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11687. }
  11688. }
  11689. }
  11690. // construct all of the faces
  11691. for ( let i = 0; i < cols; i ++ ) {
  11692. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11693. const k = Math.floor( j / 2 );
  11694. if ( j % 2 === 0 ) {
  11695. pushVertex( v[ i ][ k + 1 ] );
  11696. pushVertex( v[ i + 1 ][ k ] );
  11697. pushVertex( v[ i ][ k ] );
  11698. } else {
  11699. pushVertex( v[ i ][ k + 1 ] );
  11700. pushVertex( v[ i + 1 ][ k + 1 ] );
  11701. pushVertex( v[ i + 1 ][ k ] );
  11702. }
  11703. }
  11704. }
  11705. }
  11706. function applyRadius( radius ) {
  11707. const vertex = new Vector3();
  11708. // iterate over the entire buffer and apply the radius to each vertex
  11709. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11710. vertex.x = vertexBuffer[ i + 0 ];
  11711. vertex.y = vertexBuffer[ i + 1 ];
  11712. vertex.z = vertexBuffer[ i + 2 ];
  11713. vertex.normalize().multiplyScalar( radius );
  11714. vertexBuffer[ i + 0 ] = vertex.x;
  11715. vertexBuffer[ i + 1 ] = vertex.y;
  11716. vertexBuffer[ i + 2 ] = vertex.z;
  11717. }
  11718. }
  11719. function generateUVs() {
  11720. const vertex = new Vector3();
  11721. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11722. vertex.x = vertexBuffer[ i + 0 ];
  11723. vertex.y = vertexBuffer[ i + 1 ];
  11724. vertex.z = vertexBuffer[ i + 2 ];
  11725. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11726. const v = inclination( vertex ) / Math.PI + 0.5;
  11727. uvBuffer.push( u, 1 - v );
  11728. }
  11729. correctUVs();
  11730. correctSeam();
  11731. }
  11732. function correctSeam() {
  11733. // handle case when face straddles the seam, see #3269
  11734. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11735. // uv data of a single face
  11736. const x0 = uvBuffer[ i + 0 ];
  11737. const x1 = uvBuffer[ i + 2 ];
  11738. const x2 = uvBuffer[ i + 4 ];
  11739. const max = Math.max( x0, x1, x2 );
  11740. const min = Math.min( x0, x1, x2 );
  11741. // 0.9 is somewhat arbitrary
  11742. if ( max > 0.9 && min < 0.1 ) {
  11743. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11744. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11745. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11746. }
  11747. }
  11748. }
  11749. function pushVertex( vertex ) {
  11750. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11751. }
  11752. function getVertexByIndex( index, vertex ) {
  11753. const stride = index * 3;
  11754. vertex.x = vertices[ stride + 0 ];
  11755. vertex.y = vertices[ stride + 1 ];
  11756. vertex.z = vertices[ stride + 2 ];
  11757. }
  11758. function correctUVs() {
  11759. const a = new Vector3();
  11760. const b = new Vector3();
  11761. const c = new Vector3();
  11762. const centroid = new Vector3();
  11763. const uvA = new Vector2();
  11764. const uvB = new Vector2();
  11765. const uvC = new Vector2();
  11766. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11767. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11768. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11769. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11770. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11771. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11772. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11773. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11774. const azi = azimuth( centroid );
  11775. correctUV( uvA, j + 0, a, azi );
  11776. correctUV( uvB, j + 2, b, azi );
  11777. correctUV( uvC, j + 4, c, azi );
  11778. }
  11779. }
  11780. function correctUV( uv, stride, vector, azimuth ) {
  11781. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11782. uvBuffer[ stride ] = uv.x - 1;
  11783. }
  11784. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11785. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11786. }
  11787. }
  11788. // Angle around the Y axis, counter-clockwise when looking from above.
  11789. function azimuth( vector ) {
  11790. return Math.atan2( vector.z, - vector.x );
  11791. }
  11792. // Angle above the XZ plane.
  11793. function inclination( vector ) {
  11794. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11795. }
  11796. }
  11797. copy( source ) {
  11798. super.copy( source );
  11799. this.parameters = Object.assign( {}, source.parameters );
  11800. return this;
  11801. }
  11802. static fromJSON( data ) {
  11803. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11804. }
  11805. }
  11806. class DodecahedronGeometry extends PolyhedronGeometry {
  11807. constructor( radius = 1, detail = 0 ) {
  11808. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11809. const r = 1 / t;
  11810. const vertices = [
  11811. // (±1, ±1, ±1)
  11812. - 1, - 1, - 1, - 1, - 1, 1,
  11813. - 1, 1, - 1, - 1, 1, 1,
  11814. 1, - 1, - 1, 1, - 1, 1,
  11815. 1, 1, - 1, 1, 1, 1,
  11816. // (0, ±1/φ, ±φ)
  11817. 0, - r, - t, 0, - r, t,
  11818. 0, r, - t, 0, r, t,
  11819. // (±1/φ, ±φ, 0)
  11820. - r, - t, 0, - r, t, 0,
  11821. r, - t, 0, r, t, 0,
  11822. // (±φ, 0, ±1/φ)
  11823. - t, 0, - r, t, 0, - r,
  11824. - t, 0, r, t, 0, r
  11825. ];
  11826. const indices = [
  11827. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11828. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11829. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11830. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11831. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11832. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11833. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11834. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11835. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11836. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11837. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11838. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11839. ];
  11840. super( vertices, indices, radius, detail );
  11841. this.type = 'DodecahedronGeometry';
  11842. this.parameters = {
  11843. radius: radius,
  11844. detail: detail
  11845. };
  11846. }
  11847. static fromJSON( data ) {
  11848. return new DodecahedronGeometry( data.radius, data.detail );
  11849. }
  11850. }
  11851. const _v0 = /*@__PURE__*/ new Vector3();
  11852. const _v1$1 = /*@__PURE__*/ new Vector3();
  11853. const _normal$1 = /*@__PURE__*/ new Vector3();
  11854. const _triangle = /*@__PURE__*/ new Triangle();
  11855. class EdgesGeometry extends BufferGeometry {
  11856. constructor( geometry = null, thresholdAngle = 1 ) {
  11857. super();
  11858. this.type = 'EdgesGeometry';
  11859. this.parameters = {
  11860. geometry: geometry,
  11861. thresholdAngle: thresholdAngle
  11862. };
  11863. if ( geometry !== null ) {
  11864. const precisionPoints = 4;
  11865. const precision = Math.pow( 10, precisionPoints );
  11866. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11867. const indexAttr = geometry.getIndex();
  11868. const positionAttr = geometry.getAttribute( 'position' );
  11869. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11870. const indexArr = [ 0, 0, 0 ];
  11871. const vertKeys = [ 'a', 'b', 'c' ];
  11872. const hashes = new Array( 3 );
  11873. const edgeData = {};
  11874. const vertices = [];
  11875. for ( let i = 0; i < indexCount; i += 3 ) {
  11876. if ( indexAttr ) {
  11877. indexArr[ 0 ] = indexAttr.getX( i );
  11878. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11879. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11880. } else {
  11881. indexArr[ 0 ] = i;
  11882. indexArr[ 1 ] = i + 1;
  11883. indexArr[ 2 ] = i + 2;
  11884. }
  11885. const { a, b, c } = _triangle;
  11886. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11887. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11888. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11889. _triangle.getNormal( _normal$1 );
  11890. // create hashes for the edge from the vertices
  11891. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11892. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11893. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11894. // skip degenerate triangles
  11895. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11896. continue;
  11897. }
  11898. // iterate over every edge
  11899. for ( let j = 0; j < 3; j ++ ) {
  11900. // get the first and next vertex making up the edge
  11901. const jNext = ( j + 1 ) % 3;
  11902. const vecHash0 = hashes[ j ];
  11903. const vecHash1 = hashes[ jNext ];
  11904. const v0 = _triangle[ vertKeys[ j ] ];
  11905. const v1 = _triangle[ vertKeys[ jNext ] ];
  11906. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11907. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11908. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11909. // if we found a sibling edge add it into the vertex array if
  11910. // it meets the angle threshold and delete the edge from the map.
  11911. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11912. vertices.push( v0.x, v0.y, v0.z );
  11913. vertices.push( v1.x, v1.y, v1.z );
  11914. }
  11915. edgeData[ reverseHash ] = null;
  11916. } else if ( ! ( hash in edgeData ) ) {
  11917. // if we've already got an edge here then skip adding a new one
  11918. edgeData[ hash ] = {
  11919. index0: indexArr[ j ],
  11920. index1: indexArr[ jNext ],
  11921. normal: _normal$1.clone(),
  11922. };
  11923. }
  11924. }
  11925. }
  11926. // iterate over all remaining, unmatched edges and add them to the vertex array
  11927. for ( const key in edgeData ) {
  11928. if ( edgeData[ key ] ) {
  11929. const { index0, index1 } = edgeData[ key ];
  11930. _v0.fromBufferAttribute( positionAttr, index0 );
  11931. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11932. vertices.push( _v0.x, _v0.y, _v0.z );
  11933. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11934. }
  11935. }
  11936. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11937. }
  11938. }
  11939. copy( source ) {
  11940. super.copy( source );
  11941. this.parameters = Object.assign( {}, source.parameters );
  11942. return this;
  11943. }
  11944. }
  11945. class Shape extends Path {
  11946. constructor( points ) {
  11947. super( points );
  11948. this.uuid = generateUUID();
  11949. this.type = 'Shape';
  11950. this.holes = [];
  11951. }
  11952. getPointsHoles( divisions ) {
  11953. const holesPts = [];
  11954. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11955. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  11956. }
  11957. return holesPts;
  11958. }
  11959. // get points of shape and holes (keypoints based on segments parameter)
  11960. extractPoints( divisions ) {
  11961. return {
  11962. shape: this.getPoints( divisions ),
  11963. holes: this.getPointsHoles( divisions )
  11964. };
  11965. }
  11966. copy( source ) {
  11967. super.copy( source );
  11968. this.holes = [];
  11969. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  11970. const hole = source.holes[ i ];
  11971. this.holes.push( hole.clone() );
  11972. }
  11973. return this;
  11974. }
  11975. toJSON() {
  11976. const data = super.toJSON();
  11977. data.uuid = this.uuid;
  11978. data.holes = [];
  11979. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11980. const hole = this.holes[ i ];
  11981. data.holes.push( hole.toJSON() );
  11982. }
  11983. return data;
  11984. }
  11985. fromJSON( json ) {
  11986. super.fromJSON( json );
  11987. this.uuid = json.uuid;
  11988. this.holes = [];
  11989. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  11990. const hole = json.holes[ i ];
  11991. this.holes.push( new Path().fromJSON( hole ) );
  11992. }
  11993. return this;
  11994. }
  11995. }
  11996. /**
  11997. * Port from https://github.com/mapbox/earcut (v2.2.4)
  11998. */
  11999. const Earcut = {
  12000. triangulate: function ( data, holeIndices, dim = 2 ) {
  12001. const hasHoles = holeIndices && holeIndices.length;
  12002. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12003. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12004. const triangles = [];
  12005. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12006. let minX, minY, maxX, maxY, x, y, invSize;
  12007. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12008. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12009. if ( data.length > 80 * dim ) {
  12010. minX = maxX = data[ 0 ];
  12011. minY = maxY = data[ 1 ];
  12012. for ( let i = dim; i < outerLen; i += dim ) {
  12013. x = data[ i ];
  12014. y = data[ i + 1 ];
  12015. if ( x < minX ) minX = x;
  12016. if ( y < minY ) minY = y;
  12017. if ( x > maxX ) maxX = x;
  12018. if ( y > maxY ) maxY = y;
  12019. }
  12020. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12021. invSize = Math.max( maxX - minX, maxY - minY );
  12022. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12023. }
  12024. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12025. return triangles;
  12026. }
  12027. };
  12028. // create a circular doubly linked list from polygon points in the specified winding order
  12029. function linkedList( data, start, end, dim, clockwise ) {
  12030. let i, last;
  12031. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12032. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12033. } else {
  12034. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12035. }
  12036. if ( last && equals$1( last, last.next ) ) {
  12037. removeNode( last );
  12038. last = last.next;
  12039. }
  12040. return last;
  12041. }
  12042. // eliminate colinear or duplicate points
  12043. function filterPoints( start, end ) {
  12044. if ( ! start ) return start;
  12045. if ( ! end ) end = start;
  12046. let p = start,
  12047. again;
  12048. do {
  12049. again = false;
  12050. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12051. removeNode( p );
  12052. p = end = p.prev;
  12053. if ( p === p.next ) break;
  12054. again = true;
  12055. } else {
  12056. p = p.next;
  12057. }
  12058. } while ( again || p !== end );
  12059. return end;
  12060. }
  12061. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12062. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12063. if ( ! ear ) return;
  12064. // interlink polygon nodes in z-order
  12065. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12066. let stop = ear,
  12067. prev, next;
  12068. // iterate through ears, slicing them one by one
  12069. while ( ear.prev !== ear.next ) {
  12070. prev = ear.prev;
  12071. next = ear.next;
  12072. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12073. // cut off the triangle
  12074. triangles.push( prev.i / dim | 0 );
  12075. triangles.push( ear.i / dim | 0 );
  12076. triangles.push( next.i / dim | 0 );
  12077. removeNode( ear );
  12078. // skipping the next vertex leads to less sliver triangles
  12079. ear = next.next;
  12080. stop = next.next;
  12081. continue;
  12082. }
  12083. ear = next;
  12084. // if we looped through the whole remaining polygon and can't find any more ears
  12085. if ( ear === stop ) {
  12086. // try filtering points and slicing again
  12087. if ( ! pass ) {
  12088. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12089. // if this didn't work, try curing all small self-intersections locally
  12090. } else if ( pass === 1 ) {
  12091. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12092. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12093. // as a last resort, try splitting the remaining polygon into two
  12094. } else if ( pass === 2 ) {
  12095. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12096. }
  12097. break;
  12098. }
  12099. }
  12100. }
  12101. // check whether a polygon node forms a valid ear with adjacent nodes
  12102. function isEar( ear ) {
  12103. const a = ear.prev,
  12104. b = ear,
  12105. c = ear.next;
  12106. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12107. // now make sure we don't have other points inside the potential ear
  12108. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12109. // triangle bbox; min & max are calculated like this for speed
  12110. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12111. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12112. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12113. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12114. let p = c.next;
  12115. while ( p !== a ) {
  12116. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12117. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12118. area( p.prev, p, p.next ) >= 0 ) return false;
  12119. p = p.next;
  12120. }
  12121. return true;
  12122. }
  12123. function isEarHashed( ear, minX, minY, invSize ) {
  12124. const a = ear.prev,
  12125. b = ear,
  12126. c = ear.next;
  12127. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12128. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12129. // triangle bbox; min & max are calculated like this for speed
  12130. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12131. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12132. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12133. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12134. // z-order range for the current triangle bbox;
  12135. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12136. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12137. let p = ear.prevZ,
  12138. n = ear.nextZ;
  12139. // look for points inside the triangle in both directions
  12140. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12141. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12142. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12143. p = p.prevZ;
  12144. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12145. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12146. n = n.nextZ;
  12147. }
  12148. // look for remaining points in decreasing z-order
  12149. while ( p && p.z >= minZ ) {
  12150. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12151. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12152. p = p.prevZ;
  12153. }
  12154. // look for remaining points in increasing z-order
  12155. while ( n && n.z <= maxZ ) {
  12156. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12157. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12158. n = n.nextZ;
  12159. }
  12160. return true;
  12161. }
  12162. // go through all polygon nodes and cure small local self-intersections
  12163. function cureLocalIntersections( start, triangles, dim ) {
  12164. let p = start;
  12165. do {
  12166. const a = p.prev,
  12167. b = p.next.next;
  12168. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12169. triangles.push( a.i / dim | 0 );
  12170. triangles.push( p.i / dim | 0 );
  12171. triangles.push( b.i / dim | 0 );
  12172. // remove two nodes involved
  12173. removeNode( p );
  12174. removeNode( p.next );
  12175. p = start = b;
  12176. }
  12177. p = p.next;
  12178. } while ( p !== start );
  12179. return filterPoints( p );
  12180. }
  12181. // try splitting polygon into two and triangulate them independently
  12182. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12183. // look for a valid diagonal that divides the polygon into two
  12184. let a = start;
  12185. do {
  12186. let b = a.next.next;
  12187. while ( b !== a.prev ) {
  12188. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12189. // split the polygon in two by the diagonal
  12190. let c = splitPolygon( a, b );
  12191. // filter colinear points around the cuts
  12192. a = filterPoints( a, a.next );
  12193. c = filterPoints( c, c.next );
  12194. // run earcut on each half
  12195. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12196. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12197. return;
  12198. }
  12199. b = b.next;
  12200. }
  12201. a = a.next;
  12202. } while ( a !== start );
  12203. }
  12204. // link every hole into the outer loop, producing a single-ring polygon without holes
  12205. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12206. const queue = [];
  12207. let i, len, start, end, list;
  12208. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12209. start = holeIndices[ i ] * dim;
  12210. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12211. list = linkedList( data, start, end, dim, false );
  12212. if ( list === list.next ) list.steiner = true;
  12213. queue.push( getLeftmost( list ) );
  12214. }
  12215. queue.sort( compareX );
  12216. // process holes from left to right
  12217. for ( i = 0; i < queue.length; i ++ ) {
  12218. outerNode = eliminateHole( queue[ i ], outerNode );
  12219. }
  12220. return outerNode;
  12221. }
  12222. function compareX( a, b ) {
  12223. return a.x - b.x;
  12224. }
  12225. // find a bridge between vertices that connects hole with an outer ring and link it
  12226. function eliminateHole( hole, outerNode ) {
  12227. const bridge = findHoleBridge( hole, outerNode );
  12228. if ( ! bridge ) {
  12229. return outerNode;
  12230. }
  12231. const bridgeReverse = splitPolygon( bridge, hole );
  12232. // filter collinear points around the cuts
  12233. filterPoints( bridgeReverse, bridgeReverse.next );
  12234. return filterPoints( bridge, bridge.next );
  12235. }
  12236. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12237. function findHoleBridge( hole, outerNode ) {
  12238. let p = outerNode,
  12239. qx = - Infinity,
  12240. m;
  12241. const hx = hole.x, hy = hole.y;
  12242. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12243. // segment's endpoint with lesser x will be potential connection point
  12244. do {
  12245. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12246. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12247. if ( x <= hx && x > qx ) {
  12248. qx = x;
  12249. m = p.x < p.next.x ? p : p.next;
  12250. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12251. }
  12252. }
  12253. p = p.next;
  12254. } while ( p !== outerNode );
  12255. if ( ! m ) return null;
  12256. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12257. // if there are no points found, we have a valid connection;
  12258. // otherwise choose the point of the minimum angle with the ray as connection point
  12259. const stop = m,
  12260. mx = m.x,
  12261. my = m.y;
  12262. let tanMin = Infinity, tan;
  12263. p = m;
  12264. do {
  12265. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12266. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12267. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12268. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12269. m = p;
  12270. tanMin = tan;
  12271. }
  12272. }
  12273. p = p.next;
  12274. } while ( p !== stop );
  12275. return m;
  12276. }
  12277. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12278. function sectorContainsSector( m, p ) {
  12279. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12280. }
  12281. // interlink polygon nodes in z-order
  12282. function indexCurve( start, minX, minY, invSize ) {
  12283. let p = start;
  12284. do {
  12285. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12286. p.prevZ = p.prev;
  12287. p.nextZ = p.next;
  12288. p = p.next;
  12289. } while ( p !== start );
  12290. p.prevZ.nextZ = null;
  12291. p.prevZ = null;
  12292. sortLinked( p );
  12293. }
  12294. // Simon Tatham's linked list merge sort algorithm
  12295. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12296. function sortLinked( list ) {
  12297. let i, p, q, e, tail, numMerges, pSize, qSize,
  12298. inSize = 1;
  12299. do {
  12300. p = list;
  12301. list = null;
  12302. tail = null;
  12303. numMerges = 0;
  12304. while ( p ) {
  12305. numMerges ++;
  12306. q = p;
  12307. pSize = 0;
  12308. for ( i = 0; i < inSize; i ++ ) {
  12309. pSize ++;
  12310. q = q.nextZ;
  12311. if ( ! q ) break;
  12312. }
  12313. qSize = inSize;
  12314. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12315. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12316. e = p;
  12317. p = p.nextZ;
  12318. pSize --;
  12319. } else {
  12320. e = q;
  12321. q = q.nextZ;
  12322. qSize --;
  12323. }
  12324. if ( tail ) tail.nextZ = e;
  12325. else list = e;
  12326. e.prevZ = tail;
  12327. tail = e;
  12328. }
  12329. p = q;
  12330. }
  12331. tail.nextZ = null;
  12332. inSize *= 2;
  12333. } while ( numMerges > 1 );
  12334. return list;
  12335. }
  12336. // z-order of a point given coords and inverse of the longer side of data bbox
  12337. function zOrder( x, y, minX, minY, invSize ) {
  12338. // coords are transformed into non-negative 15-bit integer range
  12339. x = ( x - minX ) * invSize | 0;
  12340. y = ( y - minY ) * invSize | 0;
  12341. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12342. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12343. x = ( x | ( x << 2 ) ) & 0x33333333;
  12344. x = ( x | ( x << 1 ) ) & 0x55555555;
  12345. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12346. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12347. y = ( y | ( y << 2 ) ) & 0x33333333;
  12348. y = ( y | ( y << 1 ) ) & 0x55555555;
  12349. return x | ( y << 1 );
  12350. }
  12351. // find the leftmost node of a polygon ring
  12352. function getLeftmost( start ) {
  12353. let p = start,
  12354. leftmost = start;
  12355. do {
  12356. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12357. p = p.next;
  12358. } while ( p !== start );
  12359. return leftmost;
  12360. }
  12361. // check if a point lies within a convex triangle
  12362. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12363. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12364. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12365. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12366. }
  12367. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12368. function isValidDiagonal( a, b ) {
  12369. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12370. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12371. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12372. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12373. }
  12374. // signed area of a triangle
  12375. function area( p, q, r ) {
  12376. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12377. }
  12378. // check if two points are equal
  12379. function equals$1( p1, p2 ) {
  12380. return p1.x === p2.x && p1.y === p2.y;
  12381. }
  12382. // check if two segments intersect
  12383. function intersects( p1, q1, p2, q2 ) {
  12384. const o1 = sign$1( area( p1, q1, p2 ) );
  12385. const o2 = sign$1( area( p1, q1, q2 ) );
  12386. const o3 = sign$1( area( p2, q2, p1 ) );
  12387. const o4 = sign$1( area( p2, q2, q1 ) );
  12388. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12389. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12390. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12391. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12392. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12393. return false;
  12394. }
  12395. // for collinear points p, q, r, check if point q lies on segment pr
  12396. function onSegment( p, q, r ) {
  12397. 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 );
  12398. }
  12399. function sign$1( num ) {
  12400. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12401. }
  12402. // check if a polygon diagonal intersects any polygon segments
  12403. function intersectsPolygon( a, b ) {
  12404. let p = a;
  12405. do {
  12406. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12407. intersects( p, p.next, a, b ) ) return true;
  12408. p = p.next;
  12409. } while ( p !== a );
  12410. return false;
  12411. }
  12412. // check if a polygon diagonal is locally inside the polygon
  12413. function locallyInside( a, b ) {
  12414. return area( a.prev, a, a.next ) < 0 ?
  12415. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12416. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12417. }
  12418. // check if the middle point of a polygon diagonal is inside the polygon
  12419. function middleInside( a, b ) {
  12420. let p = a,
  12421. inside = false;
  12422. const px = ( a.x + b.x ) / 2,
  12423. py = ( a.y + b.y ) / 2;
  12424. do {
  12425. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12426. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12427. inside = ! inside;
  12428. p = p.next;
  12429. } while ( p !== a );
  12430. return inside;
  12431. }
  12432. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12433. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12434. function splitPolygon( a, b ) {
  12435. const a2 = new Node$1( a.i, a.x, a.y ),
  12436. b2 = new Node$1( b.i, b.x, b.y ),
  12437. an = a.next,
  12438. bp = b.prev;
  12439. a.next = b;
  12440. b.prev = a;
  12441. a2.next = an;
  12442. an.prev = a2;
  12443. b2.next = a2;
  12444. a2.prev = b2;
  12445. bp.next = b2;
  12446. b2.prev = bp;
  12447. return b2;
  12448. }
  12449. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12450. function insertNode( i, x, y, last ) {
  12451. const p = new Node$1( i, x, y );
  12452. if ( ! last ) {
  12453. p.prev = p;
  12454. p.next = p;
  12455. } else {
  12456. p.next = last.next;
  12457. p.prev = last;
  12458. last.next.prev = p;
  12459. last.next = p;
  12460. }
  12461. return p;
  12462. }
  12463. function removeNode( p ) {
  12464. p.next.prev = p.prev;
  12465. p.prev.next = p.next;
  12466. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12467. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12468. }
  12469. function Node$1( i, x, y ) {
  12470. // vertex index in coordinates array
  12471. this.i = i;
  12472. // vertex coordinates
  12473. this.x = x;
  12474. this.y = y;
  12475. // previous and next vertex nodes in a polygon ring
  12476. this.prev = null;
  12477. this.next = null;
  12478. // z-order curve value
  12479. this.z = 0;
  12480. // previous and next nodes in z-order
  12481. this.prevZ = null;
  12482. this.nextZ = null;
  12483. // indicates whether this is a steiner point
  12484. this.steiner = false;
  12485. }
  12486. function signedArea( data, start, end, dim ) {
  12487. let sum = 0;
  12488. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12489. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12490. j = i;
  12491. }
  12492. return sum;
  12493. }
  12494. class ShapeUtils {
  12495. // calculate area of the contour polygon
  12496. static area( contour ) {
  12497. const n = contour.length;
  12498. let a = 0.0;
  12499. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12500. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12501. }
  12502. return a * 0.5;
  12503. }
  12504. static isClockWise( pts ) {
  12505. return ShapeUtils.area( pts ) < 0;
  12506. }
  12507. static triangulateShape( contour, holes ) {
  12508. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12509. const holeIndices = []; // array of hole indices
  12510. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12511. removeDupEndPts( contour );
  12512. addContour( vertices, contour );
  12513. //
  12514. let holeIndex = contour.length;
  12515. holes.forEach( removeDupEndPts );
  12516. for ( let i = 0; i < holes.length; i ++ ) {
  12517. holeIndices.push( holeIndex );
  12518. holeIndex += holes[ i ].length;
  12519. addContour( vertices, holes[ i ] );
  12520. }
  12521. //
  12522. const triangles = Earcut.triangulate( vertices, holeIndices );
  12523. //
  12524. for ( let i = 0; i < triangles.length; i += 3 ) {
  12525. faces.push( triangles.slice( i, i + 3 ) );
  12526. }
  12527. return faces;
  12528. }
  12529. }
  12530. function removeDupEndPts( points ) {
  12531. const l = points.length;
  12532. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12533. points.pop();
  12534. }
  12535. }
  12536. function addContour( vertices, contour ) {
  12537. for ( let i = 0; i < contour.length; i ++ ) {
  12538. vertices.push( contour[ i ].x );
  12539. vertices.push( contour[ i ].y );
  12540. }
  12541. }
  12542. /**
  12543. * Creates extruded geometry from a path shape.
  12544. *
  12545. * parameters = {
  12546. *
  12547. * curveSegments: <int>, // number of points on the curves
  12548. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12549. * depth: <float>, // Depth to extrude the shape
  12550. *
  12551. * bevelEnabled: <bool>, // turn on bevel
  12552. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12553. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12554. * bevelOffset: <float>, // how far from shape outline does bevel start
  12555. * bevelSegments: <int>, // number of bevel layers
  12556. *
  12557. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12558. *
  12559. * UVGenerator: <Object> // object that provides UV generator functions
  12560. *
  12561. * }
  12562. */
  12563. class ExtrudeGeometry extends BufferGeometry {
  12564. 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 = {} ) {
  12565. super();
  12566. this.type = 'ExtrudeGeometry';
  12567. this.parameters = {
  12568. shapes: shapes,
  12569. options: options
  12570. };
  12571. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12572. const scope = this;
  12573. const verticesArray = [];
  12574. const uvArray = [];
  12575. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12576. const shape = shapes[ i ];
  12577. addShape( shape );
  12578. }
  12579. // build geometry
  12580. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12581. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12582. this.computeVertexNormals();
  12583. // functions
  12584. function addShape( shape ) {
  12585. const placeholder = [];
  12586. // options
  12587. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12588. const steps = options.steps !== undefined ? options.steps : 1;
  12589. const depth = options.depth !== undefined ? options.depth : 1;
  12590. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12591. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12592. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12593. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12594. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12595. const extrudePath = options.extrudePath;
  12596. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12597. //
  12598. let extrudePts, extrudeByPath = false;
  12599. let splineTube, binormal, normal, position2;
  12600. if ( extrudePath ) {
  12601. extrudePts = extrudePath.getSpacedPoints( steps );
  12602. extrudeByPath = true;
  12603. bevelEnabled = false; // bevels not supported for path extrusion
  12604. // SETUP TNB variables
  12605. // TODO1 - have a .isClosed in spline?
  12606. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12607. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12608. binormal = new Vector3();
  12609. normal = new Vector3();
  12610. position2 = new Vector3();
  12611. }
  12612. // Safeguards if bevels are not enabled
  12613. if ( ! bevelEnabled ) {
  12614. bevelSegments = 0;
  12615. bevelThickness = 0;
  12616. bevelSize = 0;
  12617. bevelOffset = 0;
  12618. }
  12619. // Variables initialization
  12620. const shapePoints = shape.extractPoints( curveSegments );
  12621. let vertices = shapePoints.shape;
  12622. const holes = shapePoints.holes;
  12623. const reverse = ! ShapeUtils.isClockWise( vertices );
  12624. if ( reverse ) {
  12625. vertices = vertices.reverse();
  12626. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12627. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12628. const ahole = holes[ h ];
  12629. if ( ShapeUtils.isClockWise( ahole ) ) {
  12630. holes[ h ] = ahole.reverse();
  12631. }
  12632. }
  12633. }
  12634. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12635. /* Vertices */
  12636. const contour = vertices; // vertices has all points but contour has only points of circumference
  12637. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12638. const ahole = holes[ h ];
  12639. vertices = vertices.concat( ahole );
  12640. }
  12641. function scalePt2( pt, vec, size ) {
  12642. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12643. return pt.clone().addScaledVector( vec, size );
  12644. }
  12645. const vlen = vertices.length, flen = faces.length;
  12646. // Find directions for point movement
  12647. function getBevelVec( inPt, inPrev, inNext ) {
  12648. // computes for inPt the corresponding point inPt' on a new contour
  12649. // shifted by 1 unit (length of normalized vector) to the left
  12650. // if we walk along contour clockwise, this new contour is outside the old one
  12651. //
  12652. // inPt' is the intersection of the two lines parallel to the two
  12653. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12654. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12655. // good reading for geometry algorithms (here: line-line intersection)
  12656. // http://geomalgorithms.com/a05-_intersect-1.html
  12657. const v_prev_x = inPt.x - inPrev.x,
  12658. v_prev_y = inPt.y - inPrev.y;
  12659. const v_next_x = inNext.x - inPt.x,
  12660. v_next_y = inNext.y - inPt.y;
  12661. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12662. // check for collinear edges
  12663. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12664. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12665. // not collinear
  12666. // length of vectors for normalizing
  12667. const v_prev_len = Math.sqrt( v_prev_lensq );
  12668. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12669. // shift adjacent points by unit vectors to the left
  12670. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12671. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12672. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12673. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12674. // scaling factor for v_prev to intersection point
  12675. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12676. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12677. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12678. // vector from inPt to intersection point
  12679. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12680. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12681. // Don't normalize!, otherwise sharp corners become ugly
  12682. // but prevent crazy spikes
  12683. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12684. if ( v_trans_lensq <= 2 ) {
  12685. return new Vector2( v_trans_x, v_trans_y );
  12686. } else {
  12687. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12688. }
  12689. } else {
  12690. // handle special case of collinear edges
  12691. let direction_eq = false; // assumes: opposite
  12692. if ( v_prev_x > Number.EPSILON ) {
  12693. if ( v_next_x > Number.EPSILON ) {
  12694. direction_eq = true;
  12695. }
  12696. } else {
  12697. if ( v_prev_x < - Number.EPSILON ) {
  12698. if ( v_next_x < - Number.EPSILON ) {
  12699. direction_eq = true;
  12700. }
  12701. } else {
  12702. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12703. direction_eq = true;
  12704. }
  12705. }
  12706. }
  12707. if ( direction_eq ) {
  12708. // console.log("Warning: lines are a straight sequence");
  12709. v_trans_x = - v_prev_y;
  12710. v_trans_y = v_prev_x;
  12711. shrink_by = Math.sqrt( v_prev_lensq );
  12712. } else {
  12713. // console.log("Warning: lines are a straight spike");
  12714. v_trans_x = v_prev_x;
  12715. v_trans_y = v_prev_y;
  12716. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12717. }
  12718. }
  12719. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12720. }
  12721. const contourMovements = [];
  12722. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12723. if ( j === il ) j = 0;
  12724. if ( k === il ) k = 0;
  12725. // (j)---(i)---(k)
  12726. // console.log('i,j,k', i, j , k)
  12727. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12728. }
  12729. const holesMovements = [];
  12730. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12731. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12732. const ahole = holes[ h ];
  12733. oneHoleMovements = [];
  12734. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12735. if ( j === il ) j = 0;
  12736. if ( k === il ) k = 0;
  12737. // (j)---(i)---(k)
  12738. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12739. }
  12740. holesMovements.push( oneHoleMovements );
  12741. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12742. }
  12743. // Loop bevelSegments, 1 for the front, 1 for the back
  12744. for ( let b = 0; b < bevelSegments; b ++ ) {
  12745. //for ( b = bevelSegments; b > 0; b -- ) {
  12746. const t = b / bevelSegments;
  12747. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12748. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12749. // contract shape
  12750. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12751. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12752. v( vert.x, vert.y, - z );
  12753. }
  12754. // expand holes
  12755. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12756. const ahole = holes[ h ];
  12757. oneHoleMovements = holesMovements[ h ];
  12758. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12759. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12760. v( vert.x, vert.y, - z );
  12761. }
  12762. }
  12763. }
  12764. const bs = bevelSize + bevelOffset;
  12765. // Back facing vertices
  12766. for ( let i = 0; i < vlen; i ++ ) {
  12767. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12768. if ( ! extrudeByPath ) {
  12769. v( vert.x, vert.y, 0 );
  12770. } else {
  12771. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12772. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12773. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12774. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12775. v( position2.x, position2.y, position2.z );
  12776. }
  12777. }
  12778. // Add stepped vertices...
  12779. // Including front facing vertices
  12780. for ( let s = 1; s <= steps; s ++ ) {
  12781. for ( let i = 0; i < vlen; i ++ ) {
  12782. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12783. if ( ! extrudeByPath ) {
  12784. v( vert.x, vert.y, depth / steps * s );
  12785. } else {
  12786. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12787. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12788. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12789. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12790. v( position2.x, position2.y, position2.z );
  12791. }
  12792. }
  12793. }
  12794. // Add bevel segments planes
  12795. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12796. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12797. const t = b / bevelSegments;
  12798. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12799. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12800. // contract shape
  12801. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12802. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12803. v( vert.x, vert.y, depth + z );
  12804. }
  12805. // expand holes
  12806. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12807. const ahole = holes[ h ];
  12808. oneHoleMovements = holesMovements[ h ];
  12809. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12810. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12811. if ( ! extrudeByPath ) {
  12812. v( vert.x, vert.y, depth + z );
  12813. } else {
  12814. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12815. }
  12816. }
  12817. }
  12818. }
  12819. /* Faces */
  12820. // Top and bottom faces
  12821. buildLidFaces();
  12822. // Sides faces
  12823. buildSideFaces();
  12824. ///// Internal functions
  12825. function buildLidFaces() {
  12826. const start = verticesArray.length / 3;
  12827. if ( bevelEnabled ) {
  12828. let layer = 0; // steps + 1
  12829. let offset = vlen * layer;
  12830. // Bottom faces
  12831. for ( let i = 0; i < flen; i ++ ) {
  12832. const face = faces[ i ];
  12833. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12834. }
  12835. layer = steps + bevelSegments * 2;
  12836. offset = vlen * layer;
  12837. // Top faces
  12838. for ( let i = 0; i < flen; i ++ ) {
  12839. const face = faces[ i ];
  12840. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12841. }
  12842. } else {
  12843. // Bottom faces
  12844. for ( let i = 0; i < flen; i ++ ) {
  12845. const face = faces[ i ];
  12846. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12847. }
  12848. // Top faces
  12849. for ( let i = 0; i < flen; i ++ ) {
  12850. const face = faces[ i ];
  12851. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12852. }
  12853. }
  12854. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12855. }
  12856. // Create faces for the z-sides of the shape
  12857. function buildSideFaces() {
  12858. const start = verticesArray.length / 3;
  12859. let layeroffset = 0;
  12860. sidewalls( contour, layeroffset );
  12861. layeroffset += contour.length;
  12862. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12863. const ahole = holes[ h ];
  12864. sidewalls( ahole, layeroffset );
  12865. //, true
  12866. layeroffset += ahole.length;
  12867. }
  12868. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12869. }
  12870. function sidewalls( contour, layeroffset ) {
  12871. let i = contour.length;
  12872. while ( -- i >= 0 ) {
  12873. const j = i;
  12874. let k = i - 1;
  12875. if ( k < 0 ) k = contour.length - 1;
  12876. //console.log('b', i,j, i-1, k,vertices.length);
  12877. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12878. const slen1 = vlen * s;
  12879. const slen2 = vlen * ( s + 1 );
  12880. const a = layeroffset + j + slen1,
  12881. b = layeroffset + k + slen1,
  12882. c = layeroffset + k + slen2,
  12883. d = layeroffset + j + slen2;
  12884. f4( a, b, c, d );
  12885. }
  12886. }
  12887. }
  12888. function v( x, y, z ) {
  12889. placeholder.push( x );
  12890. placeholder.push( y );
  12891. placeholder.push( z );
  12892. }
  12893. function f3( a, b, c ) {
  12894. addVertex( a );
  12895. addVertex( b );
  12896. addVertex( c );
  12897. const nextIndex = verticesArray.length / 3;
  12898. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12899. addUV( uvs[ 0 ] );
  12900. addUV( uvs[ 1 ] );
  12901. addUV( uvs[ 2 ] );
  12902. }
  12903. function f4( a, b, c, d ) {
  12904. addVertex( a );
  12905. addVertex( b );
  12906. addVertex( d );
  12907. addVertex( b );
  12908. addVertex( c );
  12909. addVertex( d );
  12910. const nextIndex = verticesArray.length / 3;
  12911. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12912. addUV( uvs[ 0 ] );
  12913. addUV( uvs[ 1 ] );
  12914. addUV( uvs[ 3 ] );
  12915. addUV( uvs[ 1 ] );
  12916. addUV( uvs[ 2 ] );
  12917. addUV( uvs[ 3 ] );
  12918. }
  12919. function addVertex( index ) {
  12920. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12921. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12922. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12923. }
  12924. function addUV( vector2 ) {
  12925. uvArray.push( vector2.x );
  12926. uvArray.push( vector2.y );
  12927. }
  12928. }
  12929. }
  12930. copy( source ) {
  12931. super.copy( source );
  12932. this.parameters = Object.assign( {}, source.parameters );
  12933. return this;
  12934. }
  12935. toJSON() {
  12936. const data = super.toJSON();
  12937. const shapes = this.parameters.shapes;
  12938. const options = this.parameters.options;
  12939. return toJSON$1( shapes, options, data );
  12940. }
  12941. static fromJSON( data, shapes ) {
  12942. const geometryShapes = [];
  12943. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  12944. const shape = shapes[ data.shapes[ j ] ];
  12945. geometryShapes.push( shape );
  12946. }
  12947. const extrudePath = data.options.extrudePath;
  12948. if ( extrudePath !== undefined ) {
  12949. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  12950. }
  12951. return new ExtrudeGeometry( geometryShapes, data.options );
  12952. }
  12953. }
  12954. const WorldUVGenerator = {
  12955. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  12956. const a_x = vertices[ indexA * 3 ];
  12957. const a_y = vertices[ indexA * 3 + 1 ];
  12958. const b_x = vertices[ indexB * 3 ];
  12959. const b_y = vertices[ indexB * 3 + 1 ];
  12960. const c_x = vertices[ indexC * 3 ];
  12961. const c_y = vertices[ indexC * 3 + 1 ];
  12962. return [
  12963. new Vector2( a_x, a_y ),
  12964. new Vector2( b_x, b_y ),
  12965. new Vector2( c_x, c_y )
  12966. ];
  12967. },
  12968. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  12969. const a_x = vertices[ indexA * 3 ];
  12970. const a_y = vertices[ indexA * 3 + 1 ];
  12971. const a_z = vertices[ indexA * 3 + 2 ];
  12972. const b_x = vertices[ indexB * 3 ];
  12973. const b_y = vertices[ indexB * 3 + 1 ];
  12974. const b_z = vertices[ indexB * 3 + 2 ];
  12975. const c_x = vertices[ indexC * 3 ];
  12976. const c_y = vertices[ indexC * 3 + 1 ];
  12977. const c_z = vertices[ indexC * 3 + 2 ];
  12978. const d_x = vertices[ indexD * 3 ];
  12979. const d_y = vertices[ indexD * 3 + 1 ];
  12980. const d_z = vertices[ indexD * 3 + 2 ];
  12981. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  12982. return [
  12983. new Vector2( a_x, 1 - a_z ),
  12984. new Vector2( b_x, 1 - b_z ),
  12985. new Vector2( c_x, 1 - c_z ),
  12986. new Vector2( d_x, 1 - d_z )
  12987. ];
  12988. } else {
  12989. return [
  12990. new Vector2( a_y, 1 - a_z ),
  12991. new Vector2( b_y, 1 - b_z ),
  12992. new Vector2( c_y, 1 - c_z ),
  12993. new Vector2( d_y, 1 - d_z )
  12994. ];
  12995. }
  12996. }
  12997. };
  12998. function toJSON$1( shapes, options, data ) {
  12999. data.shapes = [];
  13000. if ( Array.isArray( shapes ) ) {
  13001. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13002. const shape = shapes[ i ];
  13003. data.shapes.push( shape.uuid );
  13004. }
  13005. } else {
  13006. data.shapes.push( shapes.uuid );
  13007. }
  13008. data.options = Object.assign( {}, options );
  13009. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13010. return data;
  13011. }
  13012. class IcosahedronGeometry extends PolyhedronGeometry {
  13013. constructor( radius = 1, detail = 0 ) {
  13014. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13015. const vertices = [
  13016. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13017. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13018. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13019. ];
  13020. const indices = [
  13021. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13022. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13023. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13024. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13025. ];
  13026. super( vertices, indices, radius, detail );
  13027. this.type = 'IcosahedronGeometry';
  13028. this.parameters = {
  13029. radius: radius,
  13030. detail: detail
  13031. };
  13032. }
  13033. static fromJSON( data ) {
  13034. return new IcosahedronGeometry( data.radius, data.detail );
  13035. }
  13036. }
  13037. class OctahedronGeometry extends PolyhedronGeometry {
  13038. constructor( radius = 1, detail = 0 ) {
  13039. const vertices = [
  13040. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13041. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13042. ];
  13043. const indices = [
  13044. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13045. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13046. 1, 3, 4, 1, 4, 2
  13047. ];
  13048. super( vertices, indices, radius, detail );
  13049. this.type = 'OctahedronGeometry';
  13050. this.parameters = {
  13051. radius: radius,
  13052. detail: detail
  13053. };
  13054. }
  13055. static fromJSON( data ) {
  13056. return new OctahedronGeometry( data.radius, data.detail );
  13057. }
  13058. }
  13059. class PlaneGeometry extends BufferGeometry {
  13060. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13061. super();
  13062. this.type = 'PlaneGeometry';
  13063. this.parameters = {
  13064. width: width,
  13065. height: height,
  13066. widthSegments: widthSegments,
  13067. heightSegments: heightSegments
  13068. };
  13069. const width_half = width / 2;
  13070. const height_half = height / 2;
  13071. const gridX = Math.floor( widthSegments );
  13072. const gridY = Math.floor( heightSegments );
  13073. const gridX1 = gridX + 1;
  13074. const gridY1 = gridY + 1;
  13075. const segment_width = width / gridX;
  13076. const segment_height = height / gridY;
  13077. //
  13078. const indices = [];
  13079. const vertices = [];
  13080. const normals = [];
  13081. const uvs = [];
  13082. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13083. const y = iy * segment_height - height_half;
  13084. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13085. const x = ix * segment_width - width_half;
  13086. vertices.push( x, - y, 0 );
  13087. normals.push( 0, 0, 1 );
  13088. uvs.push( ix / gridX );
  13089. uvs.push( 1 - ( iy / gridY ) );
  13090. }
  13091. }
  13092. for ( let iy = 0; iy < gridY; iy ++ ) {
  13093. for ( let ix = 0; ix < gridX; ix ++ ) {
  13094. const a = ix + gridX1 * iy;
  13095. const b = ix + gridX1 * ( iy + 1 );
  13096. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13097. const d = ( ix + 1 ) + gridX1 * iy;
  13098. indices.push( a, b, d );
  13099. indices.push( b, c, d );
  13100. }
  13101. }
  13102. this.setIndex( indices );
  13103. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13104. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13105. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13106. }
  13107. copy( source ) {
  13108. super.copy( source );
  13109. this.parameters = Object.assign( {}, source.parameters );
  13110. return this;
  13111. }
  13112. static fromJSON( data ) {
  13113. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13114. }
  13115. }
  13116. class RingGeometry extends BufferGeometry {
  13117. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13118. super();
  13119. this.type = 'RingGeometry';
  13120. this.parameters = {
  13121. innerRadius: innerRadius,
  13122. outerRadius: outerRadius,
  13123. thetaSegments: thetaSegments,
  13124. phiSegments: phiSegments,
  13125. thetaStart: thetaStart,
  13126. thetaLength: thetaLength
  13127. };
  13128. thetaSegments = Math.max( 3, thetaSegments );
  13129. phiSegments = Math.max( 1, phiSegments );
  13130. // buffers
  13131. const indices = [];
  13132. const vertices = [];
  13133. const normals = [];
  13134. const uvs = [];
  13135. // some helper variables
  13136. let radius = innerRadius;
  13137. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13138. const vertex = new Vector3();
  13139. const uv = new Vector2();
  13140. // generate vertices, normals and uvs
  13141. for ( let j = 0; j <= phiSegments; j ++ ) {
  13142. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13143. // values are generate from the inside of the ring to the outside
  13144. const segment = thetaStart + i / thetaSegments * thetaLength;
  13145. // vertex
  13146. vertex.x = radius * Math.cos( segment );
  13147. vertex.y = radius * Math.sin( segment );
  13148. vertices.push( vertex.x, vertex.y, vertex.z );
  13149. // normal
  13150. normals.push( 0, 0, 1 );
  13151. // uv
  13152. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13153. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13154. uvs.push( uv.x, uv.y );
  13155. }
  13156. // increase the radius for next row of vertices
  13157. radius += radiusStep;
  13158. }
  13159. // indices
  13160. for ( let j = 0; j < phiSegments; j ++ ) {
  13161. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13162. for ( let i = 0; i < thetaSegments; i ++ ) {
  13163. const segment = i + thetaSegmentLevel;
  13164. const a = segment;
  13165. const b = segment + thetaSegments + 1;
  13166. const c = segment + thetaSegments + 2;
  13167. const d = segment + 1;
  13168. // faces
  13169. indices.push( a, b, d );
  13170. indices.push( b, c, d );
  13171. }
  13172. }
  13173. // build geometry
  13174. this.setIndex( indices );
  13175. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13176. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13177. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13178. }
  13179. copy( source ) {
  13180. super.copy( source );
  13181. this.parameters = Object.assign( {}, source.parameters );
  13182. return this;
  13183. }
  13184. static fromJSON( data ) {
  13185. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13186. }
  13187. }
  13188. class ShapeGeometry extends BufferGeometry {
  13189. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13190. super();
  13191. this.type = 'ShapeGeometry';
  13192. this.parameters = {
  13193. shapes: shapes,
  13194. curveSegments: curveSegments
  13195. };
  13196. // buffers
  13197. const indices = [];
  13198. const vertices = [];
  13199. const normals = [];
  13200. const uvs = [];
  13201. // helper variables
  13202. let groupStart = 0;
  13203. let groupCount = 0;
  13204. // allow single and array values for "shapes" parameter
  13205. if ( Array.isArray( shapes ) === false ) {
  13206. addShape( shapes );
  13207. } else {
  13208. for ( let i = 0; i < shapes.length; i ++ ) {
  13209. addShape( shapes[ i ] );
  13210. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13211. groupStart += groupCount;
  13212. groupCount = 0;
  13213. }
  13214. }
  13215. // build geometry
  13216. this.setIndex( indices );
  13217. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13218. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13219. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13220. // helper functions
  13221. function addShape( shape ) {
  13222. const indexOffset = vertices.length / 3;
  13223. const points = shape.extractPoints( curveSegments );
  13224. let shapeVertices = points.shape;
  13225. const shapeHoles = points.holes;
  13226. // check direction of vertices
  13227. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13228. shapeVertices = shapeVertices.reverse();
  13229. }
  13230. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13231. const shapeHole = shapeHoles[ i ];
  13232. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13233. shapeHoles[ i ] = shapeHole.reverse();
  13234. }
  13235. }
  13236. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13237. // join vertices of inner and outer paths to a single array
  13238. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13239. const shapeHole = shapeHoles[ i ];
  13240. shapeVertices = shapeVertices.concat( shapeHole );
  13241. }
  13242. // vertices, normals, uvs
  13243. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13244. const vertex = shapeVertices[ i ];
  13245. vertices.push( vertex.x, vertex.y, 0 );
  13246. normals.push( 0, 0, 1 );
  13247. uvs.push( vertex.x, vertex.y ); // world uvs
  13248. }
  13249. // indices
  13250. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13251. const face = faces[ i ];
  13252. const a = face[ 0 ] + indexOffset;
  13253. const b = face[ 1 ] + indexOffset;
  13254. const c = face[ 2 ] + indexOffset;
  13255. indices.push( a, b, c );
  13256. groupCount += 3;
  13257. }
  13258. }
  13259. }
  13260. copy( source ) {
  13261. super.copy( source );
  13262. this.parameters = Object.assign( {}, source.parameters );
  13263. return this;
  13264. }
  13265. toJSON() {
  13266. const data = super.toJSON();
  13267. const shapes = this.parameters.shapes;
  13268. return toJSON( shapes, data );
  13269. }
  13270. static fromJSON( data, shapes ) {
  13271. const geometryShapes = [];
  13272. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13273. const shape = shapes[ data.shapes[ j ] ];
  13274. geometryShapes.push( shape );
  13275. }
  13276. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13277. }
  13278. }
  13279. function toJSON( shapes, data ) {
  13280. data.shapes = [];
  13281. if ( Array.isArray( shapes ) ) {
  13282. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13283. const shape = shapes[ i ];
  13284. data.shapes.push( shape.uuid );
  13285. }
  13286. } else {
  13287. data.shapes.push( shapes.uuid );
  13288. }
  13289. return data;
  13290. }
  13291. class SphereGeometry extends BufferGeometry {
  13292. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13293. super();
  13294. this.type = 'SphereGeometry';
  13295. this.parameters = {
  13296. radius: radius,
  13297. widthSegments: widthSegments,
  13298. heightSegments: heightSegments,
  13299. phiStart: phiStart,
  13300. phiLength: phiLength,
  13301. thetaStart: thetaStart,
  13302. thetaLength: thetaLength
  13303. };
  13304. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13305. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13306. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13307. let index = 0;
  13308. const grid = [];
  13309. const vertex = new Vector3();
  13310. const normal = new Vector3();
  13311. // buffers
  13312. const indices = [];
  13313. const vertices = [];
  13314. const normals = [];
  13315. const uvs = [];
  13316. // generate vertices, normals and uvs
  13317. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13318. const verticesRow = [];
  13319. const v = iy / heightSegments;
  13320. // special case for the poles
  13321. let uOffset = 0;
  13322. if ( iy === 0 && thetaStart === 0 ) {
  13323. uOffset = 0.5 / widthSegments;
  13324. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13325. uOffset = - 0.5 / widthSegments;
  13326. }
  13327. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13328. const u = ix / widthSegments;
  13329. // vertex
  13330. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13331. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13332. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13333. vertices.push( vertex.x, vertex.y, vertex.z );
  13334. // normal
  13335. normal.copy( vertex ).normalize();
  13336. normals.push( normal.x, normal.y, normal.z );
  13337. // uv
  13338. uvs.push( u + uOffset, 1 - v );
  13339. verticesRow.push( index ++ );
  13340. }
  13341. grid.push( verticesRow );
  13342. }
  13343. // indices
  13344. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13345. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13346. const a = grid[ iy ][ ix + 1 ];
  13347. const b = grid[ iy ][ ix ];
  13348. const c = grid[ iy + 1 ][ ix ];
  13349. const d = grid[ iy + 1 ][ ix + 1 ];
  13350. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13351. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13352. }
  13353. }
  13354. // build geometry
  13355. this.setIndex( indices );
  13356. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13357. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13358. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13359. }
  13360. copy( source ) {
  13361. super.copy( source );
  13362. this.parameters = Object.assign( {}, source.parameters );
  13363. return this;
  13364. }
  13365. static fromJSON( data ) {
  13366. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13367. }
  13368. }
  13369. class TetrahedronGeometry extends PolyhedronGeometry {
  13370. constructor( radius = 1, detail = 0 ) {
  13371. const vertices = [
  13372. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13373. ];
  13374. const indices = [
  13375. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13376. ];
  13377. super( vertices, indices, radius, detail );
  13378. this.type = 'TetrahedronGeometry';
  13379. this.parameters = {
  13380. radius: radius,
  13381. detail: detail
  13382. };
  13383. }
  13384. static fromJSON( data ) {
  13385. return new TetrahedronGeometry( data.radius, data.detail );
  13386. }
  13387. }
  13388. class TorusGeometry extends BufferGeometry {
  13389. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13390. super();
  13391. this.type = 'TorusGeometry';
  13392. this.parameters = {
  13393. radius: radius,
  13394. tube: tube,
  13395. radialSegments: radialSegments,
  13396. tubularSegments: tubularSegments,
  13397. arc: arc
  13398. };
  13399. radialSegments = Math.floor( radialSegments );
  13400. tubularSegments = Math.floor( tubularSegments );
  13401. // buffers
  13402. const indices = [];
  13403. const vertices = [];
  13404. const normals = [];
  13405. const uvs = [];
  13406. // helper variables
  13407. const center = new Vector3();
  13408. const vertex = new Vector3();
  13409. const normal = new Vector3();
  13410. // generate vertices, normals and uvs
  13411. for ( let j = 0; j <= radialSegments; j ++ ) {
  13412. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13413. const u = i / tubularSegments * arc;
  13414. const v = j / radialSegments * Math.PI * 2;
  13415. // vertex
  13416. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13417. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13418. vertex.z = tube * Math.sin( v );
  13419. vertices.push( vertex.x, vertex.y, vertex.z );
  13420. // normal
  13421. center.x = radius * Math.cos( u );
  13422. center.y = radius * Math.sin( u );
  13423. normal.subVectors( vertex, center ).normalize();
  13424. normals.push( normal.x, normal.y, normal.z );
  13425. // uv
  13426. uvs.push( i / tubularSegments );
  13427. uvs.push( j / radialSegments );
  13428. }
  13429. }
  13430. // generate indices
  13431. for ( let j = 1; j <= radialSegments; j ++ ) {
  13432. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13433. // indices
  13434. const a = ( tubularSegments + 1 ) * j + i - 1;
  13435. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13436. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13437. const d = ( tubularSegments + 1 ) * j + i;
  13438. // faces
  13439. indices.push( a, b, d );
  13440. indices.push( b, c, d );
  13441. }
  13442. }
  13443. // build geometry
  13444. this.setIndex( indices );
  13445. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13446. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13447. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13448. }
  13449. copy( source ) {
  13450. super.copy( source );
  13451. this.parameters = Object.assign( {}, source.parameters );
  13452. return this;
  13453. }
  13454. static fromJSON( data ) {
  13455. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13456. }
  13457. }
  13458. class TorusKnotGeometry extends BufferGeometry {
  13459. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13460. super();
  13461. this.type = 'TorusKnotGeometry';
  13462. this.parameters = {
  13463. radius: radius,
  13464. tube: tube,
  13465. tubularSegments: tubularSegments,
  13466. radialSegments: radialSegments,
  13467. p: p,
  13468. q: q
  13469. };
  13470. tubularSegments = Math.floor( tubularSegments );
  13471. radialSegments = Math.floor( radialSegments );
  13472. // buffers
  13473. const indices = [];
  13474. const vertices = [];
  13475. const normals = [];
  13476. const uvs = [];
  13477. // helper variables
  13478. const vertex = new Vector3();
  13479. const normal = new Vector3();
  13480. const P1 = new Vector3();
  13481. const P2 = new Vector3();
  13482. const B = new Vector3();
  13483. const T = new Vector3();
  13484. const N = new Vector3();
  13485. // generate vertices, normals and uvs
  13486. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13487. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13488. const u = i / tubularSegments * p * Math.PI * 2;
  13489. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13490. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13491. calculatePositionOnCurve( u, p, q, radius, P1 );
  13492. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13493. // calculate orthonormal basis
  13494. T.subVectors( P2, P1 );
  13495. N.addVectors( P2, P1 );
  13496. B.crossVectors( T, N );
  13497. N.crossVectors( B, T );
  13498. // normalize B, N. T can be ignored, we don't use it
  13499. B.normalize();
  13500. N.normalize();
  13501. for ( let j = 0; j <= radialSegments; ++ j ) {
  13502. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13503. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13504. const v = j / radialSegments * Math.PI * 2;
  13505. const cx = - tube * Math.cos( v );
  13506. const cy = tube * Math.sin( v );
  13507. // now calculate the final vertex position.
  13508. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13509. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13510. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13511. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13512. vertices.push( vertex.x, vertex.y, vertex.z );
  13513. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13514. normal.subVectors( vertex, P1 ).normalize();
  13515. normals.push( normal.x, normal.y, normal.z );
  13516. // uv
  13517. uvs.push( i / tubularSegments );
  13518. uvs.push( j / radialSegments );
  13519. }
  13520. }
  13521. // generate indices
  13522. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13523. for ( let i = 1; i <= radialSegments; i ++ ) {
  13524. // indices
  13525. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13526. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13527. const c = ( radialSegments + 1 ) * j + i;
  13528. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13529. // faces
  13530. indices.push( a, b, d );
  13531. indices.push( b, c, d );
  13532. }
  13533. }
  13534. // build geometry
  13535. this.setIndex( indices );
  13536. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13537. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13538. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13539. // this function calculates the current position on the torus curve
  13540. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13541. const cu = Math.cos( u );
  13542. const su = Math.sin( u );
  13543. const quOverP = q / p * u;
  13544. const cs = Math.cos( quOverP );
  13545. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13546. position.y = radius * ( 2 + cs ) * su * 0.5;
  13547. position.z = radius * Math.sin( quOverP ) * 0.5;
  13548. }
  13549. }
  13550. copy( source ) {
  13551. super.copy( source );
  13552. this.parameters = Object.assign( {}, source.parameters );
  13553. return this;
  13554. }
  13555. static fromJSON( data ) {
  13556. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13557. }
  13558. }
  13559. class TubeGeometry extends BufferGeometry {
  13560. 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 ) {
  13561. super();
  13562. this.type = 'TubeGeometry';
  13563. this.parameters = {
  13564. path: path,
  13565. tubularSegments: tubularSegments,
  13566. radius: radius,
  13567. radialSegments: radialSegments,
  13568. closed: closed
  13569. };
  13570. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13571. // expose internals
  13572. this.tangents = frames.tangents;
  13573. this.normals = frames.normals;
  13574. this.binormals = frames.binormals;
  13575. // helper variables
  13576. const vertex = new Vector3();
  13577. const normal = new Vector3();
  13578. const uv = new Vector2();
  13579. let P = new Vector3();
  13580. // buffer
  13581. const vertices = [];
  13582. const normals = [];
  13583. const uvs = [];
  13584. const indices = [];
  13585. // create buffer data
  13586. generateBufferData();
  13587. // build geometry
  13588. this.setIndex( indices );
  13589. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13590. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13591. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13592. // functions
  13593. function generateBufferData() {
  13594. for ( let i = 0; i < tubularSegments; i ++ ) {
  13595. generateSegment( i );
  13596. }
  13597. // if the geometry is not closed, generate the last row of vertices and normals
  13598. // at the regular position on the given path
  13599. //
  13600. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13601. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13602. // uvs are generated in a separate function.
  13603. // this makes it easy compute correct values for closed geometries
  13604. generateUVs();
  13605. // finally create faces
  13606. generateIndices();
  13607. }
  13608. function generateSegment( i ) {
  13609. // we use getPointAt to sample evenly distributed points from the given path
  13610. P = path.getPointAt( i / tubularSegments, P );
  13611. // retrieve corresponding normal and binormal
  13612. const N = frames.normals[ i ];
  13613. const B = frames.binormals[ i ];
  13614. // generate normals and vertices for the current segment
  13615. for ( let j = 0; j <= radialSegments; j ++ ) {
  13616. const v = j / radialSegments * Math.PI * 2;
  13617. const sin = Math.sin( v );
  13618. const cos = - Math.cos( v );
  13619. // normal
  13620. normal.x = ( cos * N.x + sin * B.x );
  13621. normal.y = ( cos * N.y + sin * B.y );
  13622. normal.z = ( cos * N.z + sin * B.z );
  13623. normal.normalize();
  13624. normals.push( normal.x, normal.y, normal.z );
  13625. // vertex
  13626. vertex.x = P.x + radius * normal.x;
  13627. vertex.y = P.y + radius * normal.y;
  13628. vertex.z = P.z + radius * normal.z;
  13629. vertices.push( vertex.x, vertex.y, vertex.z );
  13630. }
  13631. }
  13632. function generateIndices() {
  13633. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13634. for ( let i = 1; i <= radialSegments; i ++ ) {
  13635. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13636. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13637. const c = ( radialSegments + 1 ) * j + i;
  13638. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13639. // faces
  13640. indices.push( a, b, d );
  13641. indices.push( b, c, d );
  13642. }
  13643. }
  13644. }
  13645. function generateUVs() {
  13646. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13647. for ( let j = 0; j <= radialSegments; j ++ ) {
  13648. uv.x = i / tubularSegments;
  13649. uv.y = j / radialSegments;
  13650. uvs.push( uv.x, uv.y );
  13651. }
  13652. }
  13653. }
  13654. }
  13655. copy( source ) {
  13656. super.copy( source );
  13657. this.parameters = Object.assign( {}, source.parameters );
  13658. return this;
  13659. }
  13660. toJSON() {
  13661. const data = super.toJSON();
  13662. data.path = this.parameters.path.toJSON();
  13663. return data;
  13664. }
  13665. static fromJSON( data ) {
  13666. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13667. // User defined curves or instances of CurvePath will not be deserialized.
  13668. return new TubeGeometry(
  13669. new Curves[ data.path.type ]().fromJSON( data.path ),
  13670. data.tubularSegments,
  13671. data.radius,
  13672. data.radialSegments,
  13673. data.closed
  13674. );
  13675. }
  13676. }
  13677. class WireframeGeometry extends BufferGeometry {
  13678. constructor( geometry = null ) {
  13679. super();
  13680. this.type = 'WireframeGeometry';
  13681. this.parameters = {
  13682. geometry: geometry
  13683. };
  13684. if ( geometry !== null ) {
  13685. // buffer
  13686. const vertices = [];
  13687. const edges = new Set();
  13688. // helper variables
  13689. const start = new Vector3();
  13690. const end = new Vector3();
  13691. if ( geometry.index !== null ) {
  13692. // indexed BufferGeometry
  13693. const position = geometry.attributes.position;
  13694. const indices = geometry.index;
  13695. let groups = geometry.groups;
  13696. if ( groups.length === 0 ) {
  13697. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13698. }
  13699. // create a data structure that contains all edges without duplicates
  13700. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13701. const group = groups[ o ];
  13702. const groupStart = group.start;
  13703. const groupCount = group.count;
  13704. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13705. for ( let j = 0; j < 3; j ++ ) {
  13706. const index1 = indices.getX( i + j );
  13707. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13708. start.fromBufferAttribute( position, index1 );
  13709. end.fromBufferAttribute( position, index2 );
  13710. if ( isUniqueEdge( start, end, edges ) === true ) {
  13711. vertices.push( start.x, start.y, start.z );
  13712. vertices.push( end.x, end.y, end.z );
  13713. }
  13714. }
  13715. }
  13716. }
  13717. } else {
  13718. // non-indexed BufferGeometry
  13719. const position = geometry.attributes.position;
  13720. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13721. for ( let j = 0; j < 3; j ++ ) {
  13722. // three edges per triangle, an edge is represented as (index1, index2)
  13723. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13724. const index1 = 3 * i + j;
  13725. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13726. start.fromBufferAttribute( position, index1 );
  13727. end.fromBufferAttribute( position, index2 );
  13728. if ( isUniqueEdge( start, end, edges ) === true ) {
  13729. vertices.push( start.x, start.y, start.z );
  13730. vertices.push( end.x, end.y, end.z );
  13731. }
  13732. }
  13733. }
  13734. }
  13735. // build geometry
  13736. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13737. }
  13738. }
  13739. copy( source ) {
  13740. super.copy( source );
  13741. this.parameters = Object.assign( {}, source.parameters );
  13742. return this;
  13743. }
  13744. }
  13745. function isUniqueEdge( start, end, edges ) {
  13746. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13747. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13748. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13749. return false;
  13750. } else {
  13751. edges.add( hash1 );
  13752. edges.add( hash2 );
  13753. return true;
  13754. }
  13755. }
  13756. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13757. __proto__: null,
  13758. BoxGeometry: BoxGeometry,
  13759. CapsuleGeometry: CapsuleGeometry,
  13760. CircleGeometry: CircleGeometry,
  13761. ConeGeometry: ConeGeometry,
  13762. CylinderGeometry: CylinderGeometry,
  13763. DodecahedronGeometry: DodecahedronGeometry,
  13764. EdgesGeometry: EdgesGeometry,
  13765. ExtrudeGeometry: ExtrudeGeometry,
  13766. IcosahedronGeometry: IcosahedronGeometry,
  13767. LatheGeometry: LatheGeometry,
  13768. OctahedronGeometry: OctahedronGeometry,
  13769. PlaneGeometry: PlaneGeometry,
  13770. PolyhedronGeometry: PolyhedronGeometry,
  13771. RingGeometry: RingGeometry,
  13772. ShapeGeometry: ShapeGeometry,
  13773. SphereGeometry: SphereGeometry,
  13774. TetrahedronGeometry: TetrahedronGeometry,
  13775. TorusGeometry: TorusGeometry,
  13776. TorusKnotGeometry: TorusKnotGeometry,
  13777. TubeGeometry: TubeGeometry,
  13778. WireframeGeometry: WireframeGeometry
  13779. });
  13780. class ShadowMaterial extends Material {
  13781. constructor( parameters ) {
  13782. super();
  13783. this.isShadowMaterial = true;
  13784. this.type = 'ShadowMaterial';
  13785. this.color = new Color( 0x000000 );
  13786. this.transparent = true;
  13787. this.fog = true;
  13788. this.setValues( parameters );
  13789. }
  13790. copy( source ) {
  13791. super.copy( source );
  13792. this.color.copy( source.color );
  13793. this.fog = source.fog;
  13794. return this;
  13795. }
  13796. }
  13797. class RawShaderMaterial extends ShaderMaterial {
  13798. constructor( parameters ) {
  13799. super( parameters );
  13800. this.isRawShaderMaterial = true;
  13801. this.type = 'RawShaderMaterial';
  13802. }
  13803. }
  13804. class MeshStandardMaterial extends Material {
  13805. constructor( parameters ) {
  13806. super();
  13807. this.isMeshStandardMaterial = true;
  13808. this.defines = { 'STANDARD': '' };
  13809. this.type = 'MeshStandardMaterial';
  13810. this.color = new Color( 0xffffff ); // diffuse
  13811. this.roughness = 1.0;
  13812. this.metalness = 0.0;
  13813. this.map = null;
  13814. this.lightMap = null;
  13815. this.lightMapIntensity = 1.0;
  13816. this.aoMap = null;
  13817. this.aoMapIntensity = 1.0;
  13818. this.emissive = new Color( 0x000000 );
  13819. this.emissiveIntensity = 1.0;
  13820. this.emissiveMap = null;
  13821. this.bumpMap = null;
  13822. this.bumpScale = 1;
  13823. this.normalMap = null;
  13824. this.normalMapType = TangentSpaceNormalMap;
  13825. this.normalScale = new Vector2( 1, 1 );
  13826. this.displacementMap = null;
  13827. this.displacementScale = 1;
  13828. this.displacementBias = 0;
  13829. this.roughnessMap = null;
  13830. this.metalnessMap = null;
  13831. this.alphaMap = null;
  13832. this.envMap = null;
  13833. this.envMapRotation = new Euler();
  13834. this.envMapIntensity = 1.0;
  13835. this.wireframe = false;
  13836. this.wireframeLinewidth = 1;
  13837. this.wireframeLinecap = 'round';
  13838. this.wireframeLinejoin = 'round';
  13839. this.flatShading = false;
  13840. this.fog = true;
  13841. this.setValues( parameters );
  13842. }
  13843. copy( source ) {
  13844. super.copy( source );
  13845. this.defines = { 'STANDARD': '' };
  13846. this.color.copy( source.color );
  13847. this.roughness = source.roughness;
  13848. this.metalness = source.metalness;
  13849. this.map = source.map;
  13850. this.lightMap = source.lightMap;
  13851. this.lightMapIntensity = source.lightMapIntensity;
  13852. this.aoMap = source.aoMap;
  13853. this.aoMapIntensity = source.aoMapIntensity;
  13854. this.emissive.copy( source.emissive );
  13855. this.emissiveMap = source.emissiveMap;
  13856. this.emissiveIntensity = source.emissiveIntensity;
  13857. this.bumpMap = source.bumpMap;
  13858. this.bumpScale = source.bumpScale;
  13859. this.normalMap = source.normalMap;
  13860. this.normalMapType = source.normalMapType;
  13861. this.normalScale.copy( source.normalScale );
  13862. this.displacementMap = source.displacementMap;
  13863. this.displacementScale = source.displacementScale;
  13864. this.displacementBias = source.displacementBias;
  13865. this.roughnessMap = source.roughnessMap;
  13866. this.metalnessMap = source.metalnessMap;
  13867. this.alphaMap = source.alphaMap;
  13868. this.envMap = source.envMap;
  13869. this.envMapRotation.copy( source.envMapRotation );
  13870. this.envMapIntensity = source.envMapIntensity;
  13871. this.wireframe = source.wireframe;
  13872. this.wireframeLinewidth = source.wireframeLinewidth;
  13873. this.wireframeLinecap = source.wireframeLinecap;
  13874. this.wireframeLinejoin = source.wireframeLinejoin;
  13875. this.flatShading = source.flatShading;
  13876. this.fog = source.fog;
  13877. return this;
  13878. }
  13879. }
  13880. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13881. constructor( parameters ) {
  13882. super();
  13883. this.isMeshPhysicalMaterial = true;
  13884. this.defines = {
  13885. 'STANDARD': '',
  13886. 'PHYSICAL': ''
  13887. };
  13888. this.type = 'MeshPhysicalMaterial';
  13889. this.anisotropyRotation = 0;
  13890. this.anisotropyMap = null;
  13891. this.clearcoatMap = null;
  13892. this.clearcoatRoughness = 0.0;
  13893. this.clearcoatRoughnessMap = null;
  13894. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13895. this.clearcoatNormalMap = null;
  13896. this.ior = 1.5;
  13897. Object.defineProperty( this, 'reflectivity', {
  13898. get: function () {
  13899. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13900. },
  13901. set: function ( reflectivity ) {
  13902. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13903. }
  13904. } );
  13905. this.iridescenceMap = null;
  13906. this.iridescenceIOR = 1.3;
  13907. this.iridescenceThicknessRange = [ 100, 400 ];
  13908. this.iridescenceThicknessMap = null;
  13909. this.sheenColor = new Color( 0x000000 );
  13910. this.sheenColorMap = null;
  13911. this.sheenRoughness = 1.0;
  13912. this.sheenRoughnessMap = null;
  13913. this.transmissionMap = null;
  13914. this.thickness = 0;
  13915. this.thicknessMap = null;
  13916. this.attenuationDistance = Infinity;
  13917. this.attenuationColor = new Color( 1, 1, 1 );
  13918. this.specularIntensity = 1.0;
  13919. this.specularIntensityMap = null;
  13920. this.specularColor = new Color( 1, 1, 1 );
  13921. this.specularColorMap = null;
  13922. this._anisotropy = 0;
  13923. this._clearcoat = 0;
  13924. this._dispersion = 0;
  13925. this._iridescence = 0;
  13926. this._sheen = 0.0;
  13927. this._transmission = 0;
  13928. this.setValues( parameters );
  13929. }
  13930. get anisotropy() {
  13931. return this._anisotropy;
  13932. }
  13933. set anisotropy( value ) {
  13934. if ( this._anisotropy > 0 !== value > 0 ) {
  13935. this.version ++;
  13936. }
  13937. this._anisotropy = value;
  13938. }
  13939. get clearcoat() {
  13940. return this._clearcoat;
  13941. }
  13942. set clearcoat( value ) {
  13943. if ( this._clearcoat > 0 !== value > 0 ) {
  13944. this.version ++;
  13945. }
  13946. this._clearcoat = value;
  13947. }
  13948. get iridescence() {
  13949. return this._iridescence;
  13950. }
  13951. set iridescence( value ) {
  13952. if ( this._iridescence > 0 !== value > 0 ) {
  13953. this.version ++;
  13954. }
  13955. this._iridescence = value;
  13956. }
  13957. get dispersion() {
  13958. return this._dispersion;
  13959. }
  13960. set dispersion( value ) {
  13961. if ( this._dispersion > 0 !== value > 0 ) {
  13962. this.version ++;
  13963. }
  13964. this._dispersion = value;
  13965. }
  13966. get sheen() {
  13967. return this._sheen;
  13968. }
  13969. set sheen( value ) {
  13970. if ( this._sheen > 0 !== value > 0 ) {
  13971. this.version ++;
  13972. }
  13973. this._sheen = value;
  13974. }
  13975. get transmission() {
  13976. return this._transmission;
  13977. }
  13978. set transmission( value ) {
  13979. if ( this._transmission > 0 !== value > 0 ) {
  13980. this.version ++;
  13981. }
  13982. this._transmission = value;
  13983. }
  13984. copy( source ) {
  13985. super.copy( source );
  13986. this.defines = {
  13987. 'STANDARD': '',
  13988. 'PHYSICAL': ''
  13989. };
  13990. this.anisotropy = source.anisotropy;
  13991. this.anisotropyRotation = source.anisotropyRotation;
  13992. this.anisotropyMap = source.anisotropyMap;
  13993. this.clearcoat = source.clearcoat;
  13994. this.clearcoatMap = source.clearcoatMap;
  13995. this.clearcoatRoughness = source.clearcoatRoughness;
  13996. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  13997. this.clearcoatNormalMap = source.clearcoatNormalMap;
  13998. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  13999. this.dispersion = source.dispersion;
  14000. this.ior = source.ior;
  14001. this.iridescence = source.iridescence;
  14002. this.iridescenceMap = source.iridescenceMap;
  14003. this.iridescenceIOR = source.iridescenceIOR;
  14004. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14005. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14006. this.sheen = source.sheen;
  14007. this.sheenColor.copy( source.sheenColor );
  14008. this.sheenColorMap = source.sheenColorMap;
  14009. this.sheenRoughness = source.sheenRoughness;
  14010. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14011. this.transmission = source.transmission;
  14012. this.transmissionMap = source.transmissionMap;
  14013. this.thickness = source.thickness;
  14014. this.thicknessMap = source.thicknessMap;
  14015. this.attenuationDistance = source.attenuationDistance;
  14016. this.attenuationColor.copy( source.attenuationColor );
  14017. this.specularIntensity = source.specularIntensity;
  14018. this.specularIntensityMap = source.specularIntensityMap;
  14019. this.specularColor.copy( source.specularColor );
  14020. this.specularColorMap = source.specularColorMap;
  14021. return this;
  14022. }
  14023. }
  14024. class MeshPhongMaterial extends Material {
  14025. constructor( parameters ) {
  14026. super();
  14027. this.isMeshPhongMaterial = true;
  14028. this.type = 'MeshPhongMaterial';
  14029. this.color = new Color( 0xffffff ); // diffuse
  14030. this.specular = new Color( 0x111111 );
  14031. this.shininess = 30;
  14032. this.map = null;
  14033. this.lightMap = null;
  14034. this.lightMapIntensity = 1.0;
  14035. this.aoMap = null;
  14036. this.aoMapIntensity = 1.0;
  14037. this.emissive = new Color( 0x000000 );
  14038. this.emissiveIntensity = 1.0;
  14039. this.emissiveMap = null;
  14040. this.bumpMap = null;
  14041. this.bumpScale = 1;
  14042. this.normalMap = null;
  14043. this.normalMapType = TangentSpaceNormalMap;
  14044. this.normalScale = new Vector2( 1, 1 );
  14045. this.displacementMap = null;
  14046. this.displacementScale = 1;
  14047. this.displacementBias = 0;
  14048. this.specularMap = null;
  14049. this.alphaMap = null;
  14050. this.envMap = null;
  14051. this.envMapRotation = new Euler();
  14052. this.combine = MultiplyOperation;
  14053. this.reflectivity = 1;
  14054. this.refractionRatio = 0.98;
  14055. this.wireframe = false;
  14056. this.wireframeLinewidth = 1;
  14057. this.wireframeLinecap = 'round';
  14058. this.wireframeLinejoin = 'round';
  14059. this.flatShading = false;
  14060. this.fog = true;
  14061. this.setValues( parameters );
  14062. }
  14063. copy( source ) {
  14064. super.copy( source );
  14065. this.color.copy( source.color );
  14066. this.specular.copy( source.specular );
  14067. this.shininess = source.shininess;
  14068. this.map = source.map;
  14069. this.lightMap = source.lightMap;
  14070. this.lightMapIntensity = source.lightMapIntensity;
  14071. this.aoMap = source.aoMap;
  14072. this.aoMapIntensity = source.aoMapIntensity;
  14073. this.emissive.copy( source.emissive );
  14074. this.emissiveMap = source.emissiveMap;
  14075. this.emissiveIntensity = source.emissiveIntensity;
  14076. this.bumpMap = source.bumpMap;
  14077. this.bumpScale = source.bumpScale;
  14078. this.normalMap = source.normalMap;
  14079. this.normalMapType = source.normalMapType;
  14080. this.normalScale.copy( source.normalScale );
  14081. this.displacementMap = source.displacementMap;
  14082. this.displacementScale = source.displacementScale;
  14083. this.displacementBias = source.displacementBias;
  14084. this.specularMap = source.specularMap;
  14085. this.alphaMap = source.alphaMap;
  14086. this.envMap = source.envMap;
  14087. this.envMapRotation.copy( source.envMapRotation );
  14088. this.combine = source.combine;
  14089. this.reflectivity = source.reflectivity;
  14090. this.refractionRatio = source.refractionRatio;
  14091. this.wireframe = source.wireframe;
  14092. this.wireframeLinewidth = source.wireframeLinewidth;
  14093. this.wireframeLinecap = source.wireframeLinecap;
  14094. this.wireframeLinejoin = source.wireframeLinejoin;
  14095. this.flatShading = source.flatShading;
  14096. this.fog = source.fog;
  14097. return this;
  14098. }
  14099. }
  14100. class MeshToonMaterial extends Material {
  14101. constructor( parameters ) {
  14102. super();
  14103. this.isMeshToonMaterial = true;
  14104. this.defines = { 'TOON': '' };
  14105. this.type = 'MeshToonMaterial';
  14106. this.color = new Color( 0xffffff );
  14107. this.map = null;
  14108. this.gradientMap = null;
  14109. this.lightMap = null;
  14110. this.lightMapIntensity = 1.0;
  14111. this.aoMap = null;
  14112. this.aoMapIntensity = 1.0;
  14113. this.emissive = new Color( 0x000000 );
  14114. this.emissiveIntensity = 1.0;
  14115. this.emissiveMap = null;
  14116. this.bumpMap = null;
  14117. this.bumpScale = 1;
  14118. this.normalMap = null;
  14119. this.normalMapType = TangentSpaceNormalMap;
  14120. this.normalScale = new Vector2( 1, 1 );
  14121. this.displacementMap = null;
  14122. this.displacementScale = 1;
  14123. this.displacementBias = 0;
  14124. this.alphaMap = null;
  14125. this.wireframe = false;
  14126. this.wireframeLinewidth = 1;
  14127. this.wireframeLinecap = 'round';
  14128. this.wireframeLinejoin = 'round';
  14129. this.fog = true;
  14130. this.setValues( parameters );
  14131. }
  14132. copy( source ) {
  14133. super.copy( source );
  14134. this.color.copy( source.color );
  14135. this.map = source.map;
  14136. this.gradientMap = source.gradientMap;
  14137. this.lightMap = source.lightMap;
  14138. this.lightMapIntensity = source.lightMapIntensity;
  14139. this.aoMap = source.aoMap;
  14140. this.aoMapIntensity = source.aoMapIntensity;
  14141. this.emissive.copy( source.emissive );
  14142. this.emissiveMap = source.emissiveMap;
  14143. this.emissiveIntensity = source.emissiveIntensity;
  14144. this.bumpMap = source.bumpMap;
  14145. this.bumpScale = source.bumpScale;
  14146. this.normalMap = source.normalMap;
  14147. this.normalMapType = source.normalMapType;
  14148. this.normalScale.copy( source.normalScale );
  14149. this.displacementMap = source.displacementMap;
  14150. this.displacementScale = source.displacementScale;
  14151. this.displacementBias = source.displacementBias;
  14152. this.alphaMap = source.alphaMap;
  14153. this.wireframe = source.wireframe;
  14154. this.wireframeLinewidth = source.wireframeLinewidth;
  14155. this.wireframeLinecap = source.wireframeLinecap;
  14156. this.wireframeLinejoin = source.wireframeLinejoin;
  14157. this.fog = source.fog;
  14158. return this;
  14159. }
  14160. }
  14161. class MeshNormalMaterial extends Material {
  14162. constructor( parameters ) {
  14163. super();
  14164. this.isMeshNormalMaterial = true;
  14165. this.type = 'MeshNormalMaterial';
  14166. this.bumpMap = null;
  14167. this.bumpScale = 1;
  14168. this.normalMap = null;
  14169. this.normalMapType = TangentSpaceNormalMap;
  14170. this.normalScale = new Vector2( 1, 1 );
  14171. this.displacementMap = null;
  14172. this.displacementScale = 1;
  14173. this.displacementBias = 0;
  14174. this.wireframe = false;
  14175. this.wireframeLinewidth = 1;
  14176. this.flatShading = false;
  14177. this.setValues( parameters );
  14178. }
  14179. copy( source ) {
  14180. super.copy( source );
  14181. this.bumpMap = source.bumpMap;
  14182. this.bumpScale = source.bumpScale;
  14183. this.normalMap = source.normalMap;
  14184. this.normalMapType = source.normalMapType;
  14185. this.normalScale.copy( source.normalScale );
  14186. this.displacementMap = source.displacementMap;
  14187. this.displacementScale = source.displacementScale;
  14188. this.displacementBias = source.displacementBias;
  14189. this.wireframe = source.wireframe;
  14190. this.wireframeLinewidth = source.wireframeLinewidth;
  14191. this.flatShading = source.flatShading;
  14192. return this;
  14193. }
  14194. }
  14195. class MeshLambertMaterial extends Material {
  14196. constructor( parameters ) {
  14197. super();
  14198. this.isMeshLambertMaterial = true;
  14199. this.type = 'MeshLambertMaterial';
  14200. this.color = new Color( 0xffffff ); // diffuse
  14201. this.map = null;
  14202. this.lightMap = null;
  14203. this.lightMapIntensity = 1.0;
  14204. this.aoMap = null;
  14205. this.aoMapIntensity = 1.0;
  14206. this.emissive = new Color( 0x000000 );
  14207. this.emissiveIntensity = 1.0;
  14208. this.emissiveMap = null;
  14209. this.bumpMap = null;
  14210. this.bumpScale = 1;
  14211. this.normalMap = null;
  14212. this.normalMapType = TangentSpaceNormalMap;
  14213. this.normalScale = new Vector2( 1, 1 );
  14214. this.displacementMap = null;
  14215. this.displacementScale = 1;
  14216. this.displacementBias = 0;
  14217. this.specularMap = null;
  14218. this.alphaMap = null;
  14219. this.envMap = null;
  14220. this.envMapRotation = new Euler();
  14221. this.combine = MultiplyOperation;
  14222. this.reflectivity = 1;
  14223. this.refractionRatio = 0.98;
  14224. this.wireframe = false;
  14225. this.wireframeLinewidth = 1;
  14226. this.wireframeLinecap = 'round';
  14227. this.wireframeLinejoin = 'round';
  14228. this.flatShading = false;
  14229. this.fog = true;
  14230. this.setValues( parameters );
  14231. }
  14232. copy( source ) {
  14233. super.copy( source );
  14234. this.color.copy( source.color );
  14235. this.map = source.map;
  14236. this.lightMap = source.lightMap;
  14237. this.lightMapIntensity = source.lightMapIntensity;
  14238. this.aoMap = source.aoMap;
  14239. this.aoMapIntensity = source.aoMapIntensity;
  14240. this.emissive.copy( source.emissive );
  14241. this.emissiveMap = source.emissiveMap;
  14242. this.emissiveIntensity = source.emissiveIntensity;
  14243. this.bumpMap = source.bumpMap;
  14244. this.bumpScale = source.bumpScale;
  14245. this.normalMap = source.normalMap;
  14246. this.normalMapType = source.normalMapType;
  14247. this.normalScale.copy( source.normalScale );
  14248. this.displacementMap = source.displacementMap;
  14249. this.displacementScale = source.displacementScale;
  14250. this.displacementBias = source.displacementBias;
  14251. this.specularMap = source.specularMap;
  14252. this.alphaMap = source.alphaMap;
  14253. this.envMap = source.envMap;
  14254. this.envMapRotation.copy( source.envMapRotation );
  14255. this.combine = source.combine;
  14256. this.reflectivity = source.reflectivity;
  14257. this.refractionRatio = source.refractionRatio;
  14258. this.wireframe = source.wireframe;
  14259. this.wireframeLinewidth = source.wireframeLinewidth;
  14260. this.wireframeLinecap = source.wireframeLinecap;
  14261. this.wireframeLinejoin = source.wireframeLinejoin;
  14262. this.flatShading = source.flatShading;
  14263. this.fog = source.fog;
  14264. return this;
  14265. }
  14266. }
  14267. class MeshDepthMaterial extends Material {
  14268. constructor( parameters ) {
  14269. super();
  14270. this.isMeshDepthMaterial = true;
  14271. this.type = 'MeshDepthMaterial';
  14272. this.depthPacking = BasicDepthPacking;
  14273. this.map = null;
  14274. this.alphaMap = null;
  14275. this.displacementMap = null;
  14276. this.displacementScale = 1;
  14277. this.displacementBias = 0;
  14278. this.wireframe = false;
  14279. this.wireframeLinewidth = 1;
  14280. this.setValues( parameters );
  14281. }
  14282. copy( source ) {
  14283. super.copy( source );
  14284. this.depthPacking = source.depthPacking;
  14285. this.map = source.map;
  14286. this.alphaMap = source.alphaMap;
  14287. this.displacementMap = source.displacementMap;
  14288. this.displacementScale = source.displacementScale;
  14289. this.displacementBias = source.displacementBias;
  14290. this.wireframe = source.wireframe;
  14291. this.wireframeLinewidth = source.wireframeLinewidth;
  14292. return this;
  14293. }
  14294. }
  14295. class MeshDistanceMaterial extends Material {
  14296. constructor( parameters ) {
  14297. super();
  14298. this.isMeshDistanceMaterial = true;
  14299. this.type = 'MeshDistanceMaterial';
  14300. this.map = null;
  14301. this.alphaMap = null;
  14302. this.displacementMap = null;
  14303. this.displacementScale = 1;
  14304. this.displacementBias = 0;
  14305. this.setValues( parameters );
  14306. }
  14307. copy( source ) {
  14308. super.copy( source );
  14309. this.map = source.map;
  14310. this.alphaMap = source.alphaMap;
  14311. this.displacementMap = source.displacementMap;
  14312. this.displacementScale = source.displacementScale;
  14313. this.displacementBias = source.displacementBias;
  14314. return this;
  14315. }
  14316. }
  14317. class MeshMatcapMaterial extends Material {
  14318. constructor( parameters ) {
  14319. super();
  14320. this.isMeshMatcapMaterial = true;
  14321. this.defines = { 'MATCAP': '' };
  14322. this.type = 'MeshMatcapMaterial';
  14323. this.color = new Color( 0xffffff ); // diffuse
  14324. this.matcap = null;
  14325. this.map = null;
  14326. this.bumpMap = null;
  14327. this.bumpScale = 1;
  14328. this.normalMap = null;
  14329. this.normalMapType = TangentSpaceNormalMap;
  14330. this.normalScale = new Vector2( 1, 1 );
  14331. this.displacementMap = null;
  14332. this.displacementScale = 1;
  14333. this.displacementBias = 0;
  14334. this.alphaMap = null;
  14335. this.flatShading = false;
  14336. this.fog = true;
  14337. this.setValues( parameters );
  14338. }
  14339. copy( source ) {
  14340. super.copy( source );
  14341. this.defines = { 'MATCAP': '' };
  14342. this.color.copy( source.color );
  14343. this.matcap = source.matcap;
  14344. this.map = source.map;
  14345. this.bumpMap = source.bumpMap;
  14346. this.bumpScale = source.bumpScale;
  14347. this.normalMap = source.normalMap;
  14348. this.normalMapType = source.normalMapType;
  14349. this.normalScale.copy( source.normalScale );
  14350. this.displacementMap = source.displacementMap;
  14351. this.displacementScale = source.displacementScale;
  14352. this.displacementBias = source.displacementBias;
  14353. this.alphaMap = source.alphaMap;
  14354. this.flatShading = source.flatShading;
  14355. this.fog = source.fog;
  14356. return this;
  14357. }
  14358. }
  14359. class LineDashedMaterial extends LineBasicMaterial {
  14360. constructor( parameters ) {
  14361. super();
  14362. this.isLineDashedMaterial = true;
  14363. this.type = 'LineDashedMaterial';
  14364. this.scale = 1;
  14365. this.dashSize = 3;
  14366. this.gapSize = 1;
  14367. this.setValues( parameters );
  14368. }
  14369. copy( source ) {
  14370. super.copy( source );
  14371. this.scale = source.scale;
  14372. this.dashSize = source.dashSize;
  14373. this.gapSize = source.gapSize;
  14374. return this;
  14375. }
  14376. }
  14377. // converts an array to a specific type
  14378. function convertArray( array, type, forceClone ) {
  14379. if ( ! array || // let 'undefined' and 'null' pass
  14380. ! forceClone && array.constructor === type ) return array;
  14381. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14382. return new type( array ); // create typed array
  14383. }
  14384. return Array.prototype.slice.call( array ); // create Array
  14385. }
  14386. function isTypedArray( object ) {
  14387. return ArrayBuffer.isView( object ) &&
  14388. ! ( object instanceof DataView );
  14389. }
  14390. // returns an array by which times and values can be sorted
  14391. function getKeyframeOrder( times ) {
  14392. function compareTime( i, j ) {
  14393. return times[ i ] - times[ j ];
  14394. }
  14395. const n = times.length;
  14396. const result = new Array( n );
  14397. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14398. result.sort( compareTime );
  14399. return result;
  14400. }
  14401. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14402. function sortedArray( values, stride, order ) {
  14403. const nValues = values.length;
  14404. const result = new values.constructor( nValues );
  14405. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14406. const srcOffset = order[ i ] * stride;
  14407. for ( let j = 0; j !== stride; ++ j ) {
  14408. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14409. }
  14410. }
  14411. return result;
  14412. }
  14413. // function for parsing AOS keyframe formats
  14414. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14415. let i = 1, key = jsonKeys[ 0 ];
  14416. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14417. key = jsonKeys[ i ++ ];
  14418. }
  14419. if ( key === undefined ) return; // no data
  14420. let value = key[ valuePropertyName ];
  14421. if ( value === undefined ) return; // no data
  14422. if ( Array.isArray( value ) ) {
  14423. do {
  14424. value = key[ valuePropertyName ];
  14425. if ( value !== undefined ) {
  14426. times.push( key.time );
  14427. values.push.apply( values, value ); // push all elements
  14428. }
  14429. key = jsonKeys[ i ++ ];
  14430. } while ( key !== undefined );
  14431. } else if ( value.toArray !== undefined ) {
  14432. // ...assume THREE.Math-ish
  14433. do {
  14434. value = key[ valuePropertyName ];
  14435. if ( value !== undefined ) {
  14436. times.push( key.time );
  14437. value.toArray( values, values.length );
  14438. }
  14439. key = jsonKeys[ i ++ ];
  14440. } while ( key !== undefined );
  14441. } else {
  14442. // otherwise push as-is
  14443. do {
  14444. value = key[ valuePropertyName ];
  14445. if ( value !== undefined ) {
  14446. times.push( key.time );
  14447. values.push( value );
  14448. }
  14449. key = jsonKeys[ i ++ ];
  14450. } while ( key !== undefined );
  14451. }
  14452. }
  14453. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14454. const clip = sourceClip.clone();
  14455. clip.name = name;
  14456. const tracks = [];
  14457. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14458. const track = clip.tracks[ i ];
  14459. const valueSize = track.getValueSize();
  14460. const times = [];
  14461. const values = [];
  14462. for ( let j = 0; j < track.times.length; ++ j ) {
  14463. const frame = track.times[ j ] * fps;
  14464. if ( frame < startFrame || frame >= endFrame ) continue;
  14465. times.push( track.times[ j ] );
  14466. for ( let k = 0; k < valueSize; ++ k ) {
  14467. values.push( track.values[ j * valueSize + k ] );
  14468. }
  14469. }
  14470. if ( times.length === 0 ) continue;
  14471. track.times = convertArray( times, track.times.constructor );
  14472. track.values = convertArray( values, track.values.constructor );
  14473. tracks.push( track );
  14474. }
  14475. clip.tracks = tracks;
  14476. // find minimum .times value across all tracks in the trimmed clip
  14477. let minStartTime = Infinity;
  14478. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14479. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14480. minStartTime = clip.tracks[ i ].times[ 0 ];
  14481. }
  14482. }
  14483. // shift all tracks such that clip begins at t=0
  14484. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14485. clip.tracks[ i ].shift( - 1 * minStartTime );
  14486. }
  14487. clip.resetDuration();
  14488. return clip;
  14489. }
  14490. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14491. if ( fps <= 0 ) fps = 30;
  14492. const numTracks = referenceClip.tracks.length;
  14493. const referenceTime = referenceFrame / fps;
  14494. // Make each track's values relative to the values at the reference frame
  14495. for ( let i = 0; i < numTracks; ++ i ) {
  14496. const referenceTrack = referenceClip.tracks[ i ];
  14497. const referenceTrackType = referenceTrack.ValueTypeName;
  14498. // Skip this track if it's non-numeric
  14499. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14500. // Find the track in the target clip whose name and type matches the reference track
  14501. const targetTrack = targetClip.tracks.find( function ( track ) {
  14502. return track.name === referenceTrack.name
  14503. && track.ValueTypeName === referenceTrackType;
  14504. } );
  14505. if ( targetTrack === undefined ) continue;
  14506. let referenceOffset = 0;
  14507. const referenceValueSize = referenceTrack.getValueSize();
  14508. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14509. referenceOffset = referenceValueSize / 3;
  14510. }
  14511. let targetOffset = 0;
  14512. const targetValueSize = targetTrack.getValueSize();
  14513. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14514. targetOffset = targetValueSize / 3;
  14515. }
  14516. const lastIndex = referenceTrack.times.length - 1;
  14517. let referenceValue;
  14518. // Find the value to subtract out of the track
  14519. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14520. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14521. const startIndex = referenceOffset;
  14522. const endIndex = referenceValueSize - referenceOffset;
  14523. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14524. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14525. // Reference frame is after the last keyframe, so just use the last keyframe
  14526. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14527. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14528. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14529. } else {
  14530. // Interpolate to the reference value
  14531. const interpolant = referenceTrack.createInterpolant();
  14532. const startIndex = referenceOffset;
  14533. const endIndex = referenceValueSize - referenceOffset;
  14534. interpolant.evaluate( referenceTime );
  14535. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14536. }
  14537. // Conjugate the quaternion
  14538. if ( referenceTrackType === 'quaternion' ) {
  14539. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14540. referenceQuat.toArray( referenceValue );
  14541. }
  14542. // Subtract the reference value from all of the track values
  14543. const numTimes = targetTrack.times.length;
  14544. for ( let j = 0; j < numTimes; ++ j ) {
  14545. const valueStart = j * targetValueSize + targetOffset;
  14546. if ( referenceTrackType === 'quaternion' ) {
  14547. // Multiply the conjugate for quaternion track types
  14548. Quaternion.multiplyQuaternionsFlat(
  14549. targetTrack.values,
  14550. valueStart,
  14551. referenceValue,
  14552. 0,
  14553. targetTrack.values,
  14554. valueStart
  14555. );
  14556. } else {
  14557. const valueEnd = targetValueSize - targetOffset * 2;
  14558. // Subtract each value for all other numeric track types
  14559. for ( let k = 0; k < valueEnd; ++ k ) {
  14560. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14561. }
  14562. }
  14563. }
  14564. }
  14565. targetClip.blendMode = AdditiveAnimationBlendMode;
  14566. return targetClip;
  14567. }
  14568. const AnimationUtils = {
  14569. convertArray: convertArray,
  14570. isTypedArray: isTypedArray,
  14571. getKeyframeOrder: getKeyframeOrder,
  14572. sortedArray: sortedArray,
  14573. flattenJSON: flattenJSON,
  14574. subclip: subclip,
  14575. makeClipAdditive: makeClipAdditive
  14576. };
  14577. /**
  14578. * Abstract base class of interpolants over parametric samples.
  14579. *
  14580. * The parameter domain is one dimensional, typically the time or a path
  14581. * along a curve defined by the data.
  14582. *
  14583. * The sample values can have any dimensionality and derived classes may
  14584. * apply special interpretations to the data.
  14585. *
  14586. * This class provides the interval seek in a Template Method, deferring
  14587. * the actual interpolation to derived classes.
  14588. *
  14589. * Time complexity is O(1) for linear access crossing at most two points
  14590. * and O(log N) for random access, where N is the number of positions.
  14591. *
  14592. * References:
  14593. *
  14594. * http://www.oodesign.com/template-method-pattern.html
  14595. *
  14596. */
  14597. class Interpolant {
  14598. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14599. this.parameterPositions = parameterPositions;
  14600. this._cachedIndex = 0;
  14601. this.resultBuffer = resultBuffer !== undefined ?
  14602. resultBuffer : new sampleValues.constructor( sampleSize );
  14603. this.sampleValues = sampleValues;
  14604. this.valueSize = sampleSize;
  14605. this.settings = null;
  14606. this.DefaultSettings_ = {};
  14607. }
  14608. evaluate( t ) {
  14609. const pp = this.parameterPositions;
  14610. let i1 = this._cachedIndex,
  14611. t1 = pp[ i1 ],
  14612. t0 = pp[ i1 - 1 ];
  14613. validate_interval: {
  14614. seek: {
  14615. let right;
  14616. linear_scan: {
  14617. //- See http://jsperf.com/comparison-to-undefined/3
  14618. //- slower code:
  14619. //-
  14620. //- if ( t >= t1 || t1 === undefined ) {
  14621. forward_scan: if ( ! ( t < t1 ) ) {
  14622. for ( let giveUpAt = i1 + 2; ; ) {
  14623. if ( t1 === undefined ) {
  14624. if ( t < t0 ) break forward_scan;
  14625. // after end
  14626. i1 = pp.length;
  14627. this._cachedIndex = i1;
  14628. return this.copySampleValue_( i1 - 1 );
  14629. }
  14630. if ( i1 === giveUpAt ) break; // this loop
  14631. t0 = t1;
  14632. t1 = pp[ ++ i1 ];
  14633. if ( t < t1 ) {
  14634. // we have arrived at the sought interval
  14635. break seek;
  14636. }
  14637. }
  14638. // prepare binary search on the right side of the index
  14639. right = pp.length;
  14640. break linear_scan;
  14641. }
  14642. //- slower code:
  14643. //- if ( t < t0 || t0 === undefined ) {
  14644. if ( ! ( t >= t0 ) ) {
  14645. // looping?
  14646. const t1global = pp[ 1 ];
  14647. if ( t < t1global ) {
  14648. i1 = 2; // + 1, using the scan for the details
  14649. t0 = t1global;
  14650. }
  14651. // linear reverse scan
  14652. for ( let giveUpAt = i1 - 2; ; ) {
  14653. if ( t0 === undefined ) {
  14654. // before start
  14655. this._cachedIndex = 0;
  14656. return this.copySampleValue_( 0 );
  14657. }
  14658. if ( i1 === giveUpAt ) break; // this loop
  14659. t1 = t0;
  14660. t0 = pp[ -- i1 - 1 ];
  14661. if ( t >= t0 ) {
  14662. // we have arrived at the sought interval
  14663. break seek;
  14664. }
  14665. }
  14666. // prepare binary search on the left side of the index
  14667. right = i1;
  14668. i1 = 0;
  14669. break linear_scan;
  14670. }
  14671. // the interval is valid
  14672. break validate_interval;
  14673. } // linear scan
  14674. // binary search
  14675. while ( i1 < right ) {
  14676. const mid = ( i1 + right ) >>> 1;
  14677. if ( t < pp[ mid ] ) {
  14678. right = mid;
  14679. } else {
  14680. i1 = mid + 1;
  14681. }
  14682. }
  14683. t1 = pp[ i1 ];
  14684. t0 = pp[ i1 - 1 ];
  14685. // check boundary cases, again
  14686. if ( t0 === undefined ) {
  14687. this._cachedIndex = 0;
  14688. return this.copySampleValue_( 0 );
  14689. }
  14690. if ( t1 === undefined ) {
  14691. i1 = pp.length;
  14692. this._cachedIndex = i1;
  14693. return this.copySampleValue_( i1 - 1 );
  14694. }
  14695. } // seek
  14696. this._cachedIndex = i1;
  14697. this.intervalChanged_( i1, t0, t1 );
  14698. } // validate_interval
  14699. return this.interpolate_( i1, t0, t, t1 );
  14700. }
  14701. getSettings_() {
  14702. return this.settings || this.DefaultSettings_;
  14703. }
  14704. copySampleValue_( index ) {
  14705. // copies a sample value to the result buffer
  14706. const result = this.resultBuffer,
  14707. values = this.sampleValues,
  14708. stride = this.valueSize,
  14709. offset = index * stride;
  14710. for ( let i = 0; i !== stride; ++ i ) {
  14711. result[ i ] = values[ offset + i ];
  14712. }
  14713. return result;
  14714. }
  14715. // Template methods for derived classes:
  14716. interpolate_( /* i1, t0, t, t1 */ ) {
  14717. throw new Error( 'call to abstract method' );
  14718. // implementations shall return this.resultBuffer
  14719. }
  14720. intervalChanged_( /* i1, t0, t1 */ ) {
  14721. // empty
  14722. }
  14723. }
  14724. /**
  14725. * Fast and simple cubic spline interpolant.
  14726. *
  14727. * It was derived from a Hermitian construction setting the first derivative
  14728. * at each sample position to the linear slope between neighboring positions
  14729. * over their parameter interval.
  14730. */
  14731. class CubicInterpolant extends Interpolant {
  14732. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14733. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14734. this._weightPrev = - 0;
  14735. this._offsetPrev = - 0;
  14736. this._weightNext = - 0;
  14737. this._offsetNext = - 0;
  14738. this.DefaultSettings_ = {
  14739. endingStart: ZeroCurvatureEnding,
  14740. endingEnd: ZeroCurvatureEnding
  14741. };
  14742. }
  14743. intervalChanged_( i1, t0, t1 ) {
  14744. const pp = this.parameterPositions;
  14745. let iPrev = i1 - 2,
  14746. iNext = i1 + 1,
  14747. tPrev = pp[ iPrev ],
  14748. tNext = pp[ iNext ];
  14749. if ( tPrev === undefined ) {
  14750. switch ( this.getSettings_().endingStart ) {
  14751. case ZeroSlopeEnding:
  14752. // f'(t0) = 0
  14753. iPrev = i1;
  14754. tPrev = 2 * t0 - t1;
  14755. break;
  14756. case WrapAroundEnding:
  14757. // use the other end of the curve
  14758. iPrev = pp.length - 2;
  14759. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14760. break;
  14761. default: // ZeroCurvatureEnding
  14762. // f''(t0) = 0 a.k.a. Natural Spline
  14763. iPrev = i1;
  14764. tPrev = t1;
  14765. }
  14766. }
  14767. if ( tNext === undefined ) {
  14768. switch ( this.getSettings_().endingEnd ) {
  14769. case ZeroSlopeEnding:
  14770. // f'(tN) = 0
  14771. iNext = i1;
  14772. tNext = 2 * t1 - t0;
  14773. break;
  14774. case WrapAroundEnding:
  14775. // use the other end of the curve
  14776. iNext = 1;
  14777. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14778. break;
  14779. default: // ZeroCurvatureEnding
  14780. // f''(tN) = 0, a.k.a. Natural Spline
  14781. iNext = i1 - 1;
  14782. tNext = t0;
  14783. }
  14784. }
  14785. const halfDt = ( t1 - t0 ) * 0.5,
  14786. stride = this.valueSize;
  14787. this._weightPrev = halfDt / ( t0 - tPrev );
  14788. this._weightNext = halfDt / ( tNext - t1 );
  14789. this._offsetPrev = iPrev * stride;
  14790. this._offsetNext = iNext * stride;
  14791. }
  14792. interpolate_( i1, t0, t, t1 ) {
  14793. const result = this.resultBuffer,
  14794. values = this.sampleValues,
  14795. stride = this.valueSize,
  14796. o1 = i1 * stride, o0 = o1 - stride,
  14797. oP = this._offsetPrev, oN = this._offsetNext,
  14798. wP = this._weightPrev, wN = this._weightNext,
  14799. p = ( t - t0 ) / ( t1 - t0 ),
  14800. pp = p * p,
  14801. ppp = pp * p;
  14802. // evaluate polynomials
  14803. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14804. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14805. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14806. const sN = wN * ppp - wN * pp;
  14807. // combine data linearly
  14808. for ( let i = 0; i !== stride; ++ i ) {
  14809. result[ i ] =
  14810. sP * values[ oP + i ] +
  14811. s0 * values[ o0 + i ] +
  14812. s1 * values[ o1 + i ] +
  14813. sN * values[ oN + i ];
  14814. }
  14815. return result;
  14816. }
  14817. }
  14818. class LinearInterpolant extends Interpolant {
  14819. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14820. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14821. }
  14822. interpolate_( i1, t0, t, t1 ) {
  14823. const result = this.resultBuffer,
  14824. values = this.sampleValues,
  14825. stride = this.valueSize,
  14826. offset1 = i1 * stride,
  14827. offset0 = offset1 - stride,
  14828. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14829. weight0 = 1 - weight1;
  14830. for ( let i = 0; i !== stride; ++ i ) {
  14831. result[ i ] =
  14832. values[ offset0 + i ] * weight0 +
  14833. values[ offset1 + i ] * weight1;
  14834. }
  14835. return result;
  14836. }
  14837. }
  14838. /**
  14839. *
  14840. * Interpolant that evaluates to the sample value at the position preceding
  14841. * the parameter.
  14842. */
  14843. class DiscreteInterpolant extends Interpolant {
  14844. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14845. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14846. }
  14847. interpolate_( i1 /*, t0, t, t1 */ ) {
  14848. return this.copySampleValue_( i1 - 1 );
  14849. }
  14850. }
  14851. class KeyframeTrack {
  14852. constructor( name, times, values, interpolation ) {
  14853. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14854. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14855. this.name = name;
  14856. this.times = convertArray( times, this.TimeBufferType );
  14857. this.values = convertArray( values, this.ValueBufferType );
  14858. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14859. }
  14860. // Serialization (in static context, because of constructor invocation
  14861. // and automatic invocation of .toJSON):
  14862. static toJSON( track ) {
  14863. const trackType = track.constructor;
  14864. let json;
  14865. // derived classes can define a static toJSON method
  14866. if ( trackType.toJSON !== this.toJSON ) {
  14867. json = trackType.toJSON( track );
  14868. } else {
  14869. // by default, we assume the data can be serialized as-is
  14870. json = {
  14871. 'name': track.name,
  14872. 'times': convertArray( track.times, Array ),
  14873. 'values': convertArray( track.values, Array )
  14874. };
  14875. const interpolation = track.getInterpolation();
  14876. if ( interpolation !== track.DefaultInterpolation ) {
  14877. json.interpolation = interpolation;
  14878. }
  14879. }
  14880. json.type = track.ValueTypeName; // mandatory
  14881. return json;
  14882. }
  14883. InterpolantFactoryMethodDiscrete( result ) {
  14884. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14885. }
  14886. InterpolantFactoryMethodLinear( result ) {
  14887. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14888. }
  14889. InterpolantFactoryMethodSmooth( result ) {
  14890. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14891. }
  14892. setInterpolation( interpolation ) {
  14893. let factoryMethod;
  14894. switch ( interpolation ) {
  14895. case InterpolateDiscrete:
  14896. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14897. break;
  14898. case InterpolateLinear:
  14899. factoryMethod = this.InterpolantFactoryMethodLinear;
  14900. break;
  14901. case InterpolateSmooth:
  14902. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14903. break;
  14904. }
  14905. if ( factoryMethod === undefined ) {
  14906. const message = 'unsupported interpolation for ' +
  14907. this.ValueTypeName + ' keyframe track named ' + this.name;
  14908. if ( this.createInterpolant === undefined ) {
  14909. // fall back to default, unless the default itself is messed up
  14910. if ( interpolation !== this.DefaultInterpolation ) {
  14911. this.setInterpolation( this.DefaultInterpolation );
  14912. } else {
  14913. throw new Error( message ); // fatal, in this case
  14914. }
  14915. }
  14916. console.warn( 'THREE.KeyframeTrack:', message );
  14917. return this;
  14918. }
  14919. this.createInterpolant = factoryMethod;
  14920. return this;
  14921. }
  14922. getInterpolation() {
  14923. switch ( this.createInterpolant ) {
  14924. case this.InterpolantFactoryMethodDiscrete:
  14925. return InterpolateDiscrete;
  14926. case this.InterpolantFactoryMethodLinear:
  14927. return InterpolateLinear;
  14928. case this.InterpolantFactoryMethodSmooth:
  14929. return InterpolateSmooth;
  14930. }
  14931. }
  14932. getValueSize() {
  14933. return this.values.length / this.times.length;
  14934. }
  14935. // move all keyframes either forwards or backwards in time
  14936. shift( timeOffset ) {
  14937. if ( timeOffset !== 0.0 ) {
  14938. const times = this.times;
  14939. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14940. times[ i ] += timeOffset;
  14941. }
  14942. }
  14943. return this;
  14944. }
  14945. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  14946. scale( timeScale ) {
  14947. if ( timeScale !== 1.0 ) {
  14948. const times = this.times;
  14949. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14950. times[ i ] *= timeScale;
  14951. }
  14952. }
  14953. return this;
  14954. }
  14955. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  14956. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  14957. trim( startTime, endTime ) {
  14958. const times = this.times,
  14959. nKeys = times.length;
  14960. let from = 0,
  14961. to = nKeys - 1;
  14962. while ( from !== nKeys && times[ from ] < startTime ) {
  14963. ++ from;
  14964. }
  14965. while ( to !== - 1 && times[ to ] > endTime ) {
  14966. -- to;
  14967. }
  14968. ++ to; // inclusive -> exclusive bound
  14969. if ( from !== 0 || to !== nKeys ) {
  14970. // empty tracks are forbidden, so keep at least one keyframe
  14971. if ( from >= to ) {
  14972. to = Math.max( to, 1 );
  14973. from = to - 1;
  14974. }
  14975. const stride = this.getValueSize();
  14976. this.times = times.slice( from, to );
  14977. this.values = this.values.slice( from * stride, to * stride );
  14978. }
  14979. return this;
  14980. }
  14981. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  14982. validate() {
  14983. let valid = true;
  14984. const valueSize = this.getValueSize();
  14985. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  14986. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  14987. valid = false;
  14988. }
  14989. const times = this.times,
  14990. values = this.values,
  14991. nKeys = times.length;
  14992. if ( nKeys === 0 ) {
  14993. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  14994. valid = false;
  14995. }
  14996. let prevTime = null;
  14997. for ( let i = 0; i !== nKeys; i ++ ) {
  14998. const currTime = times[ i ];
  14999. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15000. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15001. valid = false;
  15002. break;
  15003. }
  15004. if ( prevTime !== null && prevTime > currTime ) {
  15005. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15006. valid = false;
  15007. break;
  15008. }
  15009. prevTime = currTime;
  15010. }
  15011. if ( values !== undefined ) {
  15012. if ( isTypedArray( values ) ) {
  15013. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15014. const value = values[ i ];
  15015. if ( isNaN( value ) ) {
  15016. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15017. valid = false;
  15018. break;
  15019. }
  15020. }
  15021. }
  15022. }
  15023. return valid;
  15024. }
  15025. // removes equivalent sequential keys as common in morph target sequences
  15026. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15027. optimize() {
  15028. // times or values may be shared with other tracks, so overwriting is unsafe
  15029. const times = this.times.slice(),
  15030. values = this.values.slice(),
  15031. stride = this.getValueSize(),
  15032. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15033. lastIndex = times.length - 1;
  15034. let writeIndex = 1;
  15035. for ( let i = 1; i < lastIndex; ++ i ) {
  15036. let keep = false;
  15037. const time = times[ i ];
  15038. const timeNext = times[ i + 1 ];
  15039. // remove adjacent keyframes scheduled at the same time
  15040. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15041. if ( ! smoothInterpolation ) {
  15042. // remove unnecessary keyframes same as their neighbors
  15043. const offset = i * stride,
  15044. offsetP = offset - stride,
  15045. offsetN = offset + stride;
  15046. for ( let j = 0; j !== stride; ++ j ) {
  15047. const value = values[ offset + j ];
  15048. if ( value !== values[ offsetP + j ] ||
  15049. value !== values[ offsetN + j ] ) {
  15050. keep = true;
  15051. break;
  15052. }
  15053. }
  15054. } else {
  15055. keep = true;
  15056. }
  15057. }
  15058. // in-place compaction
  15059. if ( keep ) {
  15060. if ( i !== writeIndex ) {
  15061. times[ writeIndex ] = times[ i ];
  15062. const readOffset = i * stride,
  15063. writeOffset = writeIndex * stride;
  15064. for ( let j = 0; j !== stride; ++ j ) {
  15065. values[ writeOffset + j ] = values[ readOffset + j ];
  15066. }
  15067. }
  15068. ++ writeIndex;
  15069. }
  15070. }
  15071. // flush last keyframe (compaction looks ahead)
  15072. if ( lastIndex > 0 ) {
  15073. times[ writeIndex ] = times[ lastIndex ];
  15074. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15075. values[ writeOffset + j ] = values[ readOffset + j ];
  15076. }
  15077. ++ writeIndex;
  15078. }
  15079. if ( writeIndex !== times.length ) {
  15080. this.times = times.slice( 0, writeIndex );
  15081. this.values = values.slice( 0, writeIndex * stride );
  15082. } else {
  15083. this.times = times;
  15084. this.values = values;
  15085. }
  15086. return this;
  15087. }
  15088. clone() {
  15089. const times = this.times.slice();
  15090. const values = this.values.slice();
  15091. const TypedKeyframeTrack = this.constructor;
  15092. const track = new TypedKeyframeTrack( this.name, times, values );
  15093. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15094. track.createInterpolant = this.createInterpolant;
  15095. return track;
  15096. }
  15097. }
  15098. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15099. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15100. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15101. /**
  15102. * A Track of Boolean keyframe values.
  15103. */
  15104. class BooleanKeyframeTrack extends KeyframeTrack {
  15105. // No interpolation parameter because only InterpolateDiscrete is valid.
  15106. constructor( name, times, values ) {
  15107. super( name, times, values );
  15108. }
  15109. }
  15110. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15111. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15112. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15113. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15114. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15115. /**
  15116. * A Track of keyframe values that represent color.
  15117. */
  15118. class ColorKeyframeTrack extends KeyframeTrack {}
  15119. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15120. /**
  15121. * A Track of numeric keyframe values.
  15122. */
  15123. class NumberKeyframeTrack extends KeyframeTrack {}
  15124. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15125. /**
  15126. * Spherical linear unit quaternion interpolant.
  15127. */
  15128. class QuaternionLinearInterpolant extends Interpolant {
  15129. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15130. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15131. }
  15132. interpolate_( i1, t0, t, t1 ) {
  15133. const result = this.resultBuffer,
  15134. values = this.sampleValues,
  15135. stride = this.valueSize,
  15136. alpha = ( t - t0 ) / ( t1 - t0 );
  15137. let offset = i1 * stride;
  15138. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15139. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15140. }
  15141. return result;
  15142. }
  15143. }
  15144. /**
  15145. * A Track of quaternion keyframe values.
  15146. */
  15147. class QuaternionKeyframeTrack extends KeyframeTrack {
  15148. InterpolantFactoryMethodLinear( result ) {
  15149. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15150. }
  15151. }
  15152. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15153. // ValueBufferType is inherited
  15154. // DefaultInterpolation is inherited;
  15155. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15156. /**
  15157. * A Track that interpolates Strings
  15158. */
  15159. class StringKeyframeTrack extends KeyframeTrack {
  15160. // No interpolation parameter because only InterpolateDiscrete is valid.
  15161. constructor( name, times, values ) {
  15162. super( name, times, values );
  15163. }
  15164. }
  15165. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15166. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15167. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15168. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15169. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15170. /**
  15171. * A Track of vectored keyframe values.
  15172. */
  15173. class VectorKeyframeTrack extends KeyframeTrack {}
  15174. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15175. class AnimationClip {
  15176. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15177. this.name = name;
  15178. this.tracks = tracks;
  15179. this.duration = duration;
  15180. this.blendMode = blendMode;
  15181. this.uuid = generateUUID();
  15182. // this means it should figure out its duration by scanning the tracks
  15183. if ( this.duration < 0 ) {
  15184. this.resetDuration();
  15185. }
  15186. }
  15187. static parse( json ) {
  15188. const tracks = [],
  15189. jsonTracks = json.tracks,
  15190. frameTime = 1.0 / ( json.fps || 1.0 );
  15191. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15192. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15193. }
  15194. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15195. clip.uuid = json.uuid;
  15196. return clip;
  15197. }
  15198. static toJSON( clip ) {
  15199. const tracks = [],
  15200. clipTracks = clip.tracks;
  15201. const json = {
  15202. 'name': clip.name,
  15203. 'duration': clip.duration,
  15204. 'tracks': tracks,
  15205. 'uuid': clip.uuid,
  15206. 'blendMode': clip.blendMode
  15207. };
  15208. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15209. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15210. }
  15211. return json;
  15212. }
  15213. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15214. const numMorphTargets = morphTargetSequence.length;
  15215. const tracks = [];
  15216. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15217. let times = [];
  15218. let values = [];
  15219. times.push(
  15220. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15221. i,
  15222. ( i + 1 ) % numMorphTargets );
  15223. values.push( 0, 1, 0 );
  15224. const order = getKeyframeOrder( times );
  15225. times = sortedArray( times, 1, order );
  15226. values = sortedArray( values, 1, order );
  15227. // if there is a key at the first frame, duplicate it as the
  15228. // last frame as well for perfect loop.
  15229. if ( ! noLoop && times[ 0 ] === 0 ) {
  15230. times.push( numMorphTargets );
  15231. values.push( values[ 0 ] );
  15232. }
  15233. tracks.push(
  15234. new NumberKeyframeTrack(
  15235. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15236. times, values
  15237. ).scale( 1.0 / fps ) );
  15238. }
  15239. return new this( name, - 1, tracks );
  15240. }
  15241. static findByName( objectOrClipArray, name ) {
  15242. let clipArray = objectOrClipArray;
  15243. if ( ! Array.isArray( objectOrClipArray ) ) {
  15244. const o = objectOrClipArray;
  15245. clipArray = o.geometry && o.geometry.animations || o.animations;
  15246. }
  15247. for ( let i = 0; i < clipArray.length; i ++ ) {
  15248. if ( clipArray[ i ].name === name ) {
  15249. return clipArray[ i ];
  15250. }
  15251. }
  15252. return null;
  15253. }
  15254. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15255. const animationToMorphTargets = {};
  15256. // tested with https://regex101.com/ on trick sequences
  15257. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15258. const pattern = /^([\w-]*?)([\d]+)$/;
  15259. // sort morph target names into animation groups based
  15260. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15261. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15262. const morphTarget = morphTargets[ i ];
  15263. const parts = morphTarget.name.match( pattern );
  15264. if ( parts && parts.length > 1 ) {
  15265. const name = parts[ 1 ];
  15266. let animationMorphTargets = animationToMorphTargets[ name ];
  15267. if ( ! animationMorphTargets ) {
  15268. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15269. }
  15270. animationMorphTargets.push( morphTarget );
  15271. }
  15272. }
  15273. const clips = [];
  15274. for ( const name in animationToMorphTargets ) {
  15275. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15276. }
  15277. return clips;
  15278. }
  15279. // parse the animation.hierarchy format
  15280. static parseAnimation( animation, bones ) {
  15281. if ( ! animation ) {
  15282. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15283. return null;
  15284. }
  15285. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15286. // only return track if there are actually keys.
  15287. if ( animationKeys.length !== 0 ) {
  15288. const times = [];
  15289. const values = [];
  15290. flattenJSON( animationKeys, times, values, propertyName );
  15291. // empty keys are filtered out, so check again
  15292. if ( times.length !== 0 ) {
  15293. destTracks.push( new trackType( trackName, times, values ) );
  15294. }
  15295. }
  15296. };
  15297. const tracks = [];
  15298. const clipName = animation.name || 'default';
  15299. const fps = animation.fps || 30;
  15300. const blendMode = animation.blendMode;
  15301. // automatic length determination in AnimationClip.
  15302. let duration = animation.length || - 1;
  15303. const hierarchyTracks = animation.hierarchy || [];
  15304. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15305. const animationKeys = hierarchyTracks[ h ].keys;
  15306. // skip empty tracks
  15307. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15308. // process morph targets
  15309. if ( animationKeys[ 0 ].morphTargets ) {
  15310. // figure out all morph targets used in this track
  15311. const morphTargetNames = {};
  15312. let k;
  15313. for ( k = 0; k < animationKeys.length; k ++ ) {
  15314. if ( animationKeys[ k ].morphTargets ) {
  15315. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15316. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15317. }
  15318. }
  15319. }
  15320. // create a track for each morph target with all zero
  15321. // morphTargetInfluences except for the keys in which
  15322. // the morphTarget is named.
  15323. for ( const morphTargetName in morphTargetNames ) {
  15324. const times = [];
  15325. const values = [];
  15326. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15327. const animationKey = animationKeys[ k ];
  15328. times.push( animationKey.time );
  15329. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15330. }
  15331. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15332. }
  15333. duration = morphTargetNames.length * fps;
  15334. } else {
  15335. // ...assume skeletal animation
  15336. const boneName = '.bones[' + bones[ h ].name + ']';
  15337. addNonemptyTrack(
  15338. VectorKeyframeTrack, boneName + '.position',
  15339. animationKeys, 'pos', tracks );
  15340. addNonemptyTrack(
  15341. QuaternionKeyframeTrack, boneName + '.quaternion',
  15342. animationKeys, 'rot', tracks );
  15343. addNonemptyTrack(
  15344. VectorKeyframeTrack, boneName + '.scale',
  15345. animationKeys, 'scl', tracks );
  15346. }
  15347. }
  15348. if ( tracks.length === 0 ) {
  15349. return null;
  15350. }
  15351. const clip = new this( clipName, duration, tracks, blendMode );
  15352. return clip;
  15353. }
  15354. resetDuration() {
  15355. const tracks = this.tracks;
  15356. let duration = 0;
  15357. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15358. const track = this.tracks[ i ];
  15359. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15360. }
  15361. this.duration = duration;
  15362. return this;
  15363. }
  15364. trim() {
  15365. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15366. this.tracks[ i ].trim( 0, this.duration );
  15367. }
  15368. return this;
  15369. }
  15370. validate() {
  15371. let valid = true;
  15372. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15373. valid = valid && this.tracks[ i ].validate();
  15374. }
  15375. return valid;
  15376. }
  15377. optimize() {
  15378. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15379. this.tracks[ i ].optimize();
  15380. }
  15381. return this;
  15382. }
  15383. clone() {
  15384. const tracks = [];
  15385. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15386. tracks.push( this.tracks[ i ].clone() );
  15387. }
  15388. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15389. }
  15390. toJSON() {
  15391. return this.constructor.toJSON( this );
  15392. }
  15393. }
  15394. function getTrackTypeForValueTypeName( typeName ) {
  15395. switch ( typeName.toLowerCase() ) {
  15396. case 'scalar':
  15397. case 'double':
  15398. case 'float':
  15399. case 'number':
  15400. case 'integer':
  15401. return NumberKeyframeTrack;
  15402. case 'vector':
  15403. case 'vector2':
  15404. case 'vector3':
  15405. case 'vector4':
  15406. return VectorKeyframeTrack;
  15407. case 'color':
  15408. return ColorKeyframeTrack;
  15409. case 'quaternion':
  15410. return QuaternionKeyframeTrack;
  15411. case 'bool':
  15412. case 'boolean':
  15413. return BooleanKeyframeTrack;
  15414. case 'string':
  15415. return StringKeyframeTrack;
  15416. }
  15417. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15418. }
  15419. function parseKeyframeTrack( json ) {
  15420. if ( json.type === undefined ) {
  15421. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15422. }
  15423. const trackType = getTrackTypeForValueTypeName( json.type );
  15424. if ( json.times === undefined ) {
  15425. const times = [], values = [];
  15426. flattenJSON( json.keys, times, values, 'value' );
  15427. json.times = times;
  15428. json.values = values;
  15429. }
  15430. // derived classes can define a static parse method
  15431. if ( trackType.parse !== undefined ) {
  15432. return trackType.parse( json );
  15433. } else {
  15434. // by default, we assume a constructor compatible with the base
  15435. return new trackType( json.name, json.times, json.values, json.interpolation );
  15436. }
  15437. }
  15438. const Cache = {
  15439. enabled: false,
  15440. files: {},
  15441. add: function ( key, file ) {
  15442. if ( this.enabled === false ) return;
  15443. // console.log( 'THREE.Cache', 'Adding key:', key );
  15444. this.files[ key ] = file;
  15445. },
  15446. get: function ( key ) {
  15447. if ( this.enabled === false ) return;
  15448. // console.log( 'THREE.Cache', 'Checking key:', key );
  15449. return this.files[ key ];
  15450. },
  15451. remove: function ( key ) {
  15452. delete this.files[ key ];
  15453. },
  15454. clear: function () {
  15455. this.files = {};
  15456. }
  15457. };
  15458. class LoadingManager {
  15459. constructor( onLoad, onProgress, onError ) {
  15460. const scope = this;
  15461. let isLoading = false;
  15462. let itemsLoaded = 0;
  15463. let itemsTotal = 0;
  15464. let urlModifier = undefined;
  15465. const handlers = [];
  15466. // Refer to #5689 for the reason why we don't set .onStart
  15467. // in the constructor
  15468. this.onStart = undefined;
  15469. this.onLoad = onLoad;
  15470. this.onProgress = onProgress;
  15471. this.onError = onError;
  15472. this.itemStart = function ( url ) {
  15473. itemsTotal ++;
  15474. if ( isLoading === false ) {
  15475. if ( scope.onStart !== undefined ) {
  15476. scope.onStart( url, itemsLoaded, itemsTotal );
  15477. }
  15478. }
  15479. isLoading = true;
  15480. };
  15481. this.itemEnd = function ( url ) {
  15482. itemsLoaded ++;
  15483. if ( scope.onProgress !== undefined ) {
  15484. scope.onProgress( url, itemsLoaded, itemsTotal );
  15485. }
  15486. if ( itemsLoaded === itemsTotal ) {
  15487. isLoading = false;
  15488. if ( scope.onLoad !== undefined ) {
  15489. scope.onLoad();
  15490. }
  15491. }
  15492. };
  15493. this.itemError = function ( url ) {
  15494. if ( scope.onError !== undefined ) {
  15495. scope.onError( url );
  15496. }
  15497. };
  15498. this.resolveURL = function ( url ) {
  15499. if ( urlModifier ) {
  15500. return urlModifier( url );
  15501. }
  15502. return url;
  15503. };
  15504. this.setURLModifier = function ( transform ) {
  15505. urlModifier = transform;
  15506. return this;
  15507. };
  15508. this.addHandler = function ( regex, loader ) {
  15509. handlers.push( regex, loader );
  15510. return this;
  15511. };
  15512. this.removeHandler = function ( regex ) {
  15513. const index = handlers.indexOf( regex );
  15514. if ( index !== - 1 ) {
  15515. handlers.splice( index, 2 );
  15516. }
  15517. return this;
  15518. };
  15519. this.getHandler = function ( file ) {
  15520. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15521. const regex = handlers[ i ];
  15522. const loader = handlers[ i + 1 ];
  15523. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15524. if ( regex.test( file ) ) {
  15525. return loader;
  15526. }
  15527. }
  15528. return null;
  15529. };
  15530. }
  15531. }
  15532. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15533. class Loader {
  15534. constructor( manager ) {
  15535. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15536. this.crossOrigin = 'anonymous';
  15537. this.withCredentials = false;
  15538. this.path = '';
  15539. this.resourcePath = '';
  15540. this.requestHeader = {};
  15541. }
  15542. load( /* url, onLoad, onProgress, onError */ ) {}
  15543. loadAsync( url, onProgress ) {
  15544. const scope = this;
  15545. return new Promise( function ( resolve, reject ) {
  15546. scope.load( url, resolve, onProgress, reject );
  15547. } );
  15548. }
  15549. parse( /* data */ ) {}
  15550. setCrossOrigin( crossOrigin ) {
  15551. this.crossOrigin = crossOrigin;
  15552. return this;
  15553. }
  15554. setWithCredentials( value ) {
  15555. this.withCredentials = value;
  15556. return this;
  15557. }
  15558. setPath( path ) {
  15559. this.path = path;
  15560. return this;
  15561. }
  15562. setResourcePath( resourcePath ) {
  15563. this.resourcePath = resourcePath;
  15564. return this;
  15565. }
  15566. setRequestHeader( requestHeader ) {
  15567. this.requestHeader = requestHeader;
  15568. return this;
  15569. }
  15570. }
  15571. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15572. const loading = {};
  15573. class HttpError extends Error {
  15574. constructor( message, response ) {
  15575. super( message );
  15576. this.response = response;
  15577. }
  15578. }
  15579. class FileLoader extends Loader {
  15580. constructor( manager ) {
  15581. super( manager );
  15582. }
  15583. load( url, onLoad, onProgress, onError ) {
  15584. if ( url === undefined ) url = '';
  15585. if ( this.path !== undefined ) url = this.path + url;
  15586. url = this.manager.resolveURL( url );
  15587. const cached = Cache.get( url );
  15588. if ( cached !== undefined ) {
  15589. this.manager.itemStart( url );
  15590. setTimeout( () => {
  15591. if ( onLoad ) onLoad( cached );
  15592. this.manager.itemEnd( url );
  15593. }, 0 );
  15594. return cached;
  15595. }
  15596. // Check if request is duplicate
  15597. if ( loading[ url ] !== undefined ) {
  15598. loading[ url ].push( {
  15599. onLoad: onLoad,
  15600. onProgress: onProgress,
  15601. onError: onError
  15602. } );
  15603. return;
  15604. }
  15605. // Initialise array for duplicate requests
  15606. loading[ url ] = [];
  15607. loading[ url ].push( {
  15608. onLoad: onLoad,
  15609. onProgress: onProgress,
  15610. onError: onError,
  15611. } );
  15612. // create request
  15613. const req = new Request( url, {
  15614. headers: new Headers( this.requestHeader ),
  15615. credentials: this.withCredentials ? 'include' : 'same-origin',
  15616. // An abort controller could be added within a future PR
  15617. } );
  15618. // record states ( avoid data race )
  15619. const mimeType = this.mimeType;
  15620. const responseType = this.responseType;
  15621. // start the fetch
  15622. fetch( req )
  15623. .then( response => {
  15624. if ( response.status === 200 || response.status === 0 ) {
  15625. // Some browsers return HTTP Status 0 when using non-http protocol
  15626. // e.g. 'file://' or 'data://'. Handle as success.
  15627. if ( response.status === 0 ) {
  15628. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15629. }
  15630. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15631. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15632. return response;
  15633. }
  15634. const callbacks = loading[ url ];
  15635. const reader = response.body.getReader();
  15636. // Nginx needs X-File-Size check
  15637. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15638. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15639. const total = contentLength ? parseInt( contentLength ) : 0;
  15640. const lengthComputable = total !== 0;
  15641. let loaded = 0;
  15642. // periodically read data into the new stream tracking while download progress
  15643. const stream = new ReadableStream( {
  15644. start( controller ) {
  15645. readData();
  15646. function readData() {
  15647. reader.read().then( ( { done, value } ) => {
  15648. if ( done ) {
  15649. controller.close();
  15650. } else {
  15651. loaded += value.byteLength;
  15652. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15653. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15654. const callback = callbacks[ i ];
  15655. if ( callback.onProgress ) callback.onProgress( event );
  15656. }
  15657. controller.enqueue( value );
  15658. readData();
  15659. }
  15660. }, ( e ) => {
  15661. controller.error( e );
  15662. } );
  15663. }
  15664. }
  15665. } );
  15666. return new Response( stream );
  15667. } else {
  15668. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15669. }
  15670. } )
  15671. .then( response => {
  15672. switch ( responseType ) {
  15673. case 'arraybuffer':
  15674. return response.arrayBuffer();
  15675. case 'blob':
  15676. return response.blob();
  15677. case 'document':
  15678. return response.text()
  15679. .then( text => {
  15680. const parser = new DOMParser();
  15681. return parser.parseFromString( text, mimeType );
  15682. } );
  15683. case 'json':
  15684. return response.json();
  15685. default:
  15686. if ( mimeType === undefined ) {
  15687. return response.text();
  15688. } else {
  15689. // sniff encoding
  15690. const re = /charset="?([^;"\s]*)"?/i;
  15691. const exec = re.exec( mimeType );
  15692. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15693. const decoder = new TextDecoder( label );
  15694. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15695. }
  15696. }
  15697. } )
  15698. .then( data => {
  15699. // Add to cache only on HTTP success, so that we do not cache
  15700. // error response bodies as proper responses to requests.
  15701. Cache.add( url, data );
  15702. const callbacks = loading[ url ];
  15703. delete loading[ url ];
  15704. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15705. const callback = callbacks[ i ];
  15706. if ( callback.onLoad ) callback.onLoad( data );
  15707. }
  15708. } )
  15709. .catch( err => {
  15710. // Abort errors and other errors are handled the same
  15711. const callbacks = loading[ url ];
  15712. if ( callbacks === undefined ) {
  15713. // When onLoad was called and url was deleted in `loading`
  15714. this.manager.itemError( url );
  15715. throw err;
  15716. }
  15717. delete loading[ url ];
  15718. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15719. const callback = callbacks[ i ];
  15720. if ( callback.onError ) callback.onError( err );
  15721. }
  15722. this.manager.itemError( url );
  15723. } )
  15724. .finally( () => {
  15725. this.manager.itemEnd( url );
  15726. } );
  15727. this.manager.itemStart( url );
  15728. }
  15729. setResponseType( value ) {
  15730. this.responseType = value;
  15731. return this;
  15732. }
  15733. setMimeType( value ) {
  15734. this.mimeType = value;
  15735. return this;
  15736. }
  15737. }
  15738. class AnimationLoader extends Loader {
  15739. constructor( manager ) {
  15740. super( manager );
  15741. }
  15742. load( url, onLoad, onProgress, onError ) {
  15743. const scope = this;
  15744. const loader = new FileLoader( this.manager );
  15745. loader.setPath( this.path );
  15746. loader.setRequestHeader( this.requestHeader );
  15747. loader.setWithCredentials( this.withCredentials );
  15748. loader.load( url, function ( text ) {
  15749. try {
  15750. onLoad( scope.parse( JSON.parse( text ) ) );
  15751. } catch ( e ) {
  15752. if ( onError ) {
  15753. onError( e );
  15754. } else {
  15755. console.error( e );
  15756. }
  15757. scope.manager.itemError( url );
  15758. }
  15759. }, onProgress, onError );
  15760. }
  15761. parse( json ) {
  15762. const animations = [];
  15763. for ( let i = 0; i < json.length; i ++ ) {
  15764. const clip = AnimationClip.parse( json[ i ] );
  15765. animations.push( clip );
  15766. }
  15767. return animations;
  15768. }
  15769. }
  15770. /**
  15771. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15772. *
  15773. * Sub classes have to implement the parse() method which will be used in load().
  15774. */
  15775. class CompressedTextureLoader extends Loader {
  15776. constructor( manager ) {
  15777. super( manager );
  15778. }
  15779. load( url, onLoad, onProgress, onError ) {
  15780. const scope = this;
  15781. const images = [];
  15782. const texture = new CompressedTexture();
  15783. const loader = new FileLoader( this.manager );
  15784. loader.setPath( this.path );
  15785. loader.setResponseType( 'arraybuffer' );
  15786. loader.setRequestHeader( this.requestHeader );
  15787. loader.setWithCredentials( scope.withCredentials );
  15788. let loaded = 0;
  15789. function loadTexture( i ) {
  15790. loader.load( url[ i ], function ( buffer ) {
  15791. const texDatas = scope.parse( buffer, true );
  15792. images[ i ] = {
  15793. width: texDatas.width,
  15794. height: texDatas.height,
  15795. format: texDatas.format,
  15796. mipmaps: texDatas.mipmaps
  15797. };
  15798. loaded += 1;
  15799. if ( loaded === 6 ) {
  15800. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15801. texture.image = images;
  15802. texture.format = texDatas.format;
  15803. texture.needsUpdate = true;
  15804. if ( onLoad ) onLoad( texture );
  15805. }
  15806. }, onProgress, onError );
  15807. }
  15808. if ( Array.isArray( url ) ) {
  15809. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15810. loadTexture( i );
  15811. }
  15812. } else {
  15813. // compressed cubemap texture stored in a single DDS file
  15814. loader.load( url, function ( buffer ) {
  15815. const texDatas = scope.parse( buffer, true );
  15816. if ( texDatas.isCubemap ) {
  15817. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15818. for ( let f = 0; f < faces; f ++ ) {
  15819. images[ f ] = { mipmaps: [] };
  15820. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15821. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15822. images[ f ].format = texDatas.format;
  15823. images[ f ].width = texDatas.width;
  15824. images[ f ].height = texDatas.height;
  15825. }
  15826. }
  15827. texture.image = images;
  15828. } else {
  15829. texture.image.width = texDatas.width;
  15830. texture.image.height = texDatas.height;
  15831. texture.mipmaps = texDatas.mipmaps;
  15832. }
  15833. if ( texDatas.mipmapCount === 1 ) {
  15834. texture.minFilter = LinearFilter;
  15835. }
  15836. texture.format = texDatas.format;
  15837. texture.needsUpdate = true;
  15838. if ( onLoad ) onLoad( texture );
  15839. }, onProgress, onError );
  15840. }
  15841. return texture;
  15842. }
  15843. }
  15844. class ImageLoader extends Loader {
  15845. constructor( manager ) {
  15846. super( manager );
  15847. }
  15848. load( url, onLoad, onProgress, onError ) {
  15849. if ( this.path !== undefined ) url = this.path + url;
  15850. url = this.manager.resolveURL( url );
  15851. const scope = this;
  15852. const cached = Cache.get( url );
  15853. if ( cached !== undefined ) {
  15854. scope.manager.itemStart( url );
  15855. setTimeout( function () {
  15856. if ( onLoad ) onLoad( cached );
  15857. scope.manager.itemEnd( url );
  15858. }, 0 );
  15859. return cached;
  15860. }
  15861. const image = createElementNS( 'img' );
  15862. function onImageLoad() {
  15863. removeEventListeners();
  15864. Cache.add( url, this );
  15865. if ( onLoad ) onLoad( this );
  15866. scope.manager.itemEnd( url );
  15867. }
  15868. function onImageError( event ) {
  15869. removeEventListeners();
  15870. if ( onError ) onError( event );
  15871. scope.manager.itemError( url );
  15872. scope.manager.itemEnd( url );
  15873. }
  15874. function removeEventListeners() {
  15875. image.removeEventListener( 'load', onImageLoad, false );
  15876. image.removeEventListener( 'error', onImageError, false );
  15877. }
  15878. image.addEventListener( 'load', onImageLoad, false );
  15879. image.addEventListener( 'error', onImageError, false );
  15880. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15881. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15882. }
  15883. scope.manager.itemStart( url );
  15884. image.src = url;
  15885. return image;
  15886. }
  15887. }
  15888. class CubeTextureLoader extends Loader {
  15889. constructor( manager ) {
  15890. super( manager );
  15891. }
  15892. load( urls, onLoad, onProgress, onError ) {
  15893. const texture = new CubeTexture();
  15894. texture.colorSpace = SRGBColorSpace;
  15895. const loader = new ImageLoader( this.manager );
  15896. loader.setCrossOrigin( this.crossOrigin );
  15897. loader.setPath( this.path );
  15898. let loaded = 0;
  15899. function loadTexture( i ) {
  15900. loader.load( urls[ i ], function ( image ) {
  15901. texture.images[ i ] = image;
  15902. loaded ++;
  15903. if ( loaded === 6 ) {
  15904. texture.needsUpdate = true;
  15905. if ( onLoad ) onLoad( texture );
  15906. }
  15907. }, undefined, onError );
  15908. }
  15909. for ( let i = 0; i < urls.length; ++ i ) {
  15910. loadTexture( i );
  15911. }
  15912. return texture;
  15913. }
  15914. }
  15915. /**
  15916. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15917. *
  15918. * Sub classes have to implement the parse() method which will be used in load().
  15919. */
  15920. class DataTextureLoader extends Loader {
  15921. constructor( manager ) {
  15922. super( manager );
  15923. }
  15924. load( url, onLoad, onProgress, onError ) {
  15925. const scope = this;
  15926. const texture = new DataTexture();
  15927. const loader = new FileLoader( this.manager );
  15928. loader.setResponseType( 'arraybuffer' );
  15929. loader.setRequestHeader( this.requestHeader );
  15930. loader.setPath( this.path );
  15931. loader.setWithCredentials( scope.withCredentials );
  15932. loader.load( url, function ( buffer ) {
  15933. let texData;
  15934. try {
  15935. texData = scope.parse( buffer );
  15936. } catch ( error ) {
  15937. if ( onError !== undefined ) {
  15938. onError( error );
  15939. } else {
  15940. console.error( error );
  15941. return;
  15942. }
  15943. }
  15944. if ( texData.image !== undefined ) {
  15945. texture.image = texData.image;
  15946. } else if ( texData.data !== undefined ) {
  15947. texture.image.width = texData.width;
  15948. texture.image.height = texData.height;
  15949. texture.image.data = texData.data;
  15950. }
  15951. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  15952. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  15953. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  15954. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  15955. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  15956. if ( texData.colorSpace !== undefined ) {
  15957. texture.colorSpace = texData.colorSpace;
  15958. }
  15959. if ( texData.flipY !== undefined ) {
  15960. texture.flipY = texData.flipY;
  15961. }
  15962. if ( texData.format !== undefined ) {
  15963. texture.format = texData.format;
  15964. }
  15965. if ( texData.type !== undefined ) {
  15966. texture.type = texData.type;
  15967. }
  15968. if ( texData.mipmaps !== undefined ) {
  15969. texture.mipmaps = texData.mipmaps;
  15970. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  15971. }
  15972. if ( texData.mipmapCount === 1 ) {
  15973. texture.minFilter = LinearFilter;
  15974. }
  15975. if ( texData.generateMipmaps !== undefined ) {
  15976. texture.generateMipmaps = texData.generateMipmaps;
  15977. }
  15978. texture.needsUpdate = true;
  15979. if ( onLoad ) onLoad( texture, texData );
  15980. }, onProgress, onError );
  15981. return texture;
  15982. }
  15983. }
  15984. class TextureLoader extends Loader {
  15985. constructor( manager ) {
  15986. super( manager );
  15987. }
  15988. load( url, onLoad, onProgress, onError ) {
  15989. const texture = new Texture();
  15990. const loader = new ImageLoader( this.manager );
  15991. loader.setCrossOrigin( this.crossOrigin );
  15992. loader.setPath( this.path );
  15993. loader.load( url, function ( image ) {
  15994. texture.image = image;
  15995. texture.needsUpdate = true;
  15996. if ( onLoad !== undefined ) {
  15997. onLoad( texture );
  15998. }
  15999. }, onProgress, onError );
  16000. return texture;
  16001. }
  16002. }
  16003. class Light extends Object3D {
  16004. constructor( color, intensity = 1 ) {
  16005. super();
  16006. this.isLight = true;
  16007. this.type = 'Light';
  16008. this.color = new Color( color );
  16009. this.intensity = intensity;
  16010. }
  16011. dispose() {
  16012. // Empty here in base class; some subclasses override.
  16013. }
  16014. copy( source, recursive ) {
  16015. super.copy( source, recursive );
  16016. this.color.copy( source.color );
  16017. this.intensity = source.intensity;
  16018. return this;
  16019. }
  16020. toJSON( meta ) {
  16021. const data = super.toJSON( meta );
  16022. data.object.color = this.color.getHex();
  16023. data.object.intensity = this.intensity;
  16024. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16025. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16026. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16027. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16028. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16029. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16030. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16031. return data;
  16032. }
  16033. }
  16034. class HemisphereLight extends Light {
  16035. constructor( skyColor, groundColor, intensity ) {
  16036. super( skyColor, intensity );
  16037. this.isHemisphereLight = true;
  16038. this.type = 'HemisphereLight';
  16039. this.position.copy( Object3D.DEFAULT_UP );
  16040. this.updateMatrix();
  16041. this.groundColor = new Color( groundColor );
  16042. }
  16043. copy( source, recursive ) {
  16044. super.copy( source, recursive );
  16045. this.groundColor.copy( source.groundColor );
  16046. return this;
  16047. }
  16048. }
  16049. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16050. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16051. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16052. class LightShadow {
  16053. constructor( camera ) {
  16054. this.camera = camera;
  16055. this.intensity = 1;
  16056. this.bias = 0;
  16057. this.normalBias = 0;
  16058. this.radius = 1;
  16059. this.blurSamples = 8;
  16060. this.mapSize = new Vector2( 512, 512 );
  16061. this.map = null;
  16062. this.mapPass = null;
  16063. this.matrix = new Matrix4();
  16064. this.autoUpdate = true;
  16065. this.needsUpdate = false;
  16066. this._frustum = new Frustum();
  16067. this._frameExtents = new Vector2( 1, 1 );
  16068. this._viewportCount = 1;
  16069. this._viewports = [
  16070. new Vector4( 0, 0, 1, 1 )
  16071. ];
  16072. }
  16073. getViewportCount() {
  16074. return this._viewportCount;
  16075. }
  16076. getFrustum() {
  16077. return this._frustum;
  16078. }
  16079. updateMatrices( light ) {
  16080. const shadowCamera = this.camera;
  16081. const shadowMatrix = this.matrix;
  16082. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16083. shadowCamera.position.copy( _lightPositionWorld$1 );
  16084. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16085. shadowCamera.lookAt( _lookTarget$1 );
  16086. shadowCamera.updateMatrixWorld();
  16087. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16088. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16089. shadowMatrix.set(
  16090. 0.5, 0.0, 0.0, 0.5,
  16091. 0.0, 0.5, 0.0, 0.5,
  16092. 0.0, 0.0, 0.5, 0.5,
  16093. 0.0, 0.0, 0.0, 1.0
  16094. );
  16095. shadowMatrix.multiply( _projScreenMatrix$2 );
  16096. }
  16097. getViewport( viewportIndex ) {
  16098. return this._viewports[ viewportIndex ];
  16099. }
  16100. getFrameExtents() {
  16101. return this._frameExtents;
  16102. }
  16103. dispose() {
  16104. if ( this.map ) {
  16105. this.map.dispose();
  16106. }
  16107. if ( this.mapPass ) {
  16108. this.mapPass.dispose();
  16109. }
  16110. }
  16111. copy( source ) {
  16112. this.camera = source.camera.clone();
  16113. this.intensity = source.intensity;
  16114. this.bias = source.bias;
  16115. this.radius = source.radius;
  16116. this.mapSize.copy( source.mapSize );
  16117. return this;
  16118. }
  16119. clone() {
  16120. return new this.constructor().copy( this );
  16121. }
  16122. toJSON() {
  16123. const object = {};
  16124. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16125. if ( this.bias !== 0 ) object.bias = this.bias;
  16126. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16127. if ( this.radius !== 1 ) object.radius = this.radius;
  16128. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16129. object.camera = this.camera.toJSON( false ).object;
  16130. delete object.camera.matrix;
  16131. return object;
  16132. }
  16133. }
  16134. class SpotLightShadow extends LightShadow {
  16135. constructor() {
  16136. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16137. this.isSpotLightShadow = true;
  16138. this.focus = 1;
  16139. }
  16140. updateMatrices( light ) {
  16141. const camera = this.camera;
  16142. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16143. const aspect = this.mapSize.width / this.mapSize.height;
  16144. const far = light.distance || camera.far;
  16145. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16146. camera.fov = fov;
  16147. camera.aspect = aspect;
  16148. camera.far = far;
  16149. camera.updateProjectionMatrix();
  16150. }
  16151. super.updateMatrices( light );
  16152. }
  16153. copy( source ) {
  16154. super.copy( source );
  16155. this.focus = source.focus;
  16156. return this;
  16157. }
  16158. }
  16159. class SpotLight extends Light {
  16160. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16161. super( color, intensity );
  16162. this.isSpotLight = true;
  16163. this.type = 'SpotLight';
  16164. this.position.copy( Object3D.DEFAULT_UP );
  16165. this.updateMatrix();
  16166. this.target = new Object3D();
  16167. this.distance = distance;
  16168. this.angle = angle;
  16169. this.penumbra = penumbra;
  16170. this.decay = decay;
  16171. this.map = null;
  16172. this.shadow = new SpotLightShadow();
  16173. }
  16174. get power() {
  16175. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16176. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16177. return this.intensity * Math.PI;
  16178. }
  16179. set power( power ) {
  16180. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16181. this.intensity = power / Math.PI;
  16182. }
  16183. dispose() {
  16184. this.shadow.dispose();
  16185. }
  16186. copy( source, recursive ) {
  16187. super.copy( source, recursive );
  16188. this.distance = source.distance;
  16189. this.angle = source.angle;
  16190. this.penumbra = source.penumbra;
  16191. this.decay = source.decay;
  16192. this.target = source.target.clone();
  16193. this.shadow = source.shadow.clone();
  16194. return this;
  16195. }
  16196. }
  16197. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16198. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16199. const _lookTarget = /*@__PURE__*/ new Vector3();
  16200. class PointLightShadow extends LightShadow {
  16201. constructor() {
  16202. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16203. this.isPointLightShadow = true;
  16204. this._frameExtents = new Vector2( 4, 2 );
  16205. this._viewportCount = 6;
  16206. this._viewports = [
  16207. // These viewports map a cube-map onto a 2D texture with the
  16208. // following orientation:
  16209. //
  16210. // xzXZ
  16211. // y Y
  16212. //
  16213. // X - Positive x direction
  16214. // x - Negative x direction
  16215. // Y - Positive y direction
  16216. // y - Negative y direction
  16217. // Z - Positive z direction
  16218. // z - Negative z direction
  16219. // positive X
  16220. new Vector4( 2, 1, 1, 1 ),
  16221. // negative X
  16222. new Vector4( 0, 1, 1, 1 ),
  16223. // positive Z
  16224. new Vector4( 3, 1, 1, 1 ),
  16225. // negative Z
  16226. new Vector4( 1, 1, 1, 1 ),
  16227. // positive Y
  16228. new Vector4( 3, 0, 1, 1 ),
  16229. // negative Y
  16230. new Vector4( 1, 0, 1, 1 )
  16231. ];
  16232. this._cubeDirections = [
  16233. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16234. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16235. ];
  16236. this._cubeUps = [
  16237. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16238. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16239. ];
  16240. }
  16241. updateMatrices( light, viewportIndex = 0 ) {
  16242. const camera = this.camera;
  16243. const shadowMatrix = this.matrix;
  16244. const far = light.distance || camera.far;
  16245. if ( far !== camera.far ) {
  16246. camera.far = far;
  16247. camera.updateProjectionMatrix();
  16248. }
  16249. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16250. camera.position.copy( _lightPositionWorld );
  16251. _lookTarget.copy( camera.position );
  16252. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16253. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16254. camera.lookAt( _lookTarget );
  16255. camera.updateMatrixWorld();
  16256. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16257. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16258. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16259. }
  16260. }
  16261. class PointLight extends Light {
  16262. constructor( color, intensity, distance = 0, decay = 2 ) {
  16263. super( color, intensity );
  16264. this.isPointLight = true;
  16265. this.type = 'PointLight';
  16266. this.distance = distance;
  16267. this.decay = decay;
  16268. this.shadow = new PointLightShadow();
  16269. }
  16270. get power() {
  16271. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16272. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16273. return this.intensity * 4 * Math.PI;
  16274. }
  16275. set power( power ) {
  16276. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16277. this.intensity = power / ( 4 * Math.PI );
  16278. }
  16279. dispose() {
  16280. this.shadow.dispose();
  16281. }
  16282. copy( source, recursive ) {
  16283. super.copy( source, recursive );
  16284. this.distance = source.distance;
  16285. this.decay = source.decay;
  16286. this.shadow = source.shadow.clone();
  16287. return this;
  16288. }
  16289. }
  16290. class OrthographicCamera extends Camera {
  16291. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16292. super();
  16293. this.isOrthographicCamera = true;
  16294. this.type = 'OrthographicCamera';
  16295. this.zoom = 1;
  16296. this.view = null;
  16297. this.left = left;
  16298. this.right = right;
  16299. this.top = top;
  16300. this.bottom = bottom;
  16301. this.near = near;
  16302. this.far = far;
  16303. this.updateProjectionMatrix();
  16304. }
  16305. copy( source, recursive ) {
  16306. super.copy( source, recursive );
  16307. this.left = source.left;
  16308. this.right = source.right;
  16309. this.top = source.top;
  16310. this.bottom = source.bottom;
  16311. this.near = source.near;
  16312. this.far = source.far;
  16313. this.zoom = source.zoom;
  16314. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16315. return this;
  16316. }
  16317. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16318. if ( this.view === null ) {
  16319. this.view = {
  16320. enabled: true,
  16321. fullWidth: 1,
  16322. fullHeight: 1,
  16323. offsetX: 0,
  16324. offsetY: 0,
  16325. width: 1,
  16326. height: 1
  16327. };
  16328. }
  16329. this.view.enabled = true;
  16330. this.view.fullWidth = fullWidth;
  16331. this.view.fullHeight = fullHeight;
  16332. this.view.offsetX = x;
  16333. this.view.offsetY = y;
  16334. this.view.width = width;
  16335. this.view.height = height;
  16336. this.updateProjectionMatrix();
  16337. }
  16338. clearViewOffset() {
  16339. if ( this.view !== null ) {
  16340. this.view.enabled = false;
  16341. }
  16342. this.updateProjectionMatrix();
  16343. }
  16344. updateProjectionMatrix() {
  16345. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16346. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16347. const cx = ( this.right + this.left ) / 2;
  16348. const cy = ( this.top + this.bottom ) / 2;
  16349. let left = cx - dx;
  16350. let right = cx + dx;
  16351. let top = cy + dy;
  16352. let bottom = cy - dy;
  16353. if ( this.view !== null && this.view.enabled ) {
  16354. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16355. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16356. left += scaleW * this.view.offsetX;
  16357. right = left + scaleW * this.view.width;
  16358. top -= scaleH * this.view.offsetY;
  16359. bottom = top - scaleH * this.view.height;
  16360. }
  16361. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16362. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16363. }
  16364. toJSON( meta ) {
  16365. const data = super.toJSON( meta );
  16366. data.object.zoom = this.zoom;
  16367. data.object.left = this.left;
  16368. data.object.right = this.right;
  16369. data.object.top = this.top;
  16370. data.object.bottom = this.bottom;
  16371. data.object.near = this.near;
  16372. data.object.far = this.far;
  16373. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16374. return data;
  16375. }
  16376. }
  16377. class DirectionalLightShadow extends LightShadow {
  16378. constructor() {
  16379. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16380. this.isDirectionalLightShadow = true;
  16381. }
  16382. }
  16383. class DirectionalLight extends Light {
  16384. constructor( color, intensity ) {
  16385. super( color, intensity );
  16386. this.isDirectionalLight = true;
  16387. this.type = 'DirectionalLight';
  16388. this.position.copy( Object3D.DEFAULT_UP );
  16389. this.updateMatrix();
  16390. this.target = new Object3D();
  16391. this.shadow = new DirectionalLightShadow();
  16392. }
  16393. dispose() {
  16394. this.shadow.dispose();
  16395. }
  16396. copy( source ) {
  16397. super.copy( source );
  16398. this.target = source.target.clone();
  16399. this.shadow = source.shadow.clone();
  16400. return this;
  16401. }
  16402. }
  16403. class AmbientLight extends Light {
  16404. constructor( color, intensity ) {
  16405. super( color, intensity );
  16406. this.isAmbientLight = true;
  16407. this.type = 'AmbientLight';
  16408. }
  16409. }
  16410. class RectAreaLight extends Light {
  16411. constructor( color, intensity, width = 10, height = 10 ) {
  16412. super( color, intensity );
  16413. this.isRectAreaLight = true;
  16414. this.type = 'RectAreaLight';
  16415. this.width = width;
  16416. this.height = height;
  16417. }
  16418. get power() {
  16419. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16420. return this.intensity * this.width * this.height * Math.PI;
  16421. }
  16422. set power( power ) {
  16423. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16424. this.intensity = power / ( this.width * this.height * Math.PI );
  16425. }
  16426. copy( source ) {
  16427. super.copy( source );
  16428. this.width = source.width;
  16429. this.height = source.height;
  16430. return this;
  16431. }
  16432. toJSON( meta ) {
  16433. const data = super.toJSON( meta );
  16434. data.object.width = this.width;
  16435. data.object.height = this.height;
  16436. return data;
  16437. }
  16438. }
  16439. /**
  16440. * Primary reference:
  16441. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16442. *
  16443. * Secondary reference:
  16444. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16445. */
  16446. // 3-band SH defined by 9 coefficients
  16447. class SphericalHarmonics3 {
  16448. constructor() {
  16449. this.isSphericalHarmonics3 = true;
  16450. this.coefficients = [];
  16451. for ( let i = 0; i < 9; i ++ ) {
  16452. this.coefficients.push( new Vector3() );
  16453. }
  16454. }
  16455. set( coefficients ) {
  16456. for ( let i = 0; i < 9; i ++ ) {
  16457. this.coefficients[ i ].copy( coefficients[ i ] );
  16458. }
  16459. return this;
  16460. }
  16461. zero() {
  16462. for ( let i = 0; i < 9; i ++ ) {
  16463. this.coefficients[ i ].set( 0, 0, 0 );
  16464. }
  16465. return this;
  16466. }
  16467. // get the radiance in the direction of the normal
  16468. // target is a Vector3
  16469. getAt( normal, target ) {
  16470. // normal is assumed to be unit length
  16471. const x = normal.x, y = normal.y, z = normal.z;
  16472. const coeff = this.coefficients;
  16473. // band 0
  16474. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16475. // band 1
  16476. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16477. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16478. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16479. // band 2
  16480. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16481. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16482. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16483. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16484. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16485. return target;
  16486. }
  16487. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16488. // target is a Vector3
  16489. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16490. getIrradianceAt( normal, target ) {
  16491. // normal is assumed to be unit length
  16492. const x = normal.x, y = normal.y, z = normal.z;
  16493. const coeff = this.coefficients;
  16494. // band 0
  16495. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16496. // band 1
  16497. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16498. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16499. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16500. // band 2
  16501. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16502. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16503. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16504. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16505. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16506. return target;
  16507. }
  16508. add( sh ) {
  16509. for ( let i = 0; i < 9; i ++ ) {
  16510. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16511. }
  16512. return this;
  16513. }
  16514. addScaledSH( sh, s ) {
  16515. for ( let i = 0; i < 9; i ++ ) {
  16516. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16517. }
  16518. return this;
  16519. }
  16520. scale( s ) {
  16521. for ( let i = 0; i < 9; i ++ ) {
  16522. this.coefficients[ i ].multiplyScalar( s );
  16523. }
  16524. return this;
  16525. }
  16526. lerp( sh, alpha ) {
  16527. for ( let i = 0; i < 9; i ++ ) {
  16528. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16529. }
  16530. return this;
  16531. }
  16532. equals( sh ) {
  16533. for ( let i = 0; i < 9; i ++ ) {
  16534. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16535. return false;
  16536. }
  16537. }
  16538. return true;
  16539. }
  16540. copy( sh ) {
  16541. return this.set( sh.coefficients );
  16542. }
  16543. clone() {
  16544. return new this.constructor().copy( this );
  16545. }
  16546. fromArray( array, offset = 0 ) {
  16547. const coefficients = this.coefficients;
  16548. for ( let i = 0; i < 9; i ++ ) {
  16549. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16550. }
  16551. return this;
  16552. }
  16553. toArray( array = [], offset = 0 ) {
  16554. const coefficients = this.coefficients;
  16555. for ( let i = 0; i < 9; i ++ ) {
  16556. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16557. }
  16558. return array;
  16559. }
  16560. // evaluate the basis functions
  16561. // shBasis is an Array[ 9 ]
  16562. static getBasisAt( normal, shBasis ) {
  16563. // normal is assumed to be unit length
  16564. const x = normal.x, y = normal.y, z = normal.z;
  16565. // band 0
  16566. shBasis[ 0 ] = 0.282095;
  16567. // band 1
  16568. shBasis[ 1 ] = 0.488603 * y;
  16569. shBasis[ 2 ] = 0.488603 * z;
  16570. shBasis[ 3 ] = 0.488603 * x;
  16571. // band 2
  16572. shBasis[ 4 ] = 1.092548 * x * y;
  16573. shBasis[ 5 ] = 1.092548 * y * z;
  16574. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16575. shBasis[ 7 ] = 1.092548 * x * z;
  16576. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16577. }
  16578. }
  16579. class LightProbe extends Light {
  16580. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16581. super( undefined, intensity );
  16582. this.isLightProbe = true;
  16583. this.sh = sh;
  16584. }
  16585. copy( source ) {
  16586. super.copy( source );
  16587. this.sh.copy( source.sh );
  16588. return this;
  16589. }
  16590. fromJSON( json ) {
  16591. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16592. this.sh.fromArray( json.sh );
  16593. return this;
  16594. }
  16595. toJSON( meta ) {
  16596. const data = super.toJSON( meta );
  16597. data.object.sh = this.sh.toArray();
  16598. return data;
  16599. }
  16600. }
  16601. class MaterialLoader extends Loader {
  16602. constructor( manager ) {
  16603. super( manager );
  16604. this.textures = {};
  16605. }
  16606. load( url, onLoad, onProgress, onError ) {
  16607. const scope = this;
  16608. const loader = new FileLoader( scope.manager );
  16609. loader.setPath( scope.path );
  16610. loader.setRequestHeader( scope.requestHeader );
  16611. loader.setWithCredentials( scope.withCredentials );
  16612. loader.load( url, function ( text ) {
  16613. try {
  16614. onLoad( scope.parse( JSON.parse( text ) ) );
  16615. } catch ( e ) {
  16616. if ( onError ) {
  16617. onError( e );
  16618. } else {
  16619. console.error( e );
  16620. }
  16621. scope.manager.itemError( url );
  16622. }
  16623. }, onProgress, onError );
  16624. }
  16625. parse( json ) {
  16626. const textures = this.textures;
  16627. function getTexture( name ) {
  16628. if ( textures[ name ] === undefined ) {
  16629. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16630. }
  16631. return textures[ name ];
  16632. }
  16633. const material = this.createMaterialFromType( json.type );
  16634. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16635. if ( json.name !== undefined ) material.name = json.name;
  16636. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16637. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16638. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16639. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16640. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16641. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16642. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16643. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16644. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16645. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16646. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16647. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16648. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16649. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16650. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16651. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16652. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16653. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16654. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16655. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16656. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16657. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16658. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16659. if ( json.fog !== undefined ) material.fog = json.fog;
  16660. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16661. if ( json.blending !== undefined ) material.blending = json.blending;
  16662. if ( json.combine !== undefined ) material.combine = json.combine;
  16663. if ( json.side !== undefined ) material.side = json.side;
  16664. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16665. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16666. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16667. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16668. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16669. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16670. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16671. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16672. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16673. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16674. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16675. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16676. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16677. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16678. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16679. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16680. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16681. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16682. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16683. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16684. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16685. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16686. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16687. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16688. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16689. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16690. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16691. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16692. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16693. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16694. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16695. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16696. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16697. if ( json.scale !== undefined ) material.scale = json.scale;
  16698. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16699. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16700. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16701. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16702. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16703. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16704. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16705. if ( json.visible !== undefined ) material.visible = json.visible;
  16706. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16707. if ( json.userData !== undefined ) material.userData = json.userData;
  16708. if ( json.vertexColors !== undefined ) {
  16709. if ( typeof json.vertexColors === 'number' ) {
  16710. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16711. } else {
  16712. material.vertexColors = json.vertexColors;
  16713. }
  16714. }
  16715. // Shader Material
  16716. if ( json.uniforms !== undefined ) {
  16717. for ( const name in json.uniforms ) {
  16718. const uniform = json.uniforms[ name ];
  16719. material.uniforms[ name ] = {};
  16720. switch ( uniform.type ) {
  16721. case 't':
  16722. material.uniforms[ name ].value = getTexture( uniform.value );
  16723. break;
  16724. case 'c':
  16725. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16726. break;
  16727. case 'v2':
  16728. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16729. break;
  16730. case 'v3':
  16731. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16732. break;
  16733. case 'v4':
  16734. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16735. break;
  16736. case 'm3':
  16737. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16738. break;
  16739. case 'm4':
  16740. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16741. break;
  16742. default:
  16743. material.uniforms[ name ].value = uniform.value;
  16744. }
  16745. }
  16746. }
  16747. if ( json.defines !== undefined ) material.defines = json.defines;
  16748. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16749. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16750. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16751. if ( json.extensions !== undefined ) {
  16752. for ( const key in json.extensions ) {
  16753. material.extensions[ key ] = json.extensions[ key ];
  16754. }
  16755. }
  16756. if ( json.lights !== undefined ) material.lights = json.lights;
  16757. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16758. // for PointsMaterial
  16759. if ( json.size !== undefined ) material.size = json.size;
  16760. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16761. // maps
  16762. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16763. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16764. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16765. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16766. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16767. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16768. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16769. if ( json.normalScale !== undefined ) {
  16770. let normalScale = json.normalScale;
  16771. if ( Array.isArray( normalScale ) === false ) {
  16772. // Blender exporter used to export a scalar. See #7459
  16773. normalScale = [ normalScale, normalScale ];
  16774. }
  16775. material.normalScale = new Vector2().fromArray( normalScale );
  16776. }
  16777. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16778. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16779. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16780. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16781. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16782. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16783. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16784. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16785. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16786. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16787. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16788. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16789. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16790. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16791. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16792. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16793. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16794. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16795. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16796. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16797. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16798. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16799. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16800. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16801. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16802. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16803. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16804. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16805. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16806. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16807. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16808. return material;
  16809. }
  16810. setTextures( value ) {
  16811. this.textures = value;
  16812. return this;
  16813. }
  16814. createMaterialFromType( type ) {
  16815. return MaterialLoader.createMaterialFromType( type );
  16816. }
  16817. static createMaterialFromType( type ) {
  16818. const materialLib = {
  16819. ShadowMaterial,
  16820. SpriteMaterial,
  16821. RawShaderMaterial,
  16822. ShaderMaterial,
  16823. PointsMaterial,
  16824. MeshPhysicalMaterial,
  16825. MeshStandardMaterial,
  16826. MeshPhongMaterial,
  16827. MeshToonMaterial,
  16828. MeshNormalMaterial,
  16829. MeshLambertMaterial,
  16830. MeshDepthMaterial,
  16831. MeshDistanceMaterial,
  16832. MeshBasicMaterial,
  16833. MeshMatcapMaterial,
  16834. LineDashedMaterial,
  16835. LineBasicMaterial,
  16836. Material
  16837. };
  16838. return new materialLib[ type ]();
  16839. }
  16840. }
  16841. class LoaderUtils {
  16842. static decodeText( array ) { // @deprecated, r165
  16843. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16844. if ( typeof TextDecoder !== 'undefined' ) {
  16845. return new TextDecoder().decode( array );
  16846. }
  16847. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16848. // throws a "maximum call stack size exceeded" error for large arrays.
  16849. let s = '';
  16850. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16851. // Implicitly assumes little-endian.
  16852. s += String.fromCharCode( array[ i ] );
  16853. }
  16854. try {
  16855. // merges multi-byte utf-8 characters.
  16856. return decodeURIComponent( escape( s ) );
  16857. } catch ( e ) { // see #16358
  16858. return s;
  16859. }
  16860. }
  16861. static extractUrlBase( url ) {
  16862. const index = url.lastIndexOf( '/' );
  16863. if ( index === - 1 ) return './';
  16864. return url.slice( 0, index + 1 );
  16865. }
  16866. static resolveURL( url, path ) {
  16867. // Invalid URL
  16868. if ( typeof url !== 'string' || url === '' ) return '';
  16869. // Host Relative URL
  16870. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16871. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16872. }
  16873. // Absolute URL http://,https://,//
  16874. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16875. // Data URI
  16876. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16877. // Blob URL
  16878. if ( /^blob:.*$/i.test( url ) ) return url;
  16879. // Relative URL
  16880. return path + url;
  16881. }
  16882. }
  16883. class InstancedBufferGeometry extends BufferGeometry {
  16884. constructor() {
  16885. super();
  16886. this.isInstancedBufferGeometry = true;
  16887. this.type = 'InstancedBufferGeometry';
  16888. this.instanceCount = Infinity;
  16889. }
  16890. copy( source ) {
  16891. super.copy( source );
  16892. this.instanceCount = source.instanceCount;
  16893. return this;
  16894. }
  16895. toJSON() {
  16896. const data = super.toJSON();
  16897. data.instanceCount = this.instanceCount;
  16898. data.isInstancedBufferGeometry = true;
  16899. return data;
  16900. }
  16901. }
  16902. class BufferGeometryLoader extends Loader {
  16903. constructor( manager ) {
  16904. super( manager );
  16905. }
  16906. load( url, onLoad, onProgress, onError ) {
  16907. const scope = this;
  16908. const loader = new FileLoader( scope.manager );
  16909. loader.setPath( scope.path );
  16910. loader.setRequestHeader( scope.requestHeader );
  16911. loader.setWithCredentials( scope.withCredentials );
  16912. loader.load( url, function ( text ) {
  16913. try {
  16914. onLoad( scope.parse( JSON.parse( text ) ) );
  16915. } catch ( e ) {
  16916. if ( onError ) {
  16917. onError( e );
  16918. } else {
  16919. console.error( e );
  16920. }
  16921. scope.manager.itemError( url );
  16922. }
  16923. }, onProgress, onError );
  16924. }
  16925. parse( json ) {
  16926. const interleavedBufferMap = {};
  16927. const arrayBufferMap = {};
  16928. function getInterleavedBuffer( json, uuid ) {
  16929. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16930. const interleavedBuffers = json.interleavedBuffers;
  16931. const interleavedBuffer = interleavedBuffers[ uuid ];
  16932. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16933. const array = getTypedArray( interleavedBuffer.type, buffer );
  16934. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16935. ib.uuid = interleavedBuffer.uuid;
  16936. interleavedBufferMap[ uuid ] = ib;
  16937. return ib;
  16938. }
  16939. function getArrayBuffer( json, uuid ) {
  16940. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  16941. const arrayBuffers = json.arrayBuffers;
  16942. const arrayBuffer = arrayBuffers[ uuid ];
  16943. const ab = new Uint32Array( arrayBuffer ).buffer;
  16944. arrayBufferMap[ uuid ] = ab;
  16945. return ab;
  16946. }
  16947. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  16948. const index = json.data.index;
  16949. if ( index !== undefined ) {
  16950. const typedArray = getTypedArray( index.type, index.array );
  16951. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16952. }
  16953. const attributes = json.data.attributes;
  16954. for ( const key in attributes ) {
  16955. const attribute = attributes[ key ];
  16956. let bufferAttribute;
  16957. if ( attribute.isInterleavedBufferAttribute ) {
  16958. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16959. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16960. } else {
  16961. const typedArray = getTypedArray( attribute.type, attribute.array );
  16962. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  16963. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  16964. }
  16965. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16966. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  16967. geometry.setAttribute( key, bufferAttribute );
  16968. }
  16969. const morphAttributes = json.data.morphAttributes;
  16970. if ( morphAttributes ) {
  16971. for ( const key in morphAttributes ) {
  16972. const attributeArray = morphAttributes[ key ];
  16973. const array = [];
  16974. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  16975. const attribute = attributeArray[ i ];
  16976. let bufferAttribute;
  16977. if ( attribute.isInterleavedBufferAttribute ) {
  16978. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16979. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16980. } else {
  16981. const typedArray = getTypedArray( attribute.type, attribute.array );
  16982. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  16983. }
  16984. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16985. array.push( bufferAttribute );
  16986. }
  16987. geometry.morphAttributes[ key ] = array;
  16988. }
  16989. }
  16990. const morphTargetsRelative = json.data.morphTargetsRelative;
  16991. if ( morphTargetsRelative ) {
  16992. geometry.morphTargetsRelative = true;
  16993. }
  16994. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16995. if ( groups !== undefined ) {
  16996. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  16997. const group = groups[ i ];
  16998. geometry.addGroup( group.start, group.count, group.materialIndex );
  16999. }
  17000. }
  17001. const boundingSphere = json.data.boundingSphere;
  17002. if ( boundingSphere !== undefined ) {
  17003. const center = new Vector3();
  17004. if ( boundingSphere.center !== undefined ) {
  17005. center.fromArray( boundingSphere.center );
  17006. }
  17007. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17008. }
  17009. if ( json.name ) geometry.name = json.name;
  17010. if ( json.userData ) geometry.userData = json.userData;
  17011. return geometry;
  17012. }
  17013. }
  17014. class ObjectLoader extends Loader {
  17015. constructor( manager ) {
  17016. super( manager );
  17017. }
  17018. load( url, onLoad, onProgress, onError ) {
  17019. const scope = this;
  17020. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17021. this.resourcePath = this.resourcePath || path;
  17022. const loader = new FileLoader( this.manager );
  17023. loader.setPath( this.path );
  17024. loader.setRequestHeader( this.requestHeader );
  17025. loader.setWithCredentials( this.withCredentials );
  17026. loader.load( url, function ( text ) {
  17027. let json = null;
  17028. try {
  17029. json = JSON.parse( text );
  17030. } catch ( error ) {
  17031. if ( onError !== undefined ) onError( error );
  17032. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17033. return;
  17034. }
  17035. const metadata = json.metadata;
  17036. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17037. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17038. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17039. return;
  17040. }
  17041. scope.parse( json, onLoad );
  17042. }, onProgress, onError );
  17043. }
  17044. async loadAsync( url, onProgress ) {
  17045. const scope = this;
  17046. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17047. this.resourcePath = this.resourcePath || path;
  17048. const loader = new FileLoader( this.manager );
  17049. loader.setPath( this.path );
  17050. loader.setRequestHeader( this.requestHeader );
  17051. loader.setWithCredentials( this.withCredentials );
  17052. const text = await loader.loadAsync( url, onProgress );
  17053. const json = JSON.parse( text );
  17054. const metadata = json.metadata;
  17055. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17056. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17057. }
  17058. return await scope.parseAsync( json );
  17059. }
  17060. parse( json, onLoad ) {
  17061. const animations = this.parseAnimations( json.animations );
  17062. const shapes = this.parseShapes( json.shapes );
  17063. const geometries = this.parseGeometries( json.geometries, shapes );
  17064. const images = this.parseImages( json.images, function () {
  17065. if ( onLoad !== undefined ) onLoad( object );
  17066. } );
  17067. const textures = this.parseTextures( json.textures, images );
  17068. const materials = this.parseMaterials( json.materials, textures );
  17069. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17070. const skeletons = this.parseSkeletons( json.skeletons, object );
  17071. this.bindSkeletons( object, skeletons );
  17072. this.bindLightTargets( object );
  17073. //
  17074. if ( onLoad !== undefined ) {
  17075. let hasImages = false;
  17076. for ( const uuid in images ) {
  17077. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17078. hasImages = true;
  17079. break;
  17080. }
  17081. }
  17082. if ( hasImages === false ) onLoad( object );
  17083. }
  17084. return object;
  17085. }
  17086. async parseAsync( json ) {
  17087. const animations = this.parseAnimations( json.animations );
  17088. const shapes = this.parseShapes( json.shapes );
  17089. const geometries = this.parseGeometries( json.geometries, shapes );
  17090. const images = await this.parseImagesAsync( json.images );
  17091. const textures = this.parseTextures( json.textures, images );
  17092. const materials = this.parseMaterials( json.materials, textures );
  17093. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17094. const skeletons = this.parseSkeletons( json.skeletons, object );
  17095. this.bindSkeletons( object, skeletons );
  17096. this.bindLightTargets( object );
  17097. return object;
  17098. }
  17099. parseShapes( json ) {
  17100. const shapes = {};
  17101. if ( json !== undefined ) {
  17102. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17103. const shape = new Shape().fromJSON( json[ i ] );
  17104. shapes[ shape.uuid ] = shape;
  17105. }
  17106. }
  17107. return shapes;
  17108. }
  17109. parseSkeletons( json, object ) {
  17110. const skeletons = {};
  17111. const bones = {};
  17112. // generate bone lookup table
  17113. object.traverse( function ( child ) {
  17114. if ( child.isBone ) bones[ child.uuid ] = child;
  17115. } );
  17116. // create skeletons
  17117. if ( json !== undefined ) {
  17118. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17119. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17120. skeletons[ skeleton.uuid ] = skeleton;
  17121. }
  17122. }
  17123. return skeletons;
  17124. }
  17125. parseGeometries( json, shapes ) {
  17126. const geometries = {};
  17127. if ( json !== undefined ) {
  17128. const bufferGeometryLoader = new BufferGeometryLoader();
  17129. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17130. let geometry;
  17131. const data = json[ i ];
  17132. switch ( data.type ) {
  17133. case 'BufferGeometry':
  17134. case 'InstancedBufferGeometry':
  17135. geometry = bufferGeometryLoader.parse( data );
  17136. break;
  17137. default:
  17138. if ( data.type in Geometries$1 ) {
  17139. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17140. } else {
  17141. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17142. }
  17143. }
  17144. geometry.uuid = data.uuid;
  17145. if ( data.name !== undefined ) geometry.name = data.name;
  17146. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17147. geometries[ data.uuid ] = geometry;
  17148. }
  17149. }
  17150. return geometries;
  17151. }
  17152. parseMaterials( json, textures ) {
  17153. const cache = {}; // MultiMaterial
  17154. const materials = {};
  17155. if ( json !== undefined ) {
  17156. const loader = new MaterialLoader();
  17157. loader.setTextures( textures );
  17158. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17159. const data = json[ i ];
  17160. if ( cache[ data.uuid ] === undefined ) {
  17161. cache[ data.uuid ] = loader.parse( data );
  17162. }
  17163. materials[ data.uuid ] = cache[ data.uuid ];
  17164. }
  17165. }
  17166. return materials;
  17167. }
  17168. parseAnimations( json ) {
  17169. const animations = {};
  17170. if ( json !== undefined ) {
  17171. for ( let i = 0; i < json.length; i ++ ) {
  17172. const data = json[ i ];
  17173. const clip = AnimationClip.parse( data );
  17174. animations[ clip.uuid ] = clip;
  17175. }
  17176. }
  17177. return animations;
  17178. }
  17179. parseImages( json, onLoad ) {
  17180. const scope = this;
  17181. const images = {};
  17182. let loader;
  17183. function loadImage( url ) {
  17184. scope.manager.itemStart( url );
  17185. return loader.load( url, function () {
  17186. scope.manager.itemEnd( url );
  17187. }, undefined, function () {
  17188. scope.manager.itemError( url );
  17189. scope.manager.itemEnd( url );
  17190. } );
  17191. }
  17192. function deserializeImage( image ) {
  17193. if ( typeof image === 'string' ) {
  17194. const url = image;
  17195. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17196. return loadImage( path );
  17197. } else {
  17198. if ( image.data ) {
  17199. return {
  17200. data: getTypedArray( image.type, image.data ),
  17201. width: image.width,
  17202. height: image.height
  17203. };
  17204. } else {
  17205. return null;
  17206. }
  17207. }
  17208. }
  17209. if ( json !== undefined && json.length > 0 ) {
  17210. const manager = new LoadingManager( onLoad );
  17211. loader = new ImageLoader( manager );
  17212. loader.setCrossOrigin( this.crossOrigin );
  17213. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17214. const image = json[ i ];
  17215. const url = image.url;
  17216. if ( Array.isArray( url ) ) {
  17217. // load array of images e.g CubeTexture
  17218. const imageArray = [];
  17219. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17220. const currentUrl = url[ j ];
  17221. const deserializedImage = deserializeImage( currentUrl );
  17222. if ( deserializedImage !== null ) {
  17223. if ( deserializedImage instanceof HTMLImageElement ) {
  17224. imageArray.push( deserializedImage );
  17225. } else {
  17226. // special case: handle array of data textures for cube textures
  17227. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17228. }
  17229. }
  17230. }
  17231. images[ image.uuid ] = new Source( imageArray );
  17232. } else {
  17233. // load single image
  17234. const deserializedImage = deserializeImage( image.url );
  17235. images[ image.uuid ] = new Source( deserializedImage );
  17236. }
  17237. }
  17238. }
  17239. return images;
  17240. }
  17241. async parseImagesAsync( json ) {
  17242. const scope = this;
  17243. const images = {};
  17244. let loader;
  17245. async function deserializeImage( image ) {
  17246. if ( typeof image === 'string' ) {
  17247. const url = image;
  17248. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17249. return await loader.loadAsync( path );
  17250. } else {
  17251. if ( image.data ) {
  17252. return {
  17253. data: getTypedArray( image.type, image.data ),
  17254. width: image.width,
  17255. height: image.height
  17256. };
  17257. } else {
  17258. return null;
  17259. }
  17260. }
  17261. }
  17262. if ( json !== undefined && json.length > 0 ) {
  17263. loader = new ImageLoader( this.manager );
  17264. loader.setCrossOrigin( this.crossOrigin );
  17265. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17266. const image = json[ i ];
  17267. const url = image.url;
  17268. if ( Array.isArray( url ) ) {
  17269. // load array of images e.g CubeTexture
  17270. const imageArray = [];
  17271. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17272. const currentUrl = url[ j ];
  17273. const deserializedImage = await deserializeImage( currentUrl );
  17274. if ( deserializedImage !== null ) {
  17275. if ( deserializedImage instanceof HTMLImageElement ) {
  17276. imageArray.push( deserializedImage );
  17277. } else {
  17278. // special case: handle array of data textures for cube textures
  17279. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17280. }
  17281. }
  17282. }
  17283. images[ image.uuid ] = new Source( imageArray );
  17284. } else {
  17285. // load single image
  17286. const deserializedImage = await deserializeImage( image.url );
  17287. images[ image.uuid ] = new Source( deserializedImage );
  17288. }
  17289. }
  17290. }
  17291. return images;
  17292. }
  17293. parseTextures( json, images ) {
  17294. function parseConstant( value, type ) {
  17295. if ( typeof value === 'number' ) return value;
  17296. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17297. return type[ value ];
  17298. }
  17299. const textures = {};
  17300. if ( json !== undefined ) {
  17301. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17302. const data = json[ i ];
  17303. if ( data.image === undefined ) {
  17304. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17305. }
  17306. if ( images[ data.image ] === undefined ) {
  17307. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17308. }
  17309. const source = images[ data.image ];
  17310. const image = source.data;
  17311. let texture;
  17312. if ( Array.isArray( image ) ) {
  17313. texture = new CubeTexture();
  17314. if ( image.length === 6 ) texture.needsUpdate = true;
  17315. } else {
  17316. if ( image && image.data ) {
  17317. texture = new DataTexture();
  17318. } else {
  17319. texture = new Texture();
  17320. }
  17321. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17322. }
  17323. texture.source = source;
  17324. texture.uuid = data.uuid;
  17325. if ( data.name !== undefined ) texture.name = data.name;
  17326. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17327. if ( data.channel !== undefined ) texture.channel = data.channel;
  17328. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17329. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17330. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17331. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17332. if ( data.wrap !== undefined ) {
  17333. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17334. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17335. }
  17336. if ( data.format !== undefined ) texture.format = data.format;
  17337. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17338. if ( data.type !== undefined ) texture.type = data.type;
  17339. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17340. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17341. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17342. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17343. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17344. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17345. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17346. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17347. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17348. if ( data.userData !== undefined ) texture.userData = data.userData;
  17349. textures[ data.uuid ] = texture;
  17350. }
  17351. }
  17352. return textures;
  17353. }
  17354. parseObject( data, geometries, materials, textures, animations ) {
  17355. let object;
  17356. function getGeometry( name ) {
  17357. if ( geometries[ name ] === undefined ) {
  17358. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17359. }
  17360. return geometries[ name ];
  17361. }
  17362. function getMaterial( name ) {
  17363. if ( name === undefined ) return undefined;
  17364. if ( Array.isArray( name ) ) {
  17365. const array = [];
  17366. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17367. const uuid = name[ i ];
  17368. if ( materials[ uuid ] === undefined ) {
  17369. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17370. }
  17371. array.push( materials[ uuid ] );
  17372. }
  17373. return array;
  17374. }
  17375. if ( materials[ name ] === undefined ) {
  17376. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17377. }
  17378. return materials[ name ];
  17379. }
  17380. function getTexture( uuid ) {
  17381. if ( textures[ uuid ] === undefined ) {
  17382. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17383. }
  17384. return textures[ uuid ];
  17385. }
  17386. let geometry, material;
  17387. switch ( data.type ) {
  17388. case 'Scene':
  17389. object = new Scene();
  17390. if ( data.background !== undefined ) {
  17391. if ( Number.isInteger( data.background ) ) {
  17392. object.background = new Color( data.background );
  17393. } else {
  17394. object.background = getTexture( data.background );
  17395. }
  17396. }
  17397. if ( data.environment !== undefined ) {
  17398. object.environment = getTexture( data.environment );
  17399. }
  17400. if ( data.fog !== undefined ) {
  17401. if ( data.fog.type === 'Fog' ) {
  17402. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17403. } else if ( data.fog.type === 'FogExp2' ) {
  17404. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17405. }
  17406. if ( data.fog.name !== '' ) {
  17407. object.fog.name = data.fog.name;
  17408. }
  17409. }
  17410. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17411. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17412. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17413. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17414. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17415. break;
  17416. case 'PerspectiveCamera':
  17417. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17418. if ( data.focus !== undefined ) object.focus = data.focus;
  17419. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17420. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17421. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17422. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17423. break;
  17424. case 'OrthographicCamera':
  17425. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17426. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17427. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17428. break;
  17429. case 'AmbientLight':
  17430. object = new AmbientLight( data.color, data.intensity );
  17431. break;
  17432. case 'DirectionalLight':
  17433. object = new DirectionalLight( data.color, data.intensity );
  17434. object.target = data.target || '';
  17435. break;
  17436. case 'PointLight':
  17437. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17438. break;
  17439. case 'RectAreaLight':
  17440. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17441. break;
  17442. case 'SpotLight':
  17443. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17444. object.target = data.target || '';
  17445. break;
  17446. case 'HemisphereLight':
  17447. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17448. break;
  17449. case 'LightProbe':
  17450. object = new LightProbe().fromJSON( data );
  17451. break;
  17452. case 'SkinnedMesh':
  17453. geometry = getGeometry( data.geometry );
  17454. material = getMaterial( data.material );
  17455. object = new SkinnedMesh( geometry, material );
  17456. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17457. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17458. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17459. break;
  17460. case 'Mesh':
  17461. geometry = getGeometry( data.geometry );
  17462. material = getMaterial( data.material );
  17463. object = new Mesh( geometry, material );
  17464. break;
  17465. case 'InstancedMesh':
  17466. geometry = getGeometry( data.geometry );
  17467. material = getMaterial( data.material );
  17468. const count = data.count;
  17469. const instanceMatrix = data.instanceMatrix;
  17470. const instanceColor = data.instanceColor;
  17471. object = new InstancedMesh( geometry, material, count );
  17472. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17473. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17474. break;
  17475. case 'BatchedMesh':
  17476. geometry = getGeometry( data.geometry );
  17477. material = getMaterial( data.material );
  17478. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17479. object.geometry = geometry;
  17480. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17481. object.sortObjects = data.sortObjects;
  17482. object._drawRanges = data.drawRanges;
  17483. object._reservedRanges = data.reservedRanges;
  17484. object._visibility = data.visibility;
  17485. object._active = data.active;
  17486. object._bounds = data.bounds.map( bound => {
  17487. const box = new Box3();
  17488. box.min.fromArray( bound.boxMin );
  17489. box.max.fromArray( bound.boxMax );
  17490. const sphere = new Sphere();
  17491. sphere.radius = bound.sphereRadius;
  17492. sphere.center.fromArray( bound.sphereCenter );
  17493. return {
  17494. boxInitialized: bound.boxInitialized,
  17495. box: box,
  17496. sphereInitialized: bound.sphereInitialized,
  17497. sphere: sphere
  17498. };
  17499. } );
  17500. object._maxInstanceCount = data.maxInstanceCount;
  17501. object._maxVertexCount = data.maxVertexCount;
  17502. object._maxIndexCount = data.maxIndexCount;
  17503. object._geometryInitialized = data.geometryInitialized;
  17504. object._geometryCount = data.geometryCount;
  17505. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17506. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17507. break;
  17508. case 'LOD':
  17509. object = new LOD();
  17510. break;
  17511. case 'Line':
  17512. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17513. break;
  17514. case 'LineLoop':
  17515. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17516. break;
  17517. case 'LineSegments':
  17518. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17519. break;
  17520. case 'PointCloud':
  17521. case 'Points':
  17522. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17523. break;
  17524. case 'Sprite':
  17525. object = new Sprite( getMaterial( data.material ) );
  17526. break;
  17527. case 'Group':
  17528. object = new Group();
  17529. break;
  17530. case 'Bone':
  17531. object = new Bone();
  17532. break;
  17533. default:
  17534. object = new Object3D();
  17535. }
  17536. object.uuid = data.uuid;
  17537. if ( data.name !== undefined ) object.name = data.name;
  17538. if ( data.matrix !== undefined ) {
  17539. object.matrix.fromArray( data.matrix );
  17540. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17541. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17542. } else {
  17543. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17544. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17545. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17546. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17547. }
  17548. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17549. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17550. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17551. if ( data.shadow ) {
  17552. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17553. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17554. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17555. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17556. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17557. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17558. }
  17559. if ( data.visible !== undefined ) object.visible = data.visible;
  17560. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17561. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17562. if ( data.userData !== undefined ) object.userData = data.userData;
  17563. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17564. if ( data.children !== undefined ) {
  17565. const children = data.children;
  17566. for ( let i = 0; i < children.length; i ++ ) {
  17567. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17568. }
  17569. }
  17570. if ( data.animations !== undefined ) {
  17571. const objectAnimations = data.animations;
  17572. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17573. const uuid = objectAnimations[ i ];
  17574. object.animations.push( animations[ uuid ] );
  17575. }
  17576. }
  17577. if ( data.type === 'LOD' ) {
  17578. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17579. const levels = data.levels;
  17580. for ( let l = 0; l < levels.length; l ++ ) {
  17581. const level = levels[ l ];
  17582. const child = object.getObjectByProperty( 'uuid', level.object );
  17583. if ( child !== undefined ) {
  17584. object.addLevel( child, level.distance, level.hysteresis );
  17585. }
  17586. }
  17587. }
  17588. return object;
  17589. }
  17590. bindSkeletons( object, skeletons ) {
  17591. if ( Object.keys( skeletons ).length === 0 ) return;
  17592. object.traverse( function ( child ) {
  17593. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17594. const skeleton = skeletons[ child.skeleton ];
  17595. if ( skeleton === undefined ) {
  17596. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17597. } else {
  17598. child.bind( skeleton, child.bindMatrix );
  17599. }
  17600. }
  17601. } );
  17602. }
  17603. bindLightTargets( object ) {
  17604. object.traverse( function ( child ) {
  17605. if ( child.isDirectionalLight || child.isSpotLight ) {
  17606. const uuid = child.target;
  17607. const target = object.getObjectByProperty( 'uuid', uuid );
  17608. if ( target !== undefined ) {
  17609. child.target = target;
  17610. } else {
  17611. child.target = new Object3D();
  17612. }
  17613. }
  17614. } );
  17615. }
  17616. }
  17617. const TEXTURE_MAPPING = {
  17618. UVMapping: UVMapping,
  17619. CubeReflectionMapping: CubeReflectionMapping,
  17620. CubeRefractionMapping: CubeRefractionMapping,
  17621. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17622. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17623. CubeUVReflectionMapping: CubeUVReflectionMapping
  17624. };
  17625. const TEXTURE_WRAPPING = {
  17626. RepeatWrapping: RepeatWrapping,
  17627. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17628. MirroredRepeatWrapping: MirroredRepeatWrapping
  17629. };
  17630. const TEXTURE_FILTER = {
  17631. NearestFilter: NearestFilter,
  17632. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17633. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17634. LinearFilter: LinearFilter,
  17635. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17636. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17637. };
  17638. class ImageBitmapLoader extends Loader {
  17639. constructor( manager ) {
  17640. super( manager );
  17641. this.isImageBitmapLoader = true;
  17642. if ( typeof createImageBitmap === 'undefined' ) {
  17643. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17644. }
  17645. if ( typeof fetch === 'undefined' ) {
  17646. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17647. }
  17648. this.options = { premultiplyAlpha: 'none' };
  17649. }
  17650. setOptions( options ) {
  17651. this.options = options;
  17652. return this;
  17653. }
  17654. load( url, onLoad, onProgress, onError ) {
  17655. if ( url === undefined ) url = '';
  17656. if ( this.path !== undefined ) url = this.path + url;
  17657. url = this.manager.resolveURL( url );
  17658. const scope = this;
  17659. const cached = Cache.get( url );
  17660. if ( cached !== undefined ) {
  17661. scope.manager.itemStart( url );
  17662. // If cached is a promise, wait for it to resolve
  17663. if ( cached.then ) {
  17664. cached.then( imageBitmap => {
  17665. if ( onLoad ) onLoad( imageBitmap );
  17666. scope.manager.itemEnd( url );
  17667. } ).catch( e => {
  17668. if ( onError ) onError( e );
  17669. } );
  17670. return;
  17671. }
  17672. // If cached is not a promise (i.e., it's already an imageBitmap)
  17673. setTimeout( function () {
  17674. if ( onLoad ) onLoad( cached );
  17675. scope.manager.itemEnd( url );
  17676. }, 0 );
  17677. return cached;
  17678. }
  17679. const fetchOptions = {};
  17680. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17681. fetchOptions.headers = this.requestHeader;
  17682. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17683. return res.blob();
  17684. } ).then( function ( blob ) {
  17685. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17686. } ).then( function ( imageBitmap ) {
  17687. Cache.add( url, imageBitmap );
  17688. if ( onLoad ) onLoad( imageBitmap );
  17689. scope.manager.itemEnd( url );
  17690. return imageBitmap;
  17691. } ).catch( function ( e ) {
  17692. if ( onError ) onError( e );
  17693. Cache.remove( url );
  17694. scope.manager.itemError( url );
  17695. scope.manager.itemEnd( url );
  17696. } );
  17697. Cache.add( url, promise );
  17698. scope.manager.itemStart( url );
  17699. }
  17700. }
  17701. let _context;
  17702. class AudioContext {
  17703. static getContext() {
  17704. if ( _context === undefined ) {
  17705. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17706. }
  17707. return _context;
  17708. }
  17709. static setContext( value ) {
  17710. _context = value;
  17711. }
  17712. }
  17713. class AudioLoader extends Loader {
  17714. constructor( manager ) {
  17715. super( manager );
  17716. }
  17717. load( url, onLoad, onProgress, onError ) {
  17718. const scope = this;
  17719. const loader = new FileLoader( this.manager );
  17720. loader.setResponseType( 'arraybuffer' );
  17721. loader.setPath( this.path );
  17722. loader.setRequestHeader( this.requestHeader );
  17723. loader.setWithCredentials( this.withCredentials );
  17724. loader.load( url, function ( buffer ) {
  17725. try {
  17726. // Create a copy of the buffer. The `decodeAudioData` method
  17727. // detaches the buffer when complete, preventing reuse.
  17728. const bufferCopy = buffer.slice( 0 );
  17729. const context = AudioContext.getContext();
  17730. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17731. onLoad( audioBuffer );
  17732. } ).catch( handleError );
  17733. } catch ( e ) {
  17734. handleError( e );
  17735. }
  17736. }, onProgress, onError );
  17737. function handleError( e ) {
  17738. if ( onError ) {
  17739. onError( e );
  17740. } else {
  17741. console.error( e );
  17742. }
  17743. scope.manager.itemError( url );
  17744. }
  17745. }
  17746. }
  17747. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17748. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17749. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17750. class StereoCamera {
  17751. constructor() {
  17752. this.type = 'StereoCamera';
  17753. this.aspect = 1;
  17754. this.eyeSep = 0.064;
  17755. this.cameraL = new PerspectiveCamera();
  17756. this.cameraL.layers.enable( 1 );
  17757. this.cameraL.matrixAutoUpdate = false;
  17758. this.cameraR = new PerspectiveCamera();
  17759. this.cameraR.layers.enable( 2 );
  17760. this.cameraR.matrixAutoUpdate = false;
  17761. this._cache = {
  17762. focus: null,
  17763. fov: null,
  17764. aspect: null,
  17765. near: null,
  17766. far: null,
  17767. zoom: null,
  17768. eyeSep: null
  17769. };
  17770. }
  17771. update( camera ) {
  17772. const cache = this._cache;
  17773. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17774. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17775. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17776. if ( needsUpdate ) {
  17777. cache.focus = camera.focus;
  17778. cache.fov = camera.fov;
  17779. cache.aspect = camera.aspect * this.aspect;
  17780. cache.near = camera.near;
  17781. cache.far = camera.far;
  17782. cache.zoom = camera.zoom;
  17783. cache.eyeSep = this.eyeSep;
  17784. // Off-axis stereoscopic effect based on
  17785. // http://paulbourke.net/stereographics/stereorender/
  17786. _projectionMatrix.copy( camera.projectionMatrix );
  17787. const eyeSepHalf = cache.eyeSep / 2;
  17788. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17789. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17790. let xmin, xmax;
  17791. // translate xOffset
  17792. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17793. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17794. // for left eye
  17795. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17796. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17797. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17798. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17799. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17800. // for right eye
  17801. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17802. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17803. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17804. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17805. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17806. }
  17807. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17808. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17809. }
  17810. }
  17811. class ArrayCamera extends PerspectiveCamera {
  17812. constructor( array = [] ) {
  17813. super();
  17814. this.isArrayCamera = true;
  17815. this.cameras = array;
  17816. }
  17817. }
  17818. class Clock {
  17819. constructor( autoStart = true ) {
  17820. this.autoStart = autoStart;
  17821. this.startTime = 0;
  17822. this.oldTime = 0;
  17823. this.elapsedTime = 0;
  17824. this.running = false;
  17825. }
  17826. start() {
  17827. this.startTime = now();
  17828. this.oldTime = this.startTime;
  17829. this.elapsedTime = 0;
  17830. this.running = true;
  17831. }
  17832. stop() {
  17833. this.getElapsedTime();
  17834. this.running = false;
  17835. this.autoStart = false;
  17836. }
  17837. getElapsedTime() {
  17838. this.getDelta();
  17839. return this.elapsedTime;
  17840. }
  17841. getDelta() {
  17842. let diff = 0;
  17843. if ( this.autoStart && ! this.running ) {
  17844. this.start();
  17845. return 0;
  17846. }
  17847. if ( this.running ) {
  17848. const newTime = now();
  17849. diff = ( newTime - this.oldTime ) / 1000;
  17850. this.oldTime = newTime;
  17851. this.elapsedTime += diff;
  17852. }
  17853. return diff;
  17854. }
  17855. }
  17856. function now() {
  17857. return performance.now();
  17858. }
  17859. const _position$1 = /*@__PURE__*/ new Vector3();
  17860. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17861. const _scale$1 = /*@__PURE__*/ new Vector3();
  17862. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17863. class AudioListener extends Object3D {
  17864. constructor() {
  17865. super();
  17866. this.type = 'AudioListener';
  17867. this.context = AudioContext.getContext();
  17868. this.gain = this.context.createGain();
  17869. this.gain.connect( this.context.destination );
  17870. this.filter = null;
  17871. this.timeDelta = 0;
  17872. // private
  17873. this._clock = new Clock();
  17874. }
  17875. getInput() {
  17876. return this.gain;
  17877. }
  17878. removeFilter() {
  17879. if ( this.filter !== null ) {
  17880. this.gain.disconnect( this.filter );
  17881. this.filter.disconnect( this.context.destination );
  17882. this.gain.connect( this.context.destination );
  17883. this.filter = null;
  17884. }
  17885. return this;
  17886. }
  17887. getFilter() {
  17888. return this.filter;
  17889. }
  17890. setFilter( value ) {
  17891. if ( this.filter !== null ) {
  17892. this.gain.disconnect( this.filter );
  17893. this.filter.disconnect( this.context.destination );
  17894. } else {
  17895. this.gain.disconnect( this.context.destination );
  17896. }
  17897. this.filter = value;
  17898. this.gain.connect( this.filter );
  17899. this.filter.connect( this.context.destination );
  17900. return this;
  17901. }
  17902. getMasterVolume() {
  17903. return this.gain.gain.value;
  17904. }
  17905. setMasterVolume( value ) {
  17906. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17907. return this;
  17908. }
  17909. updateMatrixWorld( force ) {
  17910. super.updateMatrixWorld( force );
  17911. const listener = this.context.listener;
  17912. const up = this.up;
  17913. this.timeDelta = this._clock.getDelta();
  17914. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17915. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17916. if ( listener.positionX ) {
  17917. // code path for Chrome (see #14393)
  17918. const endTime = this.context.currentTime + this.timeDelta;
  17919. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17920. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17921. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17922. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17923. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17924. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17925. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17926. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17927. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17928. } else {
  17929. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17930. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17931. }
  17932. }
  17933. }
  17934. class Audio extends Object3D {
  17935. constructor( listener ) {
  17936. super();
  17937. this.type = 'Audio';
  17938. this.listener = listener;
  17939. this.context = listener.context;
  17940. this.gain = this.context.createGain();
  17941. this.gain.connect( listener.getInput() );
  17942. this.autoplay = false;
  17943. this.buffer = null;
  17944. this.detune = 0;
  17945. this.loop = false;
  17946. this.loopStart = 0;
  17947. this.loopEnd = 0;
  17948. this.offset = 0;
  17949. this.duration = undefined;
  17950. this.playbackRate = 1;
  17951. this.isPlaying = false;
  17952. this.hasPlaybackControl = true;
  17953. this.source = null;
  17954. this.sourceType = 'empty';
  17955. this._startedAt = 0;
  17956. this._progress = 0;
  17957. this._connected = false;
  17958. this.filters = [];
  17959. }
  17960. getOutput() {
  17961. return this.gain;
  17962. }
  17963. setNodeSource( audioNode ) {
  17964. this.hasPlaybackControl = false;
  17965. this.sourceType = 'audioNode';
  17966. this.source = audioNode;
  17967. this.connect();
  17968. return this;
  17969. }
  17970. setMediaElementSource( mediaElement ) {
  17971. this.hasPlaybackControl = false;
  17972. this.sourceType = 'mediaNode';
  17973. this.source = this.context.createMediaElementSource( mediaElement );
  17974. this.connect();
  17975. return this;
  17976. }
  17977. setMediaStreamSource( mediaStream ) {
  17978. this.hasPlaybackControl = false;
  17979. this.sourceType = 'mediaStreamNode';
  17980. this.source = this.context.createMediaStreamSource( mediaStream );
  17981. this.connect();
  17982. return this;
  17983. }
  17984. setBuffer( audioBuffer ) {
  17985. this.buffer = audioBuffer;
  17986. this.sourceType = 'buffer';
  17987. if ( this.autoplay ) this.play();
  17988. return this;
  17989. }
  17990. play( delay = 0 ) {
  17991. if ( this.isPlaying === true ) {
  17992. console.warn( 'THREE.Audio: Audio is already playing.' );
  17993. return;
  17994. }
  17995. if ( this.hasPlaybackControl === false ) {
  17996. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  17997. return;
  17998. }
  17999. this._startedAt = this.context.currentTime + delay;
  18000. const source = this.context.createBufferSource();
  18001. source.buffer = this.buffer;
  18002. source.loop = this.loop;
  18003. source.loopStart = this.loopStart;
  18004. source.loopEnd = this.loopEnd;
  18005. source.onended = this.onEnded.bind( this );
  18006. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18007. this.isPlaying = true;
  18008. this.source = source;
  18009. this.setDetune( this.detune );
  18010. this.setPlaybackRate( this.playbackRate );
  18011. return this.connect();
  18012. }
  18013. pause() {
  18014. if ( this.hasPlaybackControl === false ) {
  18015. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18016. return;
  18017. }
  18018. if ( this.isPlaying === true ) {
  18019. // update current progress
  18020. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18021. if ( this.loop === true ) {
  18022. // ensure _progress does not exceed duration with looped audios
  18023. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18024. }
  18025. this.source.stop();
  18026. this.source.onended = null;
  18027. this.isPlaying = false;
  18028. }
  18029. return this;
  18030. }
  18031. stop() {
  18032. if ( this.hasPlaybackControl === false ) {
  18033. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18034. return;
  18035. }
  18036. this._progress = 0;
  18037. if ( this.source !== null ) {
  18038. this.source.stop();
  18039. this.source.onended = null;
  18040. }
  18041. this.isPlaying = false;
  18042. return this;
  18043. }
  18044. connect() {
  18045. if ( this.filters.length > 0 ) {
  18046. this.source.connect( this.filters[ 0 ] );
  18047. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18048. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18049. }
  18050. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18051. } else {
  18052. this.source.connect( this.getOutput() );
  18053. }
  18054. this._connected = true;
  18055. return this;
  18056. }
  18057. disconnect() {
  18058. if ( this._connected === false ) {
  18059. return;
  18060. }
  18061. if ( this.filters.length > 0 ) {
  18062. this.source.disconnect( this.filters[ 0 ] );
  18063. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18064. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18065. }
  18066. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18067. } else {
  18068. this.source.disconnect( this.getOutput() );
  18069. }
  18070. this._connected = false;
  18071. return this;
  18072. }
  18073. getFilters() {
  18074. return this.filters;
  18075. }
  18076. setFilters( value ) {
  18077. if ( ! value ) value = [];
  18078. if ( this._connected === true ) {
  18079. this.disconnect();
  18080. this.filters = value.slice();
  18081. this.connect();
  18082. } else {
  18083. this.filters = value.slice();
  18084. }
  18085. return this;
  18086. }
  18087. setDetune( value ) {
  18088. this.detune = value;
  18089. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18090. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18091. }
  18092. return this;
  18093. }
  18094. getDetune() {
  18095. return this.detune;
  18096. }
  18097. getFilter() {
  18098. return this.getFilters()[ 0 ];
  18099. }
  18100. setFilter( filter ) {
  18101. return this.setFilters( filter ? [ filter ] : [] );
  18102. }
  18103. setPlaybackRate( value ) {
  18104. if ( this.hasPlaybackControl === false ) {
  18105. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18106. return;
  18107. }
  18108. this.playbackRate = value;
  18109. if ( this.isPlaying === true ) {
  18110. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18111. }
  18112. return this;
  18113. }
  18114. getPlaybackRate() {
  18115. return this.playbackRate;
  18116. }
  18117. onEnded() {
  18118. this.isPlaying = false;
  18119. }
  18120. getLoop() {
  18121. if ( this.hasPlaybackControl === false ) {
  18122. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18123. return false;
  18124. }
  18125. return this.loop;
  18126. }
  18127. setLoop( value ) {
  18128. if ( this.hasPlaybackControl === false ) {
  18129. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18130. return;
  18131. }
  18132. this.loop = value;
  18133. if ( this.isPlaying === true ) {
  18134. this.source.loop = this.loop;
  18135. }
  18136. return this;
  18137. }
  18138. setLoopStart( value ) {
  18139. this.loopStart = value;
  18140. return this;
  18141. }
  18142. setLoopEnd( value ) {
  18143. this.loopEnd = value;
  18144. return this;
  18145. }
  18146. getVolume() {
  18147. return this.gain.gain.value;
  18148. }
  18149. setVolume( value ) {
  18150. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18151. return this;
  18152. }
  18153. }
  18154. const _position = /*@__PURE__*/ new Vector3();
  18155. const _quaternion = /*@__PURE__*/ new Quaternion();
  18156. const _scale = /*@__PURE__*/ new Vector3();
  18157. const _orientation = /*@__PURE__*/ new Vector3();
  18158. class PositionalAudio extends Audio {
  18159. constructor( listener ) {
  18160. super( listener );
  18161. this.panner = this.context.createPanner();
  18162. this.panner.panningModel = 'HRTF';
  18163. this.panner.connect( this.gain );
  18164. }
  18165. connect() {
  18166. super.connect();
  18167. this.panner.connect( this.gain );
  18168. }
  18169. disconnect() {
  18170. super.disconnect();
  18171. this.panner.disconnect( this.gain );
  18172. }
  18173. getOutput() {
  18174. return this.panner;
  18175. }
  18176. getRefDistance() {
  18177. return this.panner.refDistance;
  18178. }
  18179. setRefDistance( value ) {
  18180. this.panner.refDistance = value;
  18181. return this;
  18182. }
  18183. getRolloffFactor() {
  18184. return this.panner.rolloffFactor;
  18185. }
  18186. setRolloffFactor( value ) {
  18187. this.panner.rolloffFactor = value;
  18188. return this;
  18189. }
  18190. getDistanceModel() {
  18191. return this.panner.distanceModel;
  18192. }
  18193. setDistanceModel( value ) {
  18194. this.panner.distanceModel = value;
  18195. return this;
  18196. }
  18197. getMaxDistance() {
  18198. return this.panner.maxDistance;
  18199. }
  18200. setMaxDistance( value ) {
  18201. this.panner.maxDistance = value;
  18202. return this;
  18203. }
  18204. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18205. this.panner.coneInnerAngle = coneInnerAngle;
  18206. this.panner.coneOuterAngle = coneOuterAngle;
  18207. this.panner.coneOuterGain = coneOuterGain;
  18208. return this;
  18209. }
  18210. updateMatrixWorld( force ) {
  18211. super.updateMatrixWorld( force );
  18212. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18213. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18214. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18215. const panner = this.panner;
  18216. if ( panner.positionX ) {
  18217. // code path for Chrome and Firefox (see #14393)
  18218. const endTime = this.context.currentTime + this.listener.timeDelta;
  18219. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18220. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18221. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18222. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18223. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18224. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18225. } else {
  18226. panner.setPosition( _position.x, _position.y, _position.z );
  18227. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18228. }
  18229. }
  18230. }
  18231. class AudioAnalyser {
  18232. constructor( audio, fftSize = 2048 ) {
  18233. this.analyser = audio.context.createAnalyser();
  18234. this.analyser.fftSize = fftSize;
  18235. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18236. audio.getOutput().connect( this.analyser );
  18237. }
  18238. getFrequencyData() {
  18239. this.analyser.getByteFrequencyData( this.data );
  18240. return this.data;
  18241. }
  18242. getAverageFrequency() {
  18243. let value = 0;
  18244. const data = this.getFrequencyData();
  18245. for ( let i = 0; i < data.length; i ++ ) {
  18246. value += data[ i ];
  18247. }
  18248. return value / data.length;
  18249. }
  18250. }
  18251. class PropertyMixer {
  18252. constructor( binding, typeName, valueSize ) {
  18253. this.binding = binding;
  18254. this.valueSize = valueSize;
  18255. let mixFunction,
  18256. mixFunctionAdditive,
  18257. setIdentity;
  18258. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18259. //
  18260. // interpolators can use .buffer as their .result
  18261. // the data then goes to 'incoming'
  18262. //
  18263. // 'accu0' and 'accu1' are used frame-interleaved for
  18264. // the cumulative result and are compared to detect
  18265. // changes
  18266. //
  18267. // 'orig' stores the original state of the property
  18268. //
  18269. // 'add' is used for additive cumulative results
  18270. //
  18271. // 'work' is optional and is only present for quaternion types. It is used
  18272. // to store intermediate quaternion multiplication results
  18273. switch ( typeName ) {
  18274. case 'quaternion':
  18275. mixFunction = this._slerp;
  18276. mixFunctionAdditive = this._slerpAdditive;
  18277. setIdentity = this._setAdditiveIdentityQuaternion;
  18278. this.buffer = new Float64Array( valueSize * 6 );
  18279. this._workIndex = 5;
  18280. break;
  18281. case 'string':
  18282. case 'bool':
  18283. mixFunction = this._select;
  18284. // Use the regular mix function and for additive on these types,
  18285. // additive is not relevant for non-numeric types
  18286. mixFunctionAdditive = this._select;
  18287. setIdentity = this._setAdditiveIdentityOther;
  18288. this.buffer = new Array( valueSize * 5 );
  18289. break;
  18290. default:
  18291. mixFunction = this._lerp;
  18292. mixFunctionAdditive = this._lerpAdditive;
  18293. setIdentity = this._setAdditiveIdentityNumeric;
  18294. this.buffer = new Float64Array( valueSize * 5 );
  18295. }
  18296. this._mixBufferRegion = mixFunction;
  18297. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18298. this._setIdentity = setIdentity;
  18299. this._origIndex = 3;
  18300. this._addIndex = 4;
  18301. this.cumulativeWeight = 0;
  18302. this.cumulativeWeightAdditive = 0;
  18303. this.useCount = 0;
  18304. this.referenceCount = 0;
  18305. }
  18306. // accumulate data in the 'incoming' region into 'accu<i>'
  18307. accumulate( accuIndex, weight ) {
  18308. // note: happily accumulating nothing when weight = 0, the caller knows
  18309. // the weight and shouldn't have made the call in the first place
  18310. const buffer = this.buffer,
  18311. stride = this.valueSize,
  18312. offset = accuIndex * stride + stride;
  18313. let currentWeight = this.cumulativeWeight;
  18314. if ( currentWeight === 0 ) {
  18315. // accuN := incoming * weight
  18316. for ( let i = 0; i !== stride; ++ i ) {
  18317. buffer[ offset + i ] = buffer[ i ];
  18318. }
  18319. currentWeight = weight;
  18320. } else {
  18321. // accuN := accuN + incoming * weight
  18322. currentWeight += weight;
  18323. const mix = weight / currentWeight;
  18324. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18325. }
  18326. this.cumulativeWeight = currentWeight;
  18327. }
  18328. // accumulate data in the 'incoming' region into 'add'
  18329. accumulateAdditive( weight ) {
  18330. const buffer = this.buffer,
  18331. stride = this.valueSize,
  18332. offset = stride * this._addIndex;
  18333. if ( this.cumulativeWeightAdditive === 0 ) {
  18334. // add = identity
  18335. this._setIdentity();
  18336. }
  18337. // add := add + incoming * weight
  18338. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18339. this.cumulativeWeightAdditive += weight;
  18340. }
  18341. // apply the state of 'accu<i>' to the binding when accus differ
  18342. apply( accuIndex ) {
  18343. const stride = this.valueSize,
  18344. buffer = this.buffer,
  18345. offset = accuIndex * stride + stride,
  18346. weight = this.cumulativeWeight,
  18347. weightAdditive = this.cumulativeWeightAdditive,
  18348. binding = this.binding;
  18349. this.cumulativeWeight = 0;
  18350. this.cumulativeWeightAdditive = 0;
  18351. if ( weight < 1 ) {
  18352. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18353. const originalValueOffset = stride * this._origIndex;
  18354. this._mixBufferRegion(
  18355. buffer, offset, originalValueOffset, 1 - weight, stride );
  18356. }
  18357. if ( weightAdditive > 0 ) {
  18358. // accuN := accuN + additive accuN
  18359. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18360. }
  18361. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18362. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18363. // value has changed -> update scene graph
  18364. binding.setValue( buffer, offset );
  18365. break;
  18366. }
  18367. }
  18368. }
  18369. // remember the state of the bound property and copy it to both accus
  18370. saveOriginalState() {
  18371. const binding = this.binding;
  18372. const buffer = this.buffer,
  18373. stride = this.valueSize,
  18374. originalValueOffset = stride * this._origIndex;
  18375. binding.getValue( buffer, originalValueOffset );
  18376. // accu[0..1] := orig -- initially detect changes against the original
  18377. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18378. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18379. }
  18380. // Add to identity for additive
  18381. this._setIdentity();
  18382. this.cumulativeWeight = 0;
  18383. this.cumulativeWeightAdditive = 0;
  18384. }
  18385. // apply the state previously taken via 'saveOriginalState' to the binding
  18386. restoreOriginalState() {
  18387. const originalValueOffset = this.valueSize * 3;
  18388. this.binding.setValue( this.buffer, originalValueOffset );
  18389. }
  18390. _setAdditiveIdentityNumeric() {
  18391. const startIndex = this._addIndex * this.valueSize;
  18392. const endIndex = startIndex + this.valueSize;
  18393. for ( let i = startIndex; i < endIndex; i ++ ) {
  18394. this.buffer[ i ] = 0;
  18395. }
  18396. }
  18397. _setAdditiveIdentityQuaternion() {
  18398. this._setAdditiveIdentityNumeric();
  18399. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18400. }
  18401. _setAdditiveIdentityOther() {
  18402. const startIndex = this._origIndex * this.valueSize;
  18403. const targetIndex = this._addIndex * this.valueSize;
  18404. for ( let i = 0; i < this.valueSize; i ++ ) {
  18405. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18406. }
  18407. }
  18408. // mix functions
  18409. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18410. if ( t >= 0.5 ) {
  18411. for ( let i = 0; i !== stride; ++ i ) {
  18412. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18413. }
  18414. }
  18415. }
  18416. _slerp( buffer, dstOffset, srcOffset, t ) {
  18417. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18418. }
  18419. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18420. const workOffset = this._workIndex * stride;
  18421. // Store result in intermediate buffer offset
  18422. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18423. // Slerp to the intermediate result
  18424. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18425. }
  18426. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18427. const s = 1 - t;
  18428. for ( let i = 0; i !== stride; ++ i ) {
  18429. const j = dstOffset + i;
  18430. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18431. }
  18432. }
  18433. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18434. for ( let i = 0; i !== stride; ++ i ) {
  18435. const j = dstOffset + i;
  18436. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18437. }
  18438. }
  18439. }
  18440. // Characters [].:/ are reserved for track binding syntax.
  18441. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18442. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18443. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18444. // only latin characters, and the unicode \p{L} is not yet supported. So
  18445. // instead, we exclude reserved characters and match everything else.
  18446. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18447. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18448. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18449. // be matched to parse the rest of the track name.
  18450. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18451. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18452. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18453. // Object on target node, and accessor. May not contain reserved
  18454. // characters. Accessor may contain any character except closing bracket.
  18455. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18456. // Property and accessor. May not contain reserved characters. Accessor may
  18457. // contain any non-bracket characters.
  18458. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18459. const _trackRe = new RegExp( ''
  18460. + '^'
  18461. + _directoryRe
  18462. + _nodeRe
  18463. + _objectRe
  18464. + _propertyRe
  18465. + '$'
  18466. );
  18467. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18468. class Composite {
  18469. constructor( targetGroup, path, optionalParsedPath ) {
  18470. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18471. this._targetGroup = targetGroup;
  18472. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18473. }
  18474. getValue( array, offset ) {
  18475. this.bind(); // bind all binding
  18476. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18477. binding = this._bindings[ firstValidIndex ];
  18478. // and only call .getValue on the first
  18479. if ( binding !== undefined ) binding.getValue( array, offset );
  18480. }
  18481. setValue( array, offset ) {
  18482. const bindings = this._bindings;
  18483. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18484. bindings[ i ].setValue( array, offset );
  18485. }
  18486. }
  18487. bind() {
  18488. const bindings = this._bindings;
  18489. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18490. bindings[ i ].bind();
  18491. }
  18492. }
  18493. unbind() {
  18494. const bindings = this._bindings;
  18495. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18496. bindings[ i ].unbind();
  18497. }
  18498. }
  18499. }
  18500. // Note: This class uses a State pattern on a per-method basis:
  18501. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18502. // prototype version of these methods with one that represents
  18503. // the bound state. When the property is not found, the methods
  18504. // become no-ops.
  18505. class PropertyBinding {
  18506. constructor( rootNode, path, parsedPath ) {
  18507. this.path = path;
  18508. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18509. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18510. this.rootNode = rootNode;
  18511. // initial state of these methods that calls 'bind'
  18512. this.getValue = this._getValue_unbound;
  18513. this.setValue = this._setValue_unbound;
  18514. }
  18515. static create( root, path, parsedPath ) {
  18516. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18517. return new PropertyBinding( root, path, parsedPath );
  18518. } else {
  18519. return new PropertyBinding.Composite( root, path, parsedPath );
  18520. }
  18521. }
  18522. /**
  18523. * Replaces spaces with underscores and removes unsupported characters from
  18524. * node names, to ensure compatibility with parseTrackName().
  18525. *
  18526. * @param {string} name Node name to be sanitized.
  18527. * @return {string}
  18528. */
  18529. static sanitizeNodeName( name ) {
  18530. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18531. }
  18532. static parseTrackName( trackName ) {
  18533. const matches = _trackRe.exec( trackName );
  18534. if ( matches === null ) {
  18535. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18536. }
  18537. const results = {
  18538. // directoryName: matches[ 1 ], // (tschw) currently unused
  18539. nodeName: matches[ 2 ],
  18540. objectName: matches[ 3 ],
  18541. objectIndex: matches[ 4 ],
  18542. propertyName: matches[ 5 ], // required
  18543. propertyIndex: matches[ 6 ]
  18544. };
  18545. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18546. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18547. const objectName = results.nodeName.substring( lastDot + 1 );
  18548. // Object names must be checked against an allowlist. Otherwise, there
  18549. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18550. // 'bar' could be the objectName, or part of a nodeName (which can
  18551. // include '.' characters).
  18552. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18553. results.nodeName = results.nodeName.substring( 0, lastDot );
  18554. results.objectName = objectName;
  18555. }
  18556. }
  18557. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18558. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18559. }
  18560. return results;
  18561. }
  18562. static findNode( root, nodeName ) {
  18563. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18564. return root;
  18565. }
  18566. // search into skeleton bones.
  18567. if ( root.skeleton ) {
  18568. const bone = root.skeleton.getBoneByName( nodeName );
  18569. if ( bone !== undefined ) {
  18570. return bone;
  18571. }
  18572. }
  18573. // search into node subtree.
  18574. if ( root.children ) {
  18575. const searchNodeSubtree = function ( children ) {
  18576. for ( let i = 0; i < children.length; i ++ ) {
  18577. const childNode = children[ i ];
  18578. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18579. return childNode;
  18580. }
  18581. const result = searchNodeSubtree( childNode.children );
  18582. if ( result ) return result;
  18583. }
  18584. return null;
  18585. };
  18586. const subTreeNode = searchNodeSubtree( root.children );
  18587. if ( subTreeNode ) {
  18588. return subTreeNode;
  18589. }
  18590. }
  18591. return null;
  18592. }
  18593. // these are used to "bind" a nonexistent property
  18594. _getValue_unavailable() {}
  18595. _setValue_unavailable() {}
  18596. // Getters
  18597. _getValue_direct( buffer, offset ) {
  18598. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18599. }
  18600. _getValue_array( buffer, offset ) {
  18601. const source = this.resolvedProperty;
  18602. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18603. buffer[ offset ++ ] = source[ i ];
  18604. }
  18605. }
  18606. _getValue_arrayElement( buffer, offset ) {
  18607. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18608. }
  18609. _getValue_toArray( buffer, offset ) {
  18610. this.resolvedProperty.toArray( buffer, offset );
  18611. }
  18612. // Direct
  18613. _setValue_direct( buffer, offset ) {
  18614. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18615. }
  18616. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18617. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18618. this.targetObject.needsUpdate = true;
  18619. }
  18620. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18621. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18622. this.targetObject.matrixWorldNeedsUpdate = true;
  18623. }
  18624. // EntireArray
  18625. _setValue_array( buffer, offset ) {
  18626. const dest = this.resolvedProperty;
  18627. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18628. dest[ i ] = buffer[ offset ++ ];
  18629. }
  18630. }
  18631. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18632. const dest = this.resolvedProperty;
  18633. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18634. dest[ i ] = buffer[ offset ++ ];
  18635. }
  18636. this.targetObject.needsUpdate = true;
  18637. }
  18638. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18639. const dest = this.resolvedProperty;
  18640. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18641. dest[ i ] = buffer[ offset ++ ];
  18642. }
  18643. this.targetObject.matrixWorldNeedsUpdate = true;
  18644. }
  18645. // ArrayElement
  18646. _setValue_arrayElement( buffer, offset ) {
  18647. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18648. }
  18649. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18650. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18651. this.targetObject.needsUpdate = true;
  18652. }
  18653. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18654. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18655. this.targetObject.matrixWorldNeedsUpdate = true;
  18656. }
  18657. // HasToFromArray
  18658. _setValue_fromArray( buffer, offset ) {
  18659. this.resolvedProperty.fromArray( buffer, offset );
  18660. }
  18661. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18662. this.resolvedProperty.fromArray( buffer, offset );
  18663. this.targetObject.needsUpdate = true;
  18664. }
  18665. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18666. this.resolvedProperty.fromArray( buffer, offset );
  18667. this.targetObject.matrixWorldNeedsUpdate = true;
  18668. }
  18669. _getValue_unbound( targetArray, offset ) {
  18670. this.bind();
  18671. this.getValue( targetArray, offset );
  18672. }
  18673. _setValue_unbound( sourceArray, offset ) {
  18674. this.bind();
  18675. this.setValue( sourceArray, offset );
  18676. }
  18677. // create getter / setter pair for a property in the scene graph
  18678. bind() {
  18679. let targetObject = this.node;
  18680. const parsedPath = this.parsedPath;
  18681. const objectName = parsedPath.objectName;
  18682. const propertyName = parsedPath.propertyName;
  18683. let propertyIndex = parsedPath.propertyIndex;
  18684. if ( ! targetObject ) {
  18685. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18686. this.node = targetObject;
  18687. }
  18688. // set fail state so we can just 'return' on error
  18689. this.getValue = this._getValue_unavailable;
  18690. this.setValue = this._setValue_unavailable;
  18691. // ensure there is a value node
  18692. if ( ! targetObject ) {
  18693. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18694. return;
  18695. }
  18696. if ( objectName ) {
  18697. let objectIndex = parsedPath.objectIndex;
  18698. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18699. switch ( objectName ) {
  18700. case 'materials':
  18701. if ( ! targetObject.material ) {
  18702. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18703. return;
  18704. }
  18705. if ( ! targetObject.material.materials ) {
  18706. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18707. return;
  18708. }
  18709. targetObject = targetObject.material.materials;
  18710. break;
  18711. case 'bones':
  18712. if ( ! targetObject.skeleton ) {
  18713. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18714. return;
  18715. }
  18716. // potential future optimization: skip this if propertyIndex is already an integer
  18717. // and convert the integer string to a true integer.
  18718. targetObject = targetObject.skeleton.bones;
  18719. // support resolving morphTarget names into indices.
  18720. for ( let i = 0; i < targetObject.length; i ++ ) {
  18721. if ( targetObject[ i ].name === objectIndex ) {
  18722. objectIndex = i;
  18723. break;
  18724. }
  18725. }
  18726. break;
  18727. case 'map':
  18728. if ( 'map' in targetObject ) {
  18729. targetObject = targetObject.map;
  18730. break;
  18731. }
  18732. if ( ! targetObject.material ) {
  18733. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18734. return;
  18735. }
  18736. if ( ! targetObject.material.map ) {
  18737. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18738. return;
  18739. }
  18740. targetObject = targetObject.material.map;
  18741. break;
  18742. default:
  18743. if ( targetObject[ objectName ] === undefined ) {
  18744. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18745. return;
  18746. }
  18747. targetObject = targetObject[ objectName ];
  18748. }
  18749. if ( objectIndex !== undefined ) {
  18750. if ( targetObject[ objectIndex ] === undefined ) {
  18751. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18752. return;
  18753. }
  18754. targetObject = targetObject[ objectIndex ];
  18755. }
  18756. }
  18757. // resolve property
  18758. const nodeProperty = targetObject[ propertyName ];
  18759. if ( nodeProperty === undefined ) {
  18760. const nodeName = parsedPath.nodeName;
  18761. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18762. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18763. return;
  18764. }
  18765. // determine versioning scheme
  18766. let versioning = this.Versioning.None;
  18767. this.targetObject = targetObject;
  18768. if ( targetObject.needsUpdate !== undefined ) { // material
  18769. versioning = this.Versioning.NeedsUpdate;
  18770. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18771. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18772. }
  18773. // determine how the property gets bound
  18774. let bindingType = this.BindingType.Direct;
  18775. if ( propertyIndex !== undefined ) {
  18776. // access a sub element of the property array (only primitives are supported right now)
  18777. if ( propertyName === 'morphTargetInfluences' ) {
  18778. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18779. // support resolving morphTarget names into indices.
  18780. if ( ! targetObject.geometry ) {
  18781. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18782. return;
  18783. }
  18784. if ( ! targetObject.geometry.morphAttributes ) {
  18785. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18786. return;
  18787. }
  18788. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18789. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18790. }
  18791. }
  18792. bindingType = this.BindingType.ArrayElement;
  18793. this.resolvedProperty = nodeProperty;
  18794. this.propertyIndex = propertyIndex;
  18795. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18796. // must use copy for Object3D.Euler/Quaternion
  18797. bindingType = this.BindingType.HasFromToArray;
  18798. this.resolvedProperty = nodeProperty;
  18799. } else if ( Array.isArray( nodeProperty ) ) {
  18800. bindingType = this.BindingType.EntireArray;
  18801. this.resolvedProperty = nodeProperty;
  18802. } else {
  18803. this.propertyName = propertyName;
  18804. }
  18805. // select getter / setter
  18806. this.getValue = this.GetterByBindingType[ bindingType ];
  18807. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18808. }
  18809. unbind() {
  18810. this.node = null;
  18811. // back to the prototype version of getValue / setValue
  18812. // note: avoiding to mutate the shape of 'this' via 'delete'
  18813. this.getValue = this._getValue_unbound;
  18814. this.setValue = this._setValue_unbound;
  18815. }
  18816. }
  18817. PropertyBinding.Composite = Composite;
  18818. PropertyBinding.prototype.BindingType = {
  18819. Direct: 0,
  18820. EntireArray: 1,
  18821. ArrayElement: 2,
  18822. HasFromToArray: 3
  18823. };
  18824. PropertyBinding.prototype.Versioning = {
  18825. None: 0,
  18826. NeedsUpdate: 1,
  18827. MatrixWorldNeedsUpdate: 2
  18828. };
  18829. PropertyBinding.prototype.GetterByBindingType = [
  18830. PropertyBinding.prototype._getValue_direct,
  18831. PropertyBinding.prototype._getValue_array,
  18832. PropertyBinding.prototype._getValue_arrayElement,
  18833. PropertyBinding.prototype._getValue_toArray,
  18834. ];
  18835. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18836. [
  18837. // Direct
  18838. PropertyBinding.prototype._setValue_direct,
  18839. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18840. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18841. ], [
  18842. // EntireArray
  18843. PropertyBinding.prototype._setValue_array,
  18844. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18845. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18846. ], [
  18847. // ArrayElement
  18848. PropertyBinding.prototype._setValue_arrayElement,
  18849. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18850. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18851. ], [
  18852. // HasToFromArray
  18853. PropertyBinding.prototype._setValue_fromArray,
  18854. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18855. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18856. ]
  18857. ];
  18858. /**
  18859. *
  18860. * A group of objects that receives a shared animation state.
  18861. *
  18862. * Usage:
  18863. *
  18864. * - Add objects you would otherwise pass as 'root' to the
  18865. * constructor or the .clipAction method of AnimationMixer.
  18866. *
  18867. * - Instead pass this object as 'root'.
  18868. *
  18869. * - You can also add and remove objects later when the mixer
  18870. * is running.
  18871. *
  18872. * Note:
  18873. *
  18874. * Objects of this class appear as one object to the mixer,
  18875. * so cache control of the individual objects must be done
  18876. * on the group.
  18877. *
  18878. * Limitation:
  18879. *
  18880. * - The animated properties must be compatible among the
  18881. * all objects in the group.
  18882. *
  18883. * - A single property can either be controlled through a
  18884. * target group or directly, but not both.
  18885. */
  18886. class AnimationObjectGroup {
  18887. constructor() {
  18888. this.isAnimationObjectGroup = true;
  18889. this.uuid = generateUUID();
  18890. // cached objects followed by the active ones
  18891. this._objects = Array.prototype.slice.call( arguments );
  18892. this.nCachedObjects_ = 0; // threshold
  18893. // note: read by PropertyBinding.Composite
  18894. const indices = {};
  18895. this._indicesByUUID = indices; // for bookkeeping
  18896. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18897. indices[ arguments[ i ].uuid ] = i;
  18898. }
  18899. this._paths = []; // inside: string
  18900. this._parsedPaths = []; // inside: { we don't care, here }
  18901. this._bindings = []; // inside: Array< PropertyBinding >
  18902. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18903. const scope = this;
  18904. this.stats = {
  18905. objects: {
  18906. get total() {
  18907. return scope._objects.length;
  18908. },
  18909. get inUse() {
  18910. return this.total - scope.nCachedObjects_;
  18911. }
  18912. },
  18913. get bindingsPerObject() {
  18914. return scope._bindings.length;
  18915. }
  18916. };
  18917. }
  18918. add() {
  18919. const objects = this._objects,
  18920. indicesByUUID = this._indicesByUUID,
  18921. paths = this._paths,
  18922. parsedPaths = this._parsedPaths,
  18923. bindings = this._bindings,
  18924. nBindings = bindings.length;
  18925. let knownObject = undefined,
  18926. nObjects = objects.length,
  18927. nCachedObjects = this.nCachedObjects_;
  18928. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18929. const object = arguments[ i ],
  18930. uuid = object.uuid;
  18931. let index = indicesByUUID[ uuid ];
  18932. if ( index === undefined ) {
  18933. // unknown object -> add it to the ACTIVE region
  18934. index = nObjects ++;
  18935. indicesByUUID[ uuid ] = index;
  18936. objects.push( object );
  18937. // accounting is done, now do the same for all bindings
  18938. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18939. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18940. }
  18941. } else if ( index < nCachedObjects ) {
  18942. knownObject = objects[ index ];
  18943. // move existing object to the ACTIVE region
  18944. const firstActiveIndex = -- nCachedObjects,
  18945. lastCachedObject = objects[ firstActiveIndex ];
  18946. indicesByUUID[ lastCachedObject.uuid ] = index;
  18947. objects[ index ] = lastCachedObject;
  18948. indicesByUUID[ uuid ] = firstActiveIndex;
  18949. objects[ firstActiveIndex ] = object;
  18950. // accounting is done, now do the same for all bindings
  18951. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18952. const bindingsForPath = bindings[ j ],
  18953. lastCached = bindingsForPath[ firstActiveIndex ];
  18954. let binding = bindingsForPath[ index ];
  18955. bindingsForPath[ index ] = lastCached;
  18956. if ( binding === undefined ) {
  18957. // since we do not bother to create new bindings
  18958. // for objects that are cached, the binding may
  18959. // or may not exist
  18960. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  18961. }
  18962. bindingsForPath[ firstActiveIndex ] = binding;
  18963. }
  18964. } else if ( objects[ index ] !== knownObject ) {
  18965. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  18966. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  18967. } // else the object is already where we want it to be
  18968. } // for arguments
  18969. this.nCachedObjects_ = nCachedObjects;
  18970. }
  18971. remove() {
  18972. const objects = this._objects,
  18973. indicesByUUID = this._indicesByUUID,
  18974. bindings = this._bindings,
  18975. nBindings = bindings.length;
  18976. let nCachedObjects = this.nCachedObjects_;
  18977. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18978. const object = arguments[ i ],
  18979. uuid = object.uuid,
  18980. index = indicesByUUID[ uuid ];
  18981. if ( index !== undefined && index >= nCachedObjects ) {
  18982. // move existing object into the CACHED region
  18983. const lastCachedIndex = nCachedObjects ++,
  18984. firstActiveObject = objects[ lastCachedIndex ];
  18985. indicesByUUID[ firstActiveObject.uuid ] = index;
  18986. objects[ index ] = firstActiveObject;
  18987. indicesByUUID[ uuid ] = lastCachedIndex;
  18988. objects[ lastCachedIndex ] = object;
  18989. // accounting is done, now do the same for all bindings
  18990. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18991. const bindingsForPath = bindings[ j ],
  18992. firstActive = bindingsForPath[ lastCachedIndex ],
  18993. binding = bindingsForPath[ index ];
  18994. bindingsForPath[ index ] = firstActive;
  18995. bindingsForPath[ lastCachedIndex ] = binding;
  18996. }
  18997. }
  18998. } // for arguments
  18999. this.nCachedObjects_ = nCachedObjects;
  19000. }
  19001. // remove & forget
  19002. uncache() {
  19003. const objects = this._objects,
  19004. indicesByUUID = this._indicesByUUID,
  19005. bindings = this._bindings,
  19006. nBindings = bindings.length;
  19007. let nCachedObjects = this.nCachedObjects_,
  19008. nObjects = objects.length;
  19009. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19010. const object = arguments[ i ],
  19011. uuid = object.uuid,
  19012. index = indicesByUUID[ uuid ];
  19013. if ( index !== undefined ) {
  19014. delete indicesByUUID[ uuid ];
  19015. if ( index < nCachedObjects ) {
  19016. // object is cached, shrink the CACHED region
  19017. const firstActiveIndex = -- nCachedObjects,
  19018. lastCachedObject = objects[ firstActiveIndex ],
  19019. lastIndex = -- nObjects,
  19020. lastObject = objects[ lastIndex ];
  19021. // last cached object takes this object's place
  19022. indicesByUUID[ lastCachedObject.uuid ] = index;
  19023. objects[ index ] = lastCachedObject;
  19024. // last object goes to the activated slot and pop
  19025. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19026. objects[ firstActiveIndex ] = lastObject;
  19027. objects.pop();
  19028. // accounting is done, now do the same for all bindings
  19029. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19030. const bindingsForPath = bindings[ j ],
  19031. lastCached = bindingsForPath[ firstActiveIndex ],
  19032. last = bindingsForPath[ lastIndex ];
  19033. bindingsForPath[ index ] = lastCached;
  19034. bindingsForPath[ firstActiveIndex ] = last;
  19035. bindingsForPath.pop();
  19036. }
  19037. } else {
  19038. // object is active, just swap with the last and pop
  19039. const lastIndex = -- nObjects,
  19040. lastObject = objects[ lastIndex ];
  19041. if ( lastIndex > 0 ) {
  19042. indicesByUUID[ lastObject.uuid ] = index;
  19043. }
  19044. objects[ index ] = lastObject;
  19045. objects.pop();
  19046. // accounting is done, now do the same for all bindings
  19047. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19048. const bindingsForPath = bindings[ j ];
  19049. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19050. bindingsForPath.pop();
  19051. }
  19052. } // cached or active
  19053. } // if object is known
  19054. } // for arguments
  19055. this.nCachedObjects_ = nCachedObjects;
  19056. }
  19057. // Internal interface used by befriended PropertyBinding.Composite:
  19058. subscribe_( path, parsedPath ) {
  19059. // returns an array of bindings for the given path that is changed
  19060. // according to the contained objects in the group
  19061. const indicesByPath = this._bindingsIndicesByPath;
  19062. let index = indicesByPath[ path ];
  19063. const bindings = this._bindings;
  19064. if ( index !== undefined ) return bindings[ index ];
  19065. const paths = this._paths,
  19066. parsedPaths = this._parsedPaths,
  19067. objects = this._objects,
  19068. nObjects = objects.length,
  19069. nCachedObjects = this.nCachedObjects_,
  19070. bindingsForPath = new Array( nObjects );
  19071. index = bindings.length;
  19072. indicesByPath[ path ] = index;
  19073. paths.push( path );
  19074. parsedPaths.push( parsedPath );
  19075. bindings.push( bindingsForPath );
  19076. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19077. const object = objects[ i ];
  19078. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19079. }
  19080. return bindingsForPath;
  19081. }
  19082. unsubscribe_( path ) {
  19083. // tells the group to forget about a property path and no longer
  19084. // update the array previously obtained with 'subscribe_'
  19085. const indicesByPath = this._bindingsIndicesByPath,
  19086. index = indicesByPath[ path ];
  19087. if ( index !== undefined ) {
  19088. const paths = this._paths,
  19089. parsedPaths = this._parsedPaths,
  19090. bindings = this._bindings,
  19091. lastBindingsIndex = bindings.length - 1,
  19092. lastBindings = bindings[ lastBindingsIndex ],
  19093. lastBindingsPath = path[ lastBindingsIndex ];
  19094. indicesByPath[ lastBindingsPath ] = index;
  19095. bindings[ index ] = lastBindings;
  19096. bindings.pop();
  19097. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19098. parsedPaths.pop();
  19099. paths[ index ] = paths[ lastBindingsIndex ];
  19100. paths.pop();
  19101. }
  19102. }
  19103. }
  19104. class AnimationAction {
  19105. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19106. this._mixer = mixer;
  19107. this._clip = clip;
  19108. this._localRoot = localRoot;
  19109. this.blendMode = blendMode;
  19110. const tracks = clip.tracks,
  19111. nTracks = tracks.length,
  19112. interpolants = new Array( nTracks );
  19113. const interpolantSettings = {
  19114. endingStart: ZeroCurvatureEnding,
  19115. endingEnd: ZeroCurvatureEnding
  19116. };
  19117. for ( let i = 0; i !== nTracks; ++ i ) {
  19118. const interpolant = tracks[ i ].createInterpolant( null );
  19119. interpolants[ i ] = interpolant;
  19120. interpolant.settings = interpolantSettings;
  19121. }
  19122. this._interpolantSettings = interpolantSettings;
  19123. this._interpolants = interpolants; // bound by the mixer
  19124. // inside: PropertyMixer (managed by the mixer)
  19125. this._propertyBindings = new Array( nTracks );
  19126. this._cacheIndex = null; // for the memory manager
  19127. this._byClipCacheIndex = null; // for the memory manager
  19128. this._timeScaleInterpolant = null;
  19129. this._weightInterpolant = null;
  19130. this.loop = LoopRepeat;
  19131. this._loopCount = - 1;
  19132. // global mixer time when the action is to be started
  19133. // it's set back to 'null' upon start of the action
  19134. this._startTime = null;
  19135. // scaled local time of the action
  19136. // gets clamped or wrapped to 0..clip.duration according to loop
  19137. this.time = 0;
  19138. this.timeScale = 1;
  19139. this._effectiveTimeScale = 1;
  19140. this.weight = 1;
  19141. this._effectiveWeight = 1;
  19142. this.repetitions = Infinity; // no. of repetitions when looping
  19143. this.paused = false; // true -> zero effective time scale
  19144. this.enabled = true; // false -> zero effective weight
  19145. this.clampWhenFinished = false;// keep feeding the last frame?
  19146. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19147. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19148. }
  19149. // State & Scheduling
  19150. play() {
  19151. this._mixer._activateAction( this );
  19152. return this;
  19153. }
  19154. stop() {
  19155. this._mixer._deactivateAction( this );
  19156. return this.reset();
  19157. }
  19158. reset() {
  19159. this.paused = false;
  19160. this.enabled = true;
  19161. this.time = 0; // restart clip
  19162. this._loopCount = - 1;// forget previous loops
  19163. this._startTime = null;// forget scheduling
  19164. return this.stopFading().stopWarping();
  19165. }
  19166. isRunning() {
  19167. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19168. this._startTime === null && this._mixer._isActiveAction( this );
  19169. }
  19170. // return true when play has been called
  19171. isScheduled() {
  19172. return this._mixer._isActiveAction( this );
  19173. }
  19174. startAt( time ) {
  19175. this._startTime = time;
  19176. return this;
  19177. }
  19178. setLoop( mode, repetitions ) {
  19179. this.loop = mode;
  19180. this.repetitions = repetitions;
  19181. return this;
  19182. }
  19183. // Weight
  19184. // set the weight stopping any scheduled fading
  19185. // although .enabled = false yields an effective weight of zero, this
  19186. // method does *not* change .enabled, because it would be confusing
  19187. setEffectiveWeight( weight ) {
  19188. this.weight = weight;
  19189. // note: same logic as when updated at runtime
  19190. this._effectiveWeight = this.enabled ? weight : 0;
  19191. return this.stopFading();
  19192. }
  19193. // return the weight considering fading and .enabled
  19194. getEffectiveWeight() {
  19195. return this._effectiveWeight;
  19196. }
  19197. fadeIn( duration ) {
  19198. return this._scheduleFading( duration, 0, 1 );
  19199. }
  19200. fadeOut( duration ) {
  19201. return this._scheduleFading( duration, 1, 0 );
  19202. }
  19203. crossFadeFrom( fadeOutAction, duration, warp ) {
  19204. fadeOutAction.fadeOut( duration );
  19205. this.fadeIn( duration );
  19206. if ( warp ) {
  19207. const fadeInDuration = this._clip.duration,
  19208. fadeOutDuration = fadeOutAction._clip.duration,
  19209. startEndRatio = fadeOutDuration / fadeInDuration,
  19210. endStartRatio = fadeInDuration / fadeOutDuration;
  19211. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19212. this.warp( endStartRatio, 1.0, duration );
  19213. }
  19214. return this;
  19215. }
  19216. crossFadeTo( fadeInAction, duration, warp ) {
  19217. return fadeInAction.crossFadeFrom( this, duration, warp );
  19218. }
  19219. stopFading() {
  19220. const weightInterpolant = this._weightInterpolant;
  19221. if ( weightInterpolant !== null ) {
  19222. this._weightInterpolant = null;
  19223. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19224. }
  19225. return this;
  19226. }
  19227. // Time Scale Control
  19228. // set the time scale stopping any scheduled warping
  19229. // although .paused = true yields an effective time scale of zero, this
  19230. // method does *not* change .paused, because it would be confusing
  19231. setEffectiveTimeScale( timeScale ) {
  19232. this.timeScale = timeScale;
  19233. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19234. return this.stopWarping();
  19235. }
  19236. // return the time scale considering warping and .paused
  19237. getEffectiveTimeScale() {
  19238. return this._effectiveTimeScale;
  19239. }
  19240. setDuration( duration ) {
  19241. this.timeScale = this._clip.duration / duration;
  19242. return this.stopWarping();
  19243. }
  19244. syncWith( action ) {
  19245. this.time = action.time;
  19246. this.timeScale = action.timeScale;
  19247. return this.stopWarping();
  19248. }
  19249. halt( duration ) {
  19250. return this.warp( this._effectiveTimeScale, 0, duration );
  19251. }
  19252. warp( startTimeScale, endTimeScale, duration ) {
  19253. const mixer = this._mixer,
  19254. now = mixer.time,
  19255. timeScale = this.timeScale;
  19256. let interpolant = this._timeScaleInterpolant;
  19257. if ( interpolant === null ) {
  19258. interpolant = mixer._lendControlInterpolant();
  19259. this._timeScaleInterpolant = interpolant;
  19260. }
  19261. const times = interpolant.parameterPositions,
  19262. values = interpolant.sampleValues;
  19263. times[ 0 ] = now;
  19264. times[ 1 ] = now + duration;
  19265. values[ 0 ] = startTimeScale / timeScale;
  19266. values[ 1 ] = endTimeScale / timeScale;
  19267. return this;
  19268. }
  19269. stopWarping() {
  19270. const timeScaleInterpolant = this._timeScaleInterpolant;
  19271. if ( timeScaleInterpolant !== null ) {
  19272. this._timeScaleInterpolant = null;
  19273. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19274. }
  19275. return this;
  19276. }
  19277. // Object Accessors
  19278. getMixer() {
  19279. return this._mixer;
  19280. }
  19281. getClip() {
  19282. return this._clip;
  19283. }
  19284. getRoot() {
  19285. return this._localRoot || this._mixer._root;
  19286. }
  19287. // Interna
  19288. _update( time, deltaTime, timeDirection, accuIndex ) {
  19289. // called by the mixer
  19290. if ( ! this.enabled ) {
  19291. // call ._updateWeight() to update ._effectiveWeight
  19292. this._updateWeight( time );
  19293. return;
  19294. }
  19295. const startTime = this._startTime;
  19296. if ( startTime !== null ) {
  19297. // check for scheduled start of action
  19298. const timeRunning = ( time - startTime ) * timeDirection;
  19299. if ( timeRunning < 0 || timeDirection === 0 ) {
  19300. deltaTime = 0;
  19301. } else {
  19302. this._startTime = null; // unschedule
  19303. deltaTime = timeDirection * timeRunning;
  19304. }
  19305. }
  19306. // apply time scale and advance time
  19307. deltaTime *= this._updateTimeScale( time );
  19308. const clipTime = this._updateTime( deltaTime );
  19309. // note: _updateTime may disable the action resulting in
  19310. // an effective weight of 0
  19311. const weight = this._updateWeight( time );
  19312. if ( weight > 0 ) {
  19313. const interpolants = this._interpolants;
  19314. const propertyMixers = this._propertyBindings;
  19315. switch ( this.blendMode ) {
  19316. case AdditiveAnimationBlendMode:
  19317. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19318. interpolants[ j ].evaluate( clipTime );
  19319. propertyMixers[ j ].accumulateAdditive( weight );
  19320. }
  19321. break;
  19322. case NormalAnimationBlendMode:
  19323. default:
  19324. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19325. interpolants[ j ].evaluate( clipTime );
  19326. propertyMixers[ j ].accumulate( accuIndex, weight );
  19327. }
  19328. }
  19329. }
  19330. }
  19331. _updateWeight( time ) {
  19332. let weight = 0;
  19333. if ( this.enabled ) {
  19334. weight = this.weight;
  19335. const interpolant = this._weightInterpolant;
  19336. if ( interpolant !== null ) {
  19337. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19338. weight *= interpolantValue;
  19339. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19340. this.stopFading();
  19341. if ( interpolantValue === 0 ) {
  19342. // faded out, disable
  19343. this.enabled = false;
  19344. }
  19345. }
  19346. }
  19347. }
  19348. this._effectiveWeight = weight;
  19349. return weight;
  19350. }
  19351. _updateTimeScale( time ) {
  19352. let timeScale = 0;
  19353. if ( ! this.paused ) {
  19354. timeScale = this.timeScale;
  19355. const interpolant = this._timeScaleInterpolant;
  19356. if ( interpolant !== null ) {
  19357. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19358. timeScale *= interpolantValue;
  19359. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19360. this.stopWarping();
  19361. if ( timeScale === 0 ) {
  19362. // motion has halted, pause
  19363. this.paused = true;
  19364. } else {
  19365. // warp done - apply final time scale
  19366. this.timeScale = timeScale;
  19367. }
  19368. }
  19369. }
  19370. }
  19371. this._effectiveTimeScale = timeScale;
  19372. return timeScale;
  19373. }
  19374. _updateTime( deltaTime ) {
  19375. const duration = this._clip.duration;
  19376. const loop = this.loop;
  19377. let time = this.time + deltaTime;
  19378. let loopCount = this._loopCount;
  19379. const pingPong = ( loop === LoopPingPong );
  19380. if ( deltaTime === 0 ) {
  19381. if ( loopCount === - 1 ) return time;
  19382. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19383. }
  19384. if ( loop === LoopOnce ) {
  19385. if ( loopCount === - 1 ) {
  19386. // just started
  19387. this._loopCount = 0;
  19388. this._setEndings( true, true, false );
  19389. }
  19390. handle_stop: {
  19391. if ( time >= duration ) {
  19392. time = duration;
  19393. } else if ( time < 0 ) {
  19394. time = 0;
  19395. } else {
  19396. this.time = time;
  19397. break handle_stop;
  19398. }
  19399. if ( this.clampWhenFinished ) this.paused = true;
  19400. else this.enabled = false;
  19401. this.time = time;
  19402. this._mixer.dispatchEvent( {
  19403. type: 'finished', action: this,
  19404. direction: deltaTime < 0 ? - 1 : 1
  19405. } );
  19406. }
  19407. } else { // repetitive Repeat or PingPong
  19408. if ( loopCount === - 1 ) {
  19409. // just started
  19410. if ( deltaTime >= 0 ) {
  19411. loopCount = 0;
  19412. this._setEndings( true, this.repetitions === 0, pingPong );
  19413. } else {
  19414. // when looping in reverse direction, the initial
  19415. // transition through zero counts as a repetition,
  19416. // so leave loopCount at -1
  19417. this._setEndings( this.repetitions === 0, true, pingPong );
  19418. }
  19419. }
  19420. if ( time >= duration || time < 0 ) {
  19421. // wrap around
  19422. const loopDelta = Math.floor( time / duration ); // signed
  19423. time -= duration * loopDelta;
  19424. loopCount += Math.abs( loopDelta );
  19425. const pending = this.repetitions - loopCount;
  19426. if ( pending <= 0 ) {
  19427. // have to stop (switch state, clamp time, fire event)
  19428. if ( this.clampWhenFinished ) this.paused = true;
  19429. else this.enabled = false;
  19430. time = deltaTime > 0 ? duration : 0;
  19431. this.time = time;
  19432. this._mixer.dispatchEvent( {
  19433. type: 'finished', action: this,
  19434. direction: deltaTime > 0 ? 1 : - 1
  19435. } );
  19436. } else {
  19437. // keep running
  19438. if ( pending === 1 ) {
  19439. // entering the last round
  19440. const atStart = deltaTime < 0;
  19441. this._setEndings( atStart, ! atStart, pingPong );
  19442. } else {
  19443. this._setEndings( false, false, pingPong );
  19444. }
  19445. this._loopCount = loopCount;
  19446. this.time = time;
  19447. this._mixer.dispatchEvent( {
  19448. type: 'loop', action: this, loopDelta: loopDelta
  19449. } );
  19450. }
  19451. } else {
  19452. this.time = time;
  19453. }
  19454. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19455. // invert time for the "pong round"
  19456. return duration - time;
  19457. }
  19458. }
  19459. return time;
  19460. }
  19461. _setEndings( atStart, atEnd, pingPong ) {
  19462. const settings = this._interpolantSettings;
  19463. if ( pingPong ) {
  19464. settings.endingStart = ZeroSlopeEnding;
  19465. settings.endingEnd = ZeroSlopeEnding;
  19466. } else {
  19467. // assuming for LoopOnce atStart == atEnd == true
  19468. if ( atStart ) {
  19469. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19470. } else {
  19471. settings.endingStart = WrapAroundEnding;
  19472. }
  19473. if ( atEnd ) {
  19474. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19475. } else {
  19476. settings.endingEnd = WrapAroundEnding;
  19477. }
  19478. }
  19479. }
  19480. _scheduleFading( duration, weightNow, weightThen ) {
  19481. const mixer = this._mixer, now = mixer.time;
  19482. let interpolant = this._weightInterpolant;
  19483. if ( interpolant === null ) {
  19484. interpolant = mixer._lendControlInterpolant();
  19485. this._weightInterpolant = interpolant;
  19486. }
  19487. const times = interpolant.parameterPositions,
  19488. values = interpolant.sampleValues;
  19489. times[ 0 ] = now;
  19490. values[ 0 ] = weightNow;
  19491. times[ 1 ] = now + duration;
  19492. values[ 1 ] = weightThen;
  19493. return this;
  19494. }
  19495. }
  19496. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19497. class AnimationMixer extends EventDispatcher {
  19498. constructor( root ) {
  19499. super();
  19500. this._root = root;
  19501. this._initMemoryManager();
  19502. this._accuIndex = 0;
  19503. this.time = 0;
  19504. this.timeScale = 1.0;
  19505. }
  19506. _bindAction( action, prototypeAction ) {
  19507. const root = action._localRoot || this._root,
  19508. tracks = action._clip.tracks,
  19509. nTracks = tracks.length,
  19510. bindings = action._propertyBindings,
  19511. interpolants = action._interpolants,
  19512. rootUuid = root.uuid,
  19513. bindingsByRoot = this._bindingsByRootAndName;
  19514. let bindingsByName = bindingsByRoot[ rootUuid ];
  19515. if ( bindingsByName === undefined ) {
  19516. bindingsByName = {};
  19517. bindingsByRoot[ rootUuid ] = bindingsByName;
  19518. }
  19519. for ( let i = 0; i !== nTracks; ++ i ) {
  19520. const track = tracks[ i ],
  19521. trackName = track.name;
  19522. let binding = bindingsByName[ trackName ];
  19523. if ( binding !== undefined ) {
  19524. ++ binding.referenceCount;
  19525. bindings[ i ] = binding;
  19526. } else {
  19527. binding = bindings[ i ];
  19528. if ( binding !== undefined ) {
  19529. // existing binding, make sure the cache knows
  19530. if ( binding._cacheIndex === null ) {
  19531. ++ binding.referenceCount;
  19532. this._addInactiveBinding( binding, rootUuid, trackName );
  19533. }
  19534. continue;
  19535. }
  19536. const path = prototypeAction && prototypeAction.
  19537. _propertyBindings[ i ].binding.parsedPath;
  19538. binding = new PropertyMixer(
  19539. PropertyBinding.create( root, trackName, path ),
  19540. track.ValueTypeName, track.getValueSize() );
  19541. ++ binding.referenceCount;
  19542. this._addInactiveBinding( binding, rootUuid, trackName );
  19543. bindings[ i ] = binding;
  19544. }
  19545. interpolants[ i ].resultBuffer = binding.buffer;
  19546. }
  19547. }
  19548. _activateAction( action ) {
  19549. if ( ! this._isActiveAction( action ) ) {
  19550. if ( action._cacheIndex === null ) {
  19551. // this action has been forgotten by the cache, but the user
  19552. // appears to be still using it -> rebind
  19553. const rootUuid = ( action._localRoot || this._root ).uuid,
  19554. clipUuid = action._clip.uuid,
  19555. actionsForClip = this._actionsByClip[ clipUuid ];
  19556. this._bindAction( action,
  19557. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19558. this._addInactiveAction( action, clipUuid, rootUuid );
  19559. }
  19560. const bindings = action._propertyBindings;
  19561. // increment reference counts / sort out state
  19562. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19563. const binding = bindings[ i ];
  19564. if ( binding.useCount ++ === 0 ) {
  19565. this._lendBinding( binding );
  19566. binding.saveOriginalState();
  19567. }
  19568. }
  19569. this._lendAction( action );
  19570. }
  19571. }
  19572. _deactivateAction( action ) {
  19573. if ( this._isActiveAction( action ) ) {
  19574. const bindings = action._propertyBindings;
  19575. // decrement reference counts / sort out state
  19576. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19577. const binding = bindings[ i ];
  19578. if ( -- binding.useCount === 0 ) {
  19579. binding.restoreOriginalState();
  19580. this._takeBackBinding( binding );
  19581. }
  19582. }
  19583. this._takeBackAction( action );
  19584. }
  19585. }
  19586. // Memory manager
  19587. _initMemoryManager() {
  19588. this._actions = []; // 'nActiveActions' followed by inactive ones
  19589. this._nActiveActions = 0;
  19590. this._actionsByClip = {};
  19591. // inside:
  19592. // {
  19593. // knownActions: Array< AnimationAction > - used as prototypes
  19594. // actionByRoot: AnimationAction - lookup
  19595. // }
  19596. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19597. this._nActiveBindings = 0;
  19598. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19599. this._controlInterpolants = []; // same game as above
  19600. this._nActiveControlInterpolants = 0;
  19601. const scope = this;
  19602. this.stats = {
  19603. actions: {
  19604. get total() {
  19605. return scope._actions.length;
  19606. },
  19607. get inUse() {
  19608. return scope._nActiveActions;
  19609. }
  19610. },
  19611. bindings: {
  19612. get total() {
  19613. return scope._bindings.length;
  19614. },
  19615. get inUse() {
  19616. return scope._nActiveBindings;
  19617. }
  19618. },
  19619. controlInterpolants: {
  19620. get total() {
  19621. return scope._controlInterpolants.length;
  19622. },
  19623. get inUse() {
  19624. return scope._nActiveControlInterpolants;
  19625. }
  19626. }
  19627. };
  19628. }
  19629. // Memory management for AnimationAction objects
  19630. _isActiveAction( action ) {
  19631. const index = action._cacheIndex;
  19632. return index !== null && index < this._nActiveActions;
  19633. }
  19634. _addInactiveAction( action, clipUuid, rootUuid ) {
  19635. const actions = this._actions,
  19636. actionsByClip = this._actionsByClip;
  19637. let actionsForClip = actionsByClip[ clipUuid ];
  19638. if ( actionsForClip === undefined ) {
  19639. actionsForClip = {
  19640. knownActions: [ action ],
  19641. actionByRoot: {}
  19642. };
  19643. action._byClipCacheIndex = 0;
  19644. actionsByClip[ clipUuid ] = actionsForClip;
  19645. } else {
  19646. const knownActions = actionsForClip.knownActions;
  19647. action._byClipCacheIndex = knownActions.length;
  19648. knownActions.push( action );
  19649. }
  19650. action._cacheIndex = actions.length;
  19651. actions.push( action );
  19652. actionsForClip.actionByRoot[ rootUuid ] = action;
  19653. }
  19654. _removeInactiveAction( action ) {
  19655. const actions = this._actions,
  19656. lastInactiveAction = actions[ actions.length - 1 ],
  19657. cacheIndex = action._cacheIndex;
  19658. lastInactiveAction._cacheIndex = cacheIndex;
  19659. actions[ cacheIndex ] = lastInactiveAction;
  19660. actions.pop();
  19661. action._cacheIndex = null;
  19662. const clipUuid = action._clip.uuid,
  19663. actionsByClip = this._actionsByClip,
  19664. actionsForClip = actionsByClip[ clipUuid ],
  19665. knownActionsForClip = actionsForClip.knownActions,
  19666. lastKnownAction =
  19667. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19668. byClipCacheIndex = action._byClipCacheIndex;
  19669. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19670. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19671. knownActionsForClip.pop();
  19672. action._byClipCacheIndex = null;
  19673. const actionByRoot = actionsForClip.actionByRoot,
  19674. rootUuid = ( action._localRoot || this._root ).uuid;
  19675. delete actionByRoot[ rootUuid ];
  19676. if ( knownActionsForClip.length === 0 ) {
  19677. delete actionsByClip[ clipUuid ];
  19678. }
  19679. this._removeInactiveBindingsForAction( action );
  19680. }
  19681. _removeInactiveBindingsForAction( action ) {
  19682. const bindings = action._propertyBindings;
  19683. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19684. const binding = bindings[ i ];
  19685. if ( -- binding.referenceCount === 0 ) {
  19686. this._removeInactiveBinding( binding );
  19687. }
  19688. }
  19689. }
  19690. _lendAction( action ) {
  19691. // [ active actions | inactive actions ]
  19692. // [ active actions >| inactive actions ]
  19693. // s a
  19694. // <-swap->
  19695. // a s
  19696. const actions = this._actions,
  19697. prevIndex = action._cacheIndex,
  19698. lastActiveIndex = this._nActiveActions ++,
  19699. firstInactiveAction = actions[ lastActiveIndex ];
  19700. action._cacheIndex = lastActiveIndex;
  19701. actions[ lastActiveIndex ] = action;
  19702. firstInactiveAction._cacheIndex = prevIndex;
  19703. actions[ prevIndex ] = firstInactiveAction;
  19704. }
  19705. _takeBackAction( action ) {
  19706. // [ active actions | inactive actions ]
  19707. // [ active actions |< inactive actions ]
  19708. // a s
  19709. // <-swap->
  19710. // s a
  19711. const actions = this._actions,
  19712. prevIndex = action._cacheIndex,
  19713. firstInactiveIndex = -- this._nActiveActions,
  19714. lastActiveAction = actions[ firstInactiveIndex ];
  19715. action._cacheIndex = firstInactiveIndex;
  19716. actions[ firstInactiveIndex ] = action;
  19717. lastActiveAction._cacheIndex = prevIndex;
  19718. actions[ prevIndex ] = lastActiveAction;
  19719. }
  19720. // Memory management for PropertyMixer objects
  19721. _addInactiveBinding( binding, rootUuid, trackName ) {
  19722. const bindingsByRoot = this._bindingsByRootAndName,
  19723. bindings = this._bindings;
  19724. let bindingByName = bindingsByRoot[ rootUuid ];
  19725. if ( bindingByName === undefined ) {
  19726. bindingByName = {};
  19727. bindingsByRoot[ rootUuid ] = bindingByName;
  19728. }
  19729. bindingByName[ trackName ] = binding;
  19730. binding._cacheIndex = bindings.length;
  19731. bindings.push( binding );
  19732. }
  19733. _removeInactiveBinding( binding ) {
  19734. const bindings = this._bindings,
  19735. propBinding = binding.binding,
  19736. rootUuid = propBinding.rootNode.uuid,
  19737. trackName = propBinding.path,
  19738. bindingsByRoot = this._bindingsByRootAndName,
  19739. bindingByName = bindingsByRoot[ rootUuid ],
  19740. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19741. cacheIndex = binding._cacheIndex;
  19742. lastInactiveBinding._cacheIndex = cacheIndex;
  19743. bindings[ cacheIndex ] = lastInactiveBinding;
  19744. bindings.pop();
  19745. delete bindingByName[ trackName ];
  19746. if ( Object.keys( bindingByName ).length === 0 ) {
  19747. delete bindingsByRoot[ rootUuid ];
  19748. }
  19749. }
  19750. _lendBinding( binding ) {
  19751. const bindings = this._bindings,
  19752. prevIndex = binding._cacheIndex,
  19753. lastActiveIndex = this._nActiveBindings ++,
  19754. firstInactiveBinding = bindings[ lastActiveIndex ];
  19755. binding._cacheIndex = lastActiveIndex;
  19756. bindings[ lastActiveIndex ] = binding;
  19757. firstInactiveBinding._cacheIndex = prevIndex;
  19758. bindings[ prevIndex ] = firstInactiveBinding;
  19759. }
  19760. _takeBackBinding( binding ) {
  19761. const bindings = this._bindings,
  19762. prevIndex = binding._cacheIndex,
  19763. firstInactiveIndex = -- this._nActiveBindings,
  19764. lastActiveBinding = bindings[ firstInactiveIndex ];
  19765. binding._cacheIndex = firstInactiveIndex;
  19766. bindings[ firstInactiveIndex ] = binding;
  19767. lastActiveBinding._cacheIndex = prevIndex;
  19768. bindings[ prevIndex ] = lastActiveBinding;
  19769. }
  19770. // Memory management of Interpolants for weight and time scale
  19771. _lendControlInterpolant() {
  19772. const interpolants = this._controlInterpolants,
  19773. lastActiveIndex = this._nActiveControlInterpolants ++;
  19774. let interpolant = interpolants[ lastActiveIndex ];
  19775. if ( interpolant === undefined ) {
  19776. interpolant = new LinearInterpolant(
  19777. new Float32Array( 2 ), new Float32Array( 2 ),
  19778. 1, _controlInterpolantsResultBuffer );
  19779. interpolant.__cacheIndex = lastActiveIndex;
  19780. interpolants[ lastActiveIndex ] = interpolant;
  19781. }
  19782. return interpolant;
  19783. }
  19784. _takeBackControlInterpolant( interpolant ) {
  19785. const interpolants = this._controlInterpolants,
  19786. prevIndex = interpolant.__cacheIndex,
  19787. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19788. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19789. interpolant.__cacheIndex = firstInactiveIndex;
  19790. interpolants[ firstInactiveIndex ] = interpolant;
  19791. lastActiveInterpolant.__cacheIndex = prevIndex;
  19792. interpolants[ prevIndex ] = lastActiveInterpolant;
  19793. }
  19794. // return an action for a clip optionally using a custom root target
  19795. // object (this method allocates a lot of dynamic memory in case a
  19796. // previously unknown clip/root combination is specified)
  19797. clipAction( clip, optionalRoot, blendMode ) {
  19798. const root = optionalRoot || this._root,
  19799. rootUuid = root.uuid;
  19800. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19801. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19802. const actionsForClip = this._actionsByClip[ clipUuid ];
  19803. let prototypeAction = null;
  19804. if ( blendMode === undefined ) {
  19805. if ( clipObject !== null ) {
  19806. blendMode = clipObject.blendMode;
  19807. } else {
  19808. blendMode = NormalAnimationBlendMode;
  19809. }
  19810. }
  19811. if ( actionsForClip !== undefined ) {
  19812. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19813. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19814. return existingAction;
  19815. }
  19816. // we know the clip, so we don't have to parse all
  19817. // the bindings again but can just copy
  19818. prototypeAction = actionsForClip.knownActions[ 0 ];
  19819. // also, take the clip from the prototype action
  19820. if ( clipObject === null )
  19821. clipObject = prototypeAction._clip;
  19822. }
  19823. // clip must be known when specified via string
  19824. if ( clipObject === null ) return null;
  19825. // allocate all resources required to run it
  19826. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19827. this._bindAction( newAction, prototypeAction );
  19828. // and make the action known to the memory manager
  19829. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19830. return newAction;
  19831. }
  19832. // get an existing action
  19833. existingAction( clip, optionalRoot ) {
  19834. const root = optionalRoot || this._root,
  19835. rootUuid = root.uuid,
  19836. clipObject = typeof clip === 'string' ?
  19837. AnimationClip.findByName( root, clip ) : clip,
  19838. clipUuid = clipObject ? clipObject.uuid : clip,
  19839. actionsForClip = this._actionsByClip[ clipUuid ];
  19840. if ( actionsForClip !== undefined ) {
  19841. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19842. }
  19843. return null;
  19844. }
  19845. // deactivates all previously scheduled actions
  19846. stopAllAction() {
  19847. const actions = this._actions,
  19848. nActions = this._nActiveActions;
  19849. for ( let i = nActions - 1; i >= 0; -- i ) {
  19850. actions[ i ].stop();
  19851. }
  19852. return this;
  19853. }
  19854. // advance the time and update apply the animation
  19855. update( deltaTime ) {
  19856. deltaTime *= this.timeScale;
  19857. const actions = this._actions,
  19858. nActions = this._nActiveActions,
  19859. time = this.time += deltaTime,
  19860. timeDirection = Math.sign( deltaTime ),
  19861. accuIndex = this._accuIndex ^= 1;
  19862. // run active actions
  19863. for ( let i = 0; i !== nActions; ++ i ) {
  19864. const action = actions[ i ];
  19865. action._update( time, deltaTime, timeDirection, accuIndex );
  19866. }
  19867. // update scene graph
  19868. const bindings = this._bindings,
  19869. nBindings = this._nActiveBindings;
  19870. for ( let i = 0; i !== nBindings; ++ i ) {
  19871. bindings[ i ].apply( accuIndex );
  19872. }
  19873. return this;
  19874. }
  19875. // Allows you to seek to a specific time in an animation.
  19876. setTime( timeInSeconds ) {
  19877. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19878. for ( let i = 0; i < this._actions.length; i ++ ) {
  19879. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19880. }
  19881. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19882. }
  19883. // return this mixer's root target object
  19884. getRoot() {
  19885. return this._root;
  19886. }
  19887. // free all resources specific to a particular clip
  19888. uncacheClip( clip ) {
  19889. const actions = this._actions,
  19890. clipUuid = clip.uuid,
  19891. actionsByClip = this._actionsByClip,
  19892. actionsForClip = actionsByClip[ clipUuid ];
  19893. if ( actionsForClip !== undefined ) {
  19894. // note: just calling _removeInactiveAction would mess up the
  19895. // iteration state and also require updating the state we can
  19896. // just throw away
  19897. const actionsToRemove = actionsForClip.knownActions;
  19898. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19899. const action = actionsToRemove[ i ];
  19900. this._deactivateAction( action );
  19901. const cacheIndex = action._cacheIndex,
  19902. lastInactiveAction = actions[ actions.length - 1 ];
  19903. action._cacheIndex = null;
  19904. action._byClipCacheIndex = null;
  19905. lastInactiveAction._cacheIndex = cacheIndex;
  19906. actions[ cacheIndex ] = lastInactiveAction;
  19907. actions.pop();
  19908. this._removeInactiveBindingsForAction( action );
  19909. }
  19910. delete actionsByClip[ clipUuid ];
  19911. }
  19912. }
  19913. // free all resources specific to a particular root target object
  19914. uncacheRoot( root ) {
  19915. const rootUuid = root.uuid,
  19916. actionsByClip = this._actionsByClip;
  19917. for ( const clipUuid in actionsByClip ) {
  19918. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19919. action = actionByRoot[ rootUuid ];
  19920. if ( action !== undefined ) {
  19921. this._deactivateAction( action );
  19922. this._removeInactiveAction( action );
  19923. }
  19924. }
  19925. const bindingsByRoot = this._bindingsByRootAndName,
  19926. bindingByName = bindingsByRoot[ rootUuid ];
  19927. if ( bindingByName !== undefined ) {
  19928. for ( const trackName in bindingByName ) {
  19929. const binding = bindingByName[ trackName ];
  19930. binding.restoreOriginalState();
  19931. this._removeInactiveBinding( binding );
  19932. }
  19933. }
  19934. }
  19935. // remove a targeted clip from the cache
  19936. uncacheAction( clip, optionalRoot ) {
  19937. const action = this.existingAction( clip, optionalRoot );
  19938. if ( action !== null ) {
  19939. this._deactivateAction( action );
  19940. this._removeInactiveAction( action );
  19941. }
  19942. }
  19943. }
  19944. let Uniform$1 = class Uniform {
  19945. constructor( value ) {
  19946. this.value = value;
  19947. }
  19948. clone() {
  19949. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  19950. }
  19951. };
  19952. let _id$8 = 0;
  19953. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  19954. constructor() {
  19955. super();
  19956. this.isUniformsGroup = true;
  19957. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  19958. this.name = '';
  19959. this.usage = StaticDrawUsage;
  19960. this.uniforms = [];
  19961. }
  19962. add( uniform ) {
  19963. this.uniforms.push( uniform );
  19964. return this;
  19965. }
  19966. remove( uniform ) {
  19967. const index = this.uniforms.indexOf( uniform );
  19968. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  19969. return this;
  19970. }
  19971. setName( name ) {
  19972. this.name = name;
  19973. return this;
  19974. }
  19975. setUsage( value ) {
  19976. this.usage = value;
  19977. return this;
  19978. }
  19979. dispose() {
  19980. this.dispatchEvent( { type: 'dispose' } );
  19981. return this;
  19982. }
  19983. copy( source ) {
  19984. this.name = source.name;
  19985. this.usage = source.usage;
  19986. const uniformsSource = source.uniforms;
  19987. this.uniforms.length = 0;
  19988. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  19989. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  19990. for ( let j = 0; j < uniforms.length; j ++ ) {
  19991. this.uniforms.push( uniforms[ j ].clone() );
  19992. }
  19993. }
  19994. return this;
  19995. }
  19996. clone() {
  19997. return new this.constructor().copy( this );
  19998. }
  19999. };
  20000. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20001. constructor( array, stride, meshPerAttribute = 1 ) {
  20002. super( array, stride );
  20003. this.isInstancedInterleavedBuffer = true;
  20004. this.meshPerAttribute = meshPerAttribute;
  20005. }
  20006. copy( source ) {
  20007. super.copy( source );
  20008. this.meshPerAttribute = source.meshPerAttribute;
  20009. return this;
  20010. }
  20011. clone( data ) {
  20012. const ib = super.clone( data );
  20013. ib.meshPerAttribute = this.meshPerAttribute;
  20014. return ib;
  20015. }
  20016. toJSON( data ) {
  20017. const json = super.toJSON( data );
  20018. json.isInstancedInterleavedBuffer = true;
  20019. json.meshPerAttribute = this.meshPerAttribute;
  20020. return json;
  20021. }
  20022. }
  20023. class GLBufferAttribute {
  20024. constructor( buffer, type, itemSize, elementSize, count ) {
  20025. this.isGLBufferAttribute = true;
  20026. this.name = '';
  20027. this.buffer = buffer;
  20028. this.type = type;
  20029. this.itemSize = itemSize;
  20030. this.elementSize = elementSize;
  20031. this.count = count;
  20032. this.version = 0;
  20033. }
  20034. set needsUpdate( value ) {
  20035. if ( value === true ) this.version ++;
  20036. }
  20037. setBuffer( buffer ) {
  20038. this.buffer = buffer;
  20039. return this;
  20040. }
  20041. setType( type, elementSize ) {
  20042. this.type = type;
  20043. this.elementSize = elementSize;
  20044. return this;
  20045. }
  20046. setItemSize( itemSize ) {
  20047. this.itemSize = itemSize;
  20048. return this;
  20049. }
  20050. setCount( count ) {
  20051. this.count = count;
  20052. return this;
  20053. }
  20054. }
  20055. const _matrix = /*@__PURE__*/ new Matrix4();
  20056. class Raycaster {
  20057. constructor( origin, direction, near = 0, far = Infinity ) {
  20058. this.ray = new Ray( origin, direction );
  20059. // direction is assumed to be normalized (for accurate distance calculations)
  20060. this.near = near;
  20061. this.far = far;
  20062. this.camera = null;
  20063. this.layers = new Layers();
  20064. this.params = {
  20065. Mesh: {},
  20066. Line: { threshold: 1 },
  20067. LOD: {},
  20068. Points: { threshold: 1 },
  20069. Sprite: {}
  20070. };
  20071. }
  20072. set( origin, direction ) {
  20073. // direction is assumed to be normalized (for accurate distance calculations)
  20074. this.ray.set( origin, direction );
  20075. }
  20076. setFromCamera( coords, camera ) {
  20077. if ( camera.isPerspectiveCamera ) {
  20078. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20079. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20080. this.camera = camera;
  20081. } else if ( camera.isOrthographicCamera ) {
  20082. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20083. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20084. this.camera = camera;
  20085. } else {
  20086. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20087. }
  20088. }
  20089. setFromXRController( controller ) {
  20090. _matrix.identity().extractRotation( controller.matrixWorld );
  20091. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20092. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20093. return this;
  20094. }
  20095. intersectObject( object, recursive = true, intersects = [] ) {
  20096. intersect( object, this, intersects, recursive );
  20097. intersects.sort( ascSort );
  20098. return intersects;
  20099. }
  20100. intersectObjects( objects, recursive = true, intersects = [] ) {
  20101. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20102. intersect( objects[ i ], this, intersects, recursive );
  20103. }
  20104. intersects.sort( ascSort );
  20105. return intersects;
  20106. }
  20107. }
  20108. function ascSort( a, b ) {
  20109. return a.distance - b.distance;
  20110. }
  20111. function intersect( object, raycaster, intersects, recursive ) {
  20112. let propagate = true;
  20113. if ( object.layers.test( raycaster.layers ) ) {
  20114. const result = object.raycast( raycaster, intersects );
  20115. if ( result === false ) propagate = false;
  20116. }
  20117. if ( propagate === true && recursive === true ) {
  20118. const children = object.children;
  20119. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20120. intersect( children[ i ], raycaster, intersects, true );
  20121. }
  20122. }
  20123. }
  20124. /**
  20125. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20126. *
  20127. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20128. * theta (the azimuthal angle) is measured from the positive z-axis.
  20129. */
  20130. class Spherical {
  20131. constructor( radius = 1, phi = 0, theta = 0 ) {
  20132. this.radius = radius;
  20133. this.phi = phi; // polar angle
  20134. this.theta = theta; // azimuthal angle
  20135. return this;
  20136. }
  20137. set( radius, phi, theta ) {
  20138. this.radius = radius;
  20139. this.phi = phi;
  20140. this.theta = theta;
  20141. return this;
  20142. }
  20143. copy( other ) {
  20144. this.radius = other.radius;
  20145. this.phi = other.phi;
  20146. this.theta = other.theta;
  20147. return this;
  20148. }
  20149. // restrict phi to be between EPS and PI-EPS
  20150. makeSafe() {
  20151. const EPS = 0.000001;
  20152. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20153. return this;
  20154. }
  20155. setFromVector3( v ) {
  20156. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20157. }
  20158. setFromCartesianCoords( x, y, z ) {
  20159. this.radius = Math.sqrt( x * x + y * y + z * z );
  20160. if ( this.radius === 0 ) {
  20161. this.theta = 0;
  20162. this.phi = 0;
  20163. } else {
  20164. this.theta = Math.atan2( x, z );
  20165. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20166. }
  20167. return this;
  20168. }
  20169. clone() {
  20170. return new this.constructor().copy( this );
  20171. }
  20172. }
  20173. /**
  20174. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20175. */
  20176. class Cylindrical {
  20177. constructor( radius = 1, theta = 0, y = 0 ) {
  20178. this.radius = radius; // distance from the origin to a point in the x-z plane
  20179. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20180. this.y = y; // height above the x-z plane
  20181. return this;
  20182. }
  20183. set( radius, theta, y ) {
  20184. this.radius = radius;
  20185. this.theta = theta;
  20186. this.y = y;
  20187. return this;
  20188. }
  20189. copy( other ) {
  20190. this.radius = other.radius;
  20191. this.theta = other.theta;
  20192. this.y = other.y;
  20193. return this;
  20194. }
  20195. setFromVector3( v ) {
  20196. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20197. }
  20198. setFromCartesianCoords( x, y, z ) {
  20199. this.radius = Math.sqrt( x * x + z * z );
  20200. this.theta = Math.atan2( x, z );
  20201. this.y = y;
  20202. return this;
  20203. }
  20204. clone() {
  20205. return new this.constructor().copy( this );
  20206. }
  20207. }
  20208. class Matrix2 {
  20209. constructor( n11, n12, n21, n22 ) {
  20210. Matrix2.prototype.isMatrix2 = true;
  20211. this.elements = [
  20212. 1, 0,
  20213. 0, 1,
  20214. ];
  20215. if ( n11 !== undefined ) {
  20216. this.set( n11, n12, n21, n22 );
  20217. }
  20218. }
  20219. identity() {
  20220. this.set(
  20221. 1, 0,
  20222. 0, 1,
  20223. );
  20224. return this;
  20225. }
  20226. fromArray( array, offset = 0 ) {
  20227. for ( let i = 0; i < 4; i ++ ) {
  20228. this.elements[ i ] = array[ i + offset ];
  20229. }
  20230. return this;
  20231. }
  20232. set( n11, n12, n21, n22 ) {
  20233. const te = this.elements;
  20234. te[ 0 ] = n11; te[ 2 ] = n12;
  20235. te[ 1 ] = n21; te[ 3 ] = n22;
  20236. return this;
  20237. }
  20238. }
  20239. const _vector$4 = /*@__PURE__*/ new Vector2();
  20240. class Box2 {
  20241. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20242. this.isBox2 = true;
  20243. this.min = min;
  20244. this.max = max;
  20245. }
  20246. set( min, max ) {
  20247. this.min.copy( min );
  20248. this.max.copy( max );
  20249. return this;
  20250. }
  20251. setFromPoints( points ) {
  20252. this.makeEmpty();
  20253. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20254. this.expandByPoint( points[ i ] );
  20255. }
  20256. return this;
  20257. }
  20258. setFromCenterAndSize( center, size ) {
  20259. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20260. this.min.copy( center ).sub( halfSize );
  20261. this.max.copy( center ).add( halfSize );
  20262. return this;
  20263. }
  20264. clone() {
  20265. return new this.constructor().copy( this );
  20266. }
  20267. copy( box ) {
  20268. this.min.copy( box.min );
  20269. this.max.copy( box.max );
  20270. return this;
  20271. }
  20272. makeEmpty() {
  20273. this.min.x = this.min.y = + Infinity;
  20274. this.max.x = this.max.y = - Infinity;
  20275. return this;
  20276. }
  20277. isEmpty() {
  20278. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20279. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20280. }
  20281. getCenter( target ) {
  20282. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20283. }
  20284. getSize( target ) {
  20285. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20286. }
  20287. expandByPoint( point ) {
  20288. this.min.min( point );
  20289. this.max.max( point );
  20290. return this;
  20291. }
  20292. expandByVector( vector ) {
  20293. this.min.sub( vector );
  20294. this.max.add( vector );
  20295. return this;
  20296. }
  20297. expandByScalar( scalar ) {
  20298. this.min.addScalar( - scalar );
  20299. this.max.addScalar( scalar );
  20300. return this;
  20301. }
  20302. containsPoint( point ) {
  20303. return point.x >= this.min.x && point.x <= this.max.x &&
  20304. point.y >= this.min.y && point.y <= this.max.y;
  20305. }
  20306. containsBox( box ) {
  20307. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20308. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20309. }
  20310. getParameter( point, target ) {
  20311. // This can potentially have a divide by zero if the box
  20312. // has a size dimension of 0.
  20313. return target.set(
  20314. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20315. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20316. );
  20317. }
  20318. intersectsBox( box ) {
  20319. // using 4 splitting planes to rule out intersections
  20320. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20321. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20322. }
  20323. clampPoint( point, target ) {
  20324. return target.copy( point ).clamp( this.min, this.max );
  20325. }
  20326. distanceToPoint( point ) {
  20327. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20328. }
  20329. intersect( box ) {
  20330. this.min.max( box.min );
  20331. this.max.min( box.max );
  20332. if ( this.isEmpty() ) this.makeEmpty();
  20333. return this;
  20334. }
  20335. union( box ) {
  20336. this.min.min( box.min );
  20337. this.max.max( box.max );
  20338. return this;
  20339. }
  20340. translate( offset ) {
  20341. this.min.add( offset );
  20342. this.max.add( offset );
  20343. return this;
  20344. }
  20345. equals( box ) {
  20346. return box.min.equals( this.min ) && box.max.equals( this.max );
  20347. }
  20348. }
  20349. const _startP = /*@__PURE__*/ new Vector3();
  20350. const _startEnd = /*@__PURE__*/ new Vector3();
  20351. class Line3 {
  20352. constructor( start = new Vector3(), end = new Vector3() ) {
  20353. this.start = start;
  20354. this.end = end;
  20355. }
  20356. set( start, end ) {
  20357. this.start.copy( start );
  20358. this.end.copy( end );
  20359. return this;
  20360. }
  20361. copy( line ) {
  20362. this.start.copy( line.start );
  20363. this.end.copy( line.end );
  20364. return this;
  20365. }
  20366. getCenter( target ) {
  20367. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20368. }
  20369. delta( target ) {
  20370. return target.subVectors( this.end, this.start );
  20371. }
  20372. distanceSq() {
  20373. return this.start.distanceToSquared( this.end );
  20374. }
  20375. distance() {
  20376. return this.start.distanceTo( this.end );
  20377. }
  20378. at( t, target ) {
  20379. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20380. }
  20381. closestPointToPointParameter( point, clampToLine ) {
  20382. _startP.subVectors( point, this.start );
  20383. _startEnd.subVectors( this.end, this.start );
  20384. const startEnd2 = _startEnd.dot( _startEnd );
  20385. const startEnd_startP = _startEnd.dot( _startP );
  20386. let t = startEnd_startP / startEnd2;
  20387. if ( clampToLine ) {
  20388. t = clamp$1( t, 0, 1 );
  20389. }
  20390. return t;
  20391. }
  20392. closestPointToPoint( point, clampToLine, target ) {
  20393. const t = this.closestPointToPointParameter( point, clampToLine );
  20394. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20395. }
  20396. applyMatrix4( matrix ) {
  20397. this.start.applyMatrix4( matrix );
  20398. this.end.applyMatrix4( matrix );
  20399. return this;
  20400. }
  20401. equals( line ) {
  20402. return line.start.equals( this.start ) && line.end.equals( this.end );
  20403. }
  20404. clone() {
  20405. return new this.constructor().copy( this );
  20406. }
  20407. }
  20408. const _vector$3 = /*@__PURE__*/ new Vector3();
  20409. class SpotLightHelper extends Object3D {
  20410. constructor( light, color ) {
  20411. super();
  20412. this.light = light;
  20413. this.matrixAutoUpdate = false;
  20414. this.color = color;
  20415. this.type = 'SpotLightHelper';
  20416. const geometry = new BufferGeometry();
  20417. const positions = [
  20418. 0, 0, 0, 0, 0, 1,
  20419. 0, 0, 0, 1, 0, 1,
  20420. 0, 0, 0, - 1, 0, 1,
  20421. 0, 0, 0, 0, 1, 1,
  20422. 0, 0, 0, 0, - 1, 1
  20423. ];
  20424. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20425. const p1 = ( i / l ) * Math.PI * 2;
  20426. const p2 = ( j / l ) * Math.PI * 2;
  20427. positions.push(
  20428. Math.cos( p1 ), Math.sin( p1 ), 1,
  20429. Math.cos( p2 ), Math.sin( p2 ), 1
  20430. );
  20431. }
  20432. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20433. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20434. this.cone = new LineSegments( geometry, material );
  20435. this.add( this.cone );
  20436. this.update();
  20437. }
  20438. dispose() {
  20439. this.cone.geometry.dispose();
  20440. this.cone.material.dispose();
  20441. }
  20442. update() {
  20443. this.light.updateWorldMatrix( true, false );
  20444. this.light.target.updateWorldMatrix( true, false );
  20445. // update the local matrix based on the parent and light target transforms
  20446. if ( this.parent ) {
  20447. this.parent.updateWorldMatrix( true );
  20448. this.matrix
  20449. .copy( this.parent.matrixWorld )
  20450. .invert()
  20451. .multiply( this.light.matrixWorld );
  20452. } else {
  20453. this.matrix.copy( this.light.matrixWorld );
  20454. }
  20455. this.matrixWorld.copy( this.light.matrixWorld );
  20456. const coneLength = this.light.distance ? this.light.distance : 1000;
  20457. const coneWidth = coneLength * Math.tan( this.light.angle );
  20458. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20459. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20460. this.cone.lookAt( _vector$3 );
  20461. if ( this.color !== undefined ) {
  20462. this.cone.material.color.set( this.color );
  20463. } else {
  20464. this.cone.material.color.copy( this.light.color );
  20465. }
  20466. }
  20467. }
  20468. const _vector$2 = /*@__PURE__*/ new Vector3();
  20469. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20470. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20471. class SkeletonHelper extends LineSegments {
  20472. constructor( object ) {
  20473. const bones = getBoneList( object );
  20474. const geometry = new BufferGeometry();
  20475. const vertices = [];
  20476. const colors = [];
  20477. const color1 = new Color( 0, 0, 1 );
  20478. const color2 = new Color( 0, 1, 0 );
  20479. for ( let i = 0; i < bones.length; i ++ ) {
  20480. const bone = bones[ i ];
  20481. if ( bone.parent && bone.parent.isBone ) {
  20482. vertices.push( 0, 0, 0 );
  20483. vertices.push( 0, 0, 0 );
  20484. colors.push( color1.r, color1.g, color1.b );
  20485. colors.push( color2.r, color2.g, color2.b );
  20486. }
  20487. }
  20488. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20489. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20490. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20491. super( geometry, material );
  20492. this.isSkeletonHelper = true;
  20493. this.type = 'SkeletonHelper';
  20494. this.root = object;
  20495. this.bones = bones;
  20496. this.matrix = object.matrixWorld;
  20497. this.matrixAutoUpdate = false;
  20498. }
  20499. updateMatrixWorld( force ) {
  20500. const bones = this.bones;
  20501. const geometry = this.geometry;
  20502. const position = geometry.getAttribute( 'position' );
  20503. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20504. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20505. const bone = bones[ i ];
  20506. if ( bone.parent && bone.parent.isBone ) {
  20507. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20508. _vector$2.setFromMatrixPosition( _boneMatrix );
  20509. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20510. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20511. _vector$2.setFromMatrixPosition( _boneMatrix );
  20512. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20513. j += 2;
  20514. }
  20515. }
  20516. geometry.getAttribute( 'position' ).needsUpdate = true;
  20517. super.updateMatrixWorld( force );
  20518. }
  20519. dispose() {
  20520. this.geometry.dispose();
  20521. this.material.dispose();
  20522. }
  20523. }
  20524. function getBoneList( object ) {
  20525. const boneList = [];
  20526. if ( object.isBone === true ) {
  20527. boneList.push( object );
  20528. }
  20529. for ( let i = 0; i < object.children.length; i ++ ) {
  20530. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20531. }
  20532. return boneList;
  20533. }
  20534. class PointLightHelper extends Mesh {
  20535. constructor( light, sphereSize, color ) {
  20536. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20537. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20538. super( geometry, material );
  20539. this.light = light;
  20540. this.color = color;
  20541. this.type = 'PointLightHelper';
  20542. this.matrix = this.light.matrixWorld;
  20543. this.matrixAutoUpdate = false;
  20544. this.update();
  20545. /*
  20546. // TODO: delete this comment?
  20547. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20548. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20549. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20550. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20551. const d = light.distance;
  20552. if ( d === 0.0 ) {
  20553. this.lightDistance.visible = false;
  20554. } else {
  20555. this.lightDistance.scale.set( d, d, d );
  20556. }
  20557. this.add( this.lightDistance );
  20558. */
  20559. }
  20560. dispose() {
  20561. this.geometry.dispose();
  20562. this.material.dispose();
  20563. }
  20564. update() {
  20565. this.light.updateWorldMatrix( true, false );
  20566. if ( this.color !== undefined ) {
  20567. this.material.color.set( this.color );
  20568. } else {
  20569. this.material.color.copy( this.light.color );
  20570. }
  20571. /*
  20572. const d = this.light.distance;
  20573. if ( d === 0.0 ) {
  20574. this.lightDistance.visible = false;
  20575. } else {
  20576. this.lightDistance.visible = true;
  20577. this.lightDistance.scale.set( d, d, d );
  20578. }
  20579. */
  20580. }
  20581. }
  20582. const _vector$1 = /*@__PURE__*/ new Vector3();
  20583. const _color1 = /*@__PURE__*/ new Color();
  20584. const _color2 = /*@__PURE__*/ new Color();
  20585. class HemisphereLightHelper extends Object3D {
  20586. constructor( light, size, color ) {
  20587. super();
  20588. this.light = light;
  20589. this.matrix = light.matrixWorld;
  20590. this.matrixAutoUpdate = false;
  20591. this.color = color;
  20592. this.type = 'HemisphereLightHelper';
  20593. const geometry = new OctahedronGeometry( size );
  20594. geometry.rotateY( Math.PI * 0.5 );
  20595. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20596. if ( this.color === undefined ) this.material.vertexColors = true;
  20597. const position = geometry.getAttribute( 'position' );
  20598. const colors = new Float32Array( position.count * 3 );
  20599. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20600. this.add( new Mesh( geometry, this.material ) );
  20601. this.update();
  20602. }
  20603. dispose() {
  20604. this.children[ 0 ].geometry.dispose();
  20605. this.children[ 0 ].material.dispose();
  20606. }
  20607. update() {
  20608. const mesh = this.children[ 0 ];
  20609. if ( this.color !== undefined ) {
  20610. this.material.color.set( this.color );
  20611. } else {
  20612. const colors = mesh.geometry.getAttribute( 'color' );
  20613. _color1.copy( this.light.color );
  20614. _color2.copy( this.light.groundColor );
  20615. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20616. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20617. colors.setXYZ( i, color.r, color.g, color.b );
  20618. }
  20619. colors.needsUpdate = true;
  20620. }
  20621. this.light.updateWorldMatrix( true, false );
  20622. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20623. }
  20624. }
  20625. class GridHelper extends LineSegments {
  20626. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20627. color1 = new Color( color1 );
  20628. color2 = new Color( color2 );
  20629. const center = divisions / 2;
  20630. const step = size / divisions;
  20631. const halfSize = size / 2;
  20632. const vertices = [], colors = [];
  20633. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20634. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20635. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20636. const color = i === center ? color1 : color2;
  20637. color.toArray( colors, j ); j += 3;
  20638. color.toArray( colors, j ); j += 3;
  20639. color.toArray( colors, j ); j += 3;
  20640. color.toArray( colors, j ); j += 3;
  20641. }
  20642. const geometry = new BufferGeometry();
  20643. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20644. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20645. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20646. super( geometry, material );
  20647. this.type = 'GridHelper';
  20648. }
  20649. dispose() {
  20650. this.geometry.dispose();
  20651. this.material.dispose();
  20652. }
  20653. }
  20654. class PolarGridHelper extends LineSegments {
  20655. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20656. color1 = new Color( color1 );
  20657. color2 = new Color( color2 );
  20658. const vertices = [];
  20659. const colors = [];
  20660. // create the sectors
  20661. if ( sectors > 1 ) {
  20662. for ( let i = 0; i < sectors; i ++ ) {
  20663. const v = ( i / sectors ) * ( Math.PI * 2 );
  20664. const x = Math.sin( v ) * radius;
  20665. const z = Math.cos( v ) * radius;
  20666. vertices.push( 0, 0, 0 );
  20667. vertices.push( x, 0, z );
  20668. const color = ( i & 1 ) ? color1 : color2;
  20669. colors.push( color.r, color.g, color.b );
  20670. colors.push( color.r, color.g, color.b );
  20671. }
  20672. }
  20673. // create the rings
  20674. for ( let i = 0; i < rings; i ++ ) {
  20675. const color = ( i & 1 ) ? color1 : color2;
  20676. const r = radius - ( radius / rings * i );
  20677. for ( let j = 0; j < divisions; j ++ ) {
  20678. // first vertex
  20679. let v = ( j / divisions ) * ( Math.PI * 2 );
  20680. let x = Math.sin( v ) * r;
  20681. let z = Math.cos( v ) * r;
  20682. vertices.push( x, 0, z );
  20683. colors.push( color.r, color.g, color.b );
  20684. // second vertex
  20685. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20686. x = Math.sin( v ) * r;
  20687. z = Math.cos( v ) * r;
  20688. vertices.push( x, 0, z );
  20689. colors.push( color.r, color.g, color.b );
  20690. }
  20691. }
  20692. const geometry = new BufferGeometry();
  20693. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20694. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20695. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20696. super( geometry, material );
  20697. this.type = 'PolarGridHelper';
  20698. }
  20699. dispose() {
  20700. this.geometry.dispose();
  20701. this.material.dispose();
  20702. }
  20703. }
  20704. const _v1 = /*@__PURE__*/ new Vector3();
  20705. const _v2 = /*@__PURE__*/ new Vector3();
  20706. const _v3 = /*@__PURE__*/ new Vector3();
  20707. class DirectionalLightHelper extends Object3D {
  20708. constructor( light, size, color ) {
  20709. super();
  20710. this.light = light;
  20711. this.matrix = light.matrixWorld;
  20712. this.matrixAutoUpdate = false;
  20713. this.color = color;
  20714. this.type = 'DirectionalLightHelper';
  20715. if ( size === undefined ) size = 1;
  20716. let geometry = new BufferGeometry();
  20717. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20718. - size, size, 0,
  20719. size, size, 0,
  20720. size, - size, 0,
  20721. - size, - size, 0,
  20722. - size, size, 0
  20723. ], 3 ) );
  20724. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20725. this.lightPlane = new Line( geometry, material );
  20726. this.add( this.lightPlane );
  20727. geometry = new BufferGeometry();
  20728. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20729. this.targetLine = new Line( geometry, material );
  20730. this.add( this.targetLine );
  20731. this.update();
  20732. }
  20733. dispose() {
  20734. this.lightPlane.geometry.dispose();
  20735. this.lightPlane.material.dispose();
  20736. this.targetLine.geometry.dispose();
  20737. this.targetLine.material.dispose();
  20738. }
  20739. update() {
  20740. this.light.updateWorldMatrix( true, false );
  20741. this.light.target.updateWorldMatrix( true, false );
  20742. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20743. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20744. _v3.subVectors( _v2, _v1 );
  20745. this.lightPlane.lookAt( _v2 );
  20746. if ( this.color !== undefined ) {
  20747. this.lightPlane.material.color.set( this.color );
  20748. this.targetLine.material.color.set( this.color );
  20749. } else {
  20750. this.lightPlane.material.color.copy( this.light.color );
  20751. this.targetLine.material.color.copy( this.light.color );
  20752. }
  20753. this.targetLine.lookAt( _v2 );
  20754. this.targetLine.scale.z = _v3.length();
  20755. }
  20756. }
  20757. const _vector = /*@__PURE__*/ new Vector3();
  20758. const _camera$1 = /*@__PURE__*/ new Camera();
  20759. /**
  20760. * - shows frustum, line of sight and up of the camera
  20761. * - suitable for fast updates
  20762. * - based on frustum visualization in lightgl.js shadowmap example
  20763. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20764. */
  20765. class CameraHelper extends LineSegments {
  20766. constructor( camera ) {
  20767. const geometry = new BufferGeometry();
  20768. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20769. const vertices = [];
  20770. const colors = [];
  20771. const pointMap = {};
  20772. // near
  20773. addLine( 'n1', 'n2' );
  20774. addLine( 'n2', 'n4' );
  20775. addLine( 'n4', 'n3' );
  20776. addLine( 'n3', 'n1' );
  20777. // far
  20778. addLine( 'f1', 'f2' );
  20779. addLine( 'f2', 'f4' );
  20780. addLine( 'f4', 'f3' );
  20781. addLine( 'f3', 'f1' );
  20782. // sides
  20783. addLine( 'n1', 'f1' );
  20784. addLine( 'n2', 'f2' );
  20785. addLine( 'n3', 'f3' );
  20786. addLine( 'n4', 'f4' );
  20787. // cone
  20788. addLine( 'p', 'n1' );
  20789. addLine( 'p', 'n2' );
  20790. addLine( 'p', 'n3' );
  20791. addLine( 'p', 'n4' );
  20792. // up
  20793. addLine( 'u1', 'u2' );
  20794. addLine( 'u2', 'u3' );
  20795. addLine( 'u3', 'u1' );
  20796. // target
  20797. addLine( 'c', 't' );
  20798. addLine( 'p', 'c' );
  20799. // cross
  20800. addLine( 'cn1', 'cn2' );
  20801. addLine( 'cn3', 'cn4' );
  20802. addLine( 'cf1', 'cf2' );
  20803. addLine( 'cf3', 'cf4' );
  20804. function addLine( a, b ) {
  20805. addPoint( a );
  20806. addPoint( b );
  20807. }
  20808. function addPoint( id ) {
  20809. vertices.push( 0, 0, 0 );
  20810. colors.push( 0, 0, 0 );
  20811. if ( pointMap[ id ] === undefined ) {
  20812. pointMap[ id ] = [];
  20813. }
  20814. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20815. }
  20816. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20817. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20818. super( geometry, material );
  20819. this.type = 'CameraHelper';
  20820. this.camera = camera;
  20821. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20822. this.matrix = camera.matrixWorld;
  20823. this.matrixAutoUpdate = false;
  20824. this.pointMap = pointMap;
  20825. this.update();
  20826. // colors
  20827. const colorFrustum = new Color( 0xffaa00 );
  20828. const colorCone = new Color( 0xff0000 );
  20829. const colorUp = new Color( 0x00aaff );
  20830. const colorTarget = new Color( 0xffffff );
  20831. const colorCross = new Color( 0x333333 );
  20832. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20833. }
  20834. setColors( frustum, cone, up, target, cross ) {
  20835. const geometry = this.geometry;
  20836. const colorAttribute = geometry.getAttribute( 'color' );
  20837. // near
  20838. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20839. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20840. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20841. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20842. // far
  20843. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20844. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20845. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20846. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20847. // sides
  20848. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20849. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20850. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20851. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20852. // cone
  20853. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20854. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20855. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20856. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20857. // up
  20858. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20859. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20860. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20861. // target
  20862. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20863. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20864. // cross
  20865. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20866. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20867. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20868. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20869. colorAttribute.needsUpdate = true;
  20870. }
  20871. update() {
  20872. const geometry = this.geometry;
  20873. const pointMap = this.pointMap;
  20874. const w = 1, h = 1;
  20875. // we need just camera projection matrix inverse
  20876. // world matrix must be identity
  20877. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20878. // center / target
  20879. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20880. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20881. // near
  20882. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20883. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20884. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20885. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20886. // far
  20887. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20888. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20889. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20890. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20891. // up
  20892. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20893. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20894. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20895. // cross
  20896. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20897. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20898. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20899. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20900. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20901. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20902. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20903. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20904. geometry.getAttribute( 'position' ).needsUpdate = true;
  20905. }
  20906. dispose() {
  20907. this.geometry.dispose();
  20908. this.material.dispose();
  20909. }
  20910. }
  20911. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20912. _vector.set( x, y, z ).unproject( camera );
  20913. const points = pointMap[ point ];
  20914. if ( points !== undefined ) {
  20915. const position = geometry.getAttribute( 'position' );
  20916. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20917. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20918. }
  20919. }
  20920. }
  20921. const _box = /*@__PURE__*/ new Box3();
  20922. class BoxHelper extends LineSegments {
  20923. constructor( object, color = 0xffff00 ) {
  20924. 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 ] );
  20925. const positions = new Float32Array( 8 * 3 );
  20926. const geometry = new BufferGeometry();
  20927. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20928. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20929. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20930. this.object = object;
  20931. this.type = 'BoxHelper';
  20932. this.matrixAutoUpdate = false;
  20933. this.update();
  20934. }
  20935. update( object ) {
  20936. if ( object !== undefined ) {
  20937. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20938. }
  20939. if ( this.object !== undefined ) {
  20940. _box.setFromObject( this.object );
  20941. }
  20942. if ( _box.isEmpty() ) return;
  20943. const min = _box.min;
  20944. const max = _box.max;
  20945. /*
  20946. 5____4
  20947. 1/___0/|
  20948. | 6__|_7
  20949. 2/___3/
  20950. 0: max.x, max.y, max.z
  20951. 1: min.x, max.y, max.z
  20952. 2: min.x, min.y, max.z
  20953. 3: max.x, min.y, max.z
  20954. 4: max.x, max.y, min.z
  20955. 5: min.x, max.y, min.z
  20956. 6: min.x, min.y, min.z
  20957. 7: max.x, min.y, min.z
  20958. */
  20959. const position = this.geometry.attributes.position;
  20960. const array = position.array;
  20961. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20962. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20963. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20964. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20965. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20966. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20967. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20968. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20969. position.needsUpdate = true;
  20970. this.geometry.computeBoundingSphere();
  20971. }
  20972. setFromObject( object ) {
  20973. this.object = object;
  20974. this.update();
  20975. return this;
  20976. }
  20977. copy( source, recursive ) {
  20978. super.copy( source, recursive );
  20979. this.object = source.object;
  20980. return this;
  20981. }
  20982. dispose() {
  20983. this.geometry.dispose();
  20984. this.material.dispose();
  20985. }
  20986. }
  20987. class Box3Helper extends LineSegments {
  20988. constructor( box, color = 0xffff00 ) {
  20989. 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 ] );
  20990. 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 ];
  20991. const geometry = new BufferGeometry();
  20992. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20993. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20994. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20995. this.box = box;
  20996. this.type = 'Box3Helper';
  20997. this.geometry.computeBoundingSphere();
  20998. }
  20999. updateMatrixWorld( force ) {
  21000. const box = this.box;
  21001. if ( box.isEmpty() ) return;
  21002. box.getCenter( this.position );
  21003. box.getSize( this.scale );
  21004. this.scale.multiplyScalar( 0.5 );
  21005. super.updateMatrixWorld( force );
  21006. }
  21007. dispose() {
  21008. this.geometry.dispose();
  21009. this.material.dispose();
  21010. }
  21011. }
  21012. class PlaneHelper extends Line {
  21013. constructor( plane, size = 1, hex = 0xffff00 ) {
  21014. const color = hex;
  21015. 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 ];
  21016. const geometry = new BufferGeometry();
  21017. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21018. geometry.computeBoundingSphere();
  21019. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21020. this.type = 'PlaneHelper';
  21021. this.plane = plane;
  21022. this.size = size;
  21023. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21024. const geometry2 = new BufferGeometry();
  21025. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21026. geometry2.computeBoundingSphere();
  21027. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21028. }
  21029. updateMatrixWorld( force ) {
  21030. this.position.set( 0, 0, 0 );
  21031. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21032. this.lookAt( this.plane.normal );
  21033. this.translateZ( - this.plane.constant );
  21034. super.updateMatrixWorld( force );
  21035. }
  21036. dispose() {
  21037. this.geometry.dispose();
  21038. this.material.dispose();
  21039. this.children[ 0 ].geometry.dispose();
  21040. this.children[ 0 ].material.dispose();
  21041. }
  21042. }
  21043. const _axis = /*@__PURE__*/ new Vector3();
  21044. let _lineGeometry, _coneGeometry;
  21045. class ArrowHelper extends Object3D {
  21046. // dir is assumed to be normalized
  21047. 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 ) {
  21048. super();
  21049. this.type = 'ArrowHelper';
  21050. if ( _lineGeometry === undefined ) {
  21051. _lineGeometry = new BufferGeometry();
  21052. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21053. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21054. _coneGeometry.translate( 0, - 0.5, 0 );
  21055. }
  21056. this.position.copy( origin );
  21057. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21058. this.line.matrixAutoUpdate = false;
  21059. this.add( this.line );
  21060. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21061. this.cone.matrixAutoUpdate = false;
  21062. this.add( this.cone );
  21063. this.setDirection( dir );
  21064. this.setLength( length, headLength, headWidth );
  21065. }
  21066. setDirection( dir ) {
  21067. // dir is assumed to be normalized
  21068. if ( dir.y > 0.99999 ) {
  21069. this.quaternion.set( 0, 0, 0, 1 );
  21070. } else if ( dir.y < - 0.99999 ) {
  21071. this.quaternion.set( 1, 0, 0, 0 );
  21072. } else {
  21073. _axis.set( dir.z, 0, - dir.x ).normalize();
  21074. const radians = Math.acos( dir.y );
  21075. this.quaternion.setFromAxisAngle( _axis, radians );
  21076. }
  21077. }
  21078. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21079. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21080. this.line.updateMatrix();
  21081. this.cone.scale.set( headWidth, headLength, headWidth );
  21082. this.cone.position.y = length;
  21083. this.cone.updateMatrix();
  21084. }
  21085. setColor( color ) {
  21086. this.line.material.color.set( color );
  21087. this.cone.material.color.set( color );
  21088. }
  21089. copy( source ) {
  21090. super.copy( source, false );
  21091. this.line.copy( source.line );
  21092. this.cone.copy( source.cone );
  21093. return this;
  21094. }
  21095. dispose() {
  21096. this.line.geometry.dispose();
  21097. this.line.material.dispose();
  21098. this.cone.geometry.dispose();
  21099. this.cone.material.dispose();
  21100. }
  21101. }
  21102. class AxesHelper extends LineSegments {
  21103. constructor( size = 1 ) {
  21104. const vertices = [
  21105. 0, 0, 0, size, 0, 0,
  21106. 0, 0, 0, 0, size, 0,
  21107. 0, 0, 0, 0, 0, size
  21108. ];
  21109. const colors = [
  21110. 1, 0, 0, 1, 0.6, 0,
  21111. 0, 1, 0, 0.6, 1, 0,
  21112. 0, 0, 1, 0, 0.6, 1
  21113. ];
  21114. const geometry = new BufferGeometry();
  21115. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21116. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21117. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21118. super( geometry, material );
  21119. this.type = 'AxesHelper';
  21120. }
  21121. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21122. const color = new Color();
  21123. const array = this.geometry.attributes.color.array;
  21124. color.set( xAxisColor );
  21125. color.toArray( array, 0 );
  21126. color.toArray( array, 3 );
  21127. color.set( yAxisColor );
  21128. color.toArray( array, 6 );
  21129. color.toArray( array, 9 );
  21130. color.set( zAxisColor );
  21131. color.toArray( array, 12 );
  21132. color.toArray( array, 15 );
  21133. this.geometry.attributes.color.needsUpdate = true;
  21134. return this;
  21135. }
  21136. dispose() {
  21137. this.geometry.dispose();
  21138. this.material.dispose();
  21139. }
  21140. }
  21141. class ShapePath {
  21142. constructor() {
  21143. this.type = 'ShapePath';
  21144. this.color = new Color();
  21145. this.subPaths = [];
  21146. this.currentPath = null;
  21147. }
  21148. moveTo( x, y ) {
  21149. this.currentPath = new Path();
  21150. this.subPaths.push( this.currentPath );
  21151. this.currentPath.moveTo( x, y );
  21152. return this;
  21153. }
  21154. lineTo( x, y ) {
  21155. this.currentPath.lineTo( x, y );
  21156. return this;
  21157. }
  21158. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21159. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21160. return this;
  21161. }
  21162. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21163. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21164. return this;
  21165. }
  21166. splineThru( pts ) {
  21167. this.currentPath.splineThru( pts );
  21168. return this;
  21169. }
  21170. toShapes( isCCW ) {
  21171. function toShapesNoHoles( inSubpaths ) {
  21172. const shapes = [];
  21173. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21174. const tmpPath = inSubpaths[ i ];
  21175. const tmpShape = new Shape();
  21176. tmpShape.curves = tmpPath.curves;
  21177. shapes.push( tmpShape );
  21178. }
  21179. return shapes;
  21180. }
  21181. function isPointInsidePolygon( inPt, inPolygon ) {
  21182. const polyLen = inPolygon.length;
  21183. // inPt on polygon contour => immediate success or
  21184. // toggling of inside/outside at every single! intersection point of an edge
  21185. // with the horizontal line through inPt, left of inPt
  21186. // not counting lowerY endpoints of edges and whole edges on that line
  21187. let inside = false;
  21188. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21189. let edgeLowPt = inPolygon[ p ];
  21190. let edgeHighPt = inPolygon[ q ];
  21191. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21192. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21193. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21194. // not parallel
  21195. if ( edgeDy < 0 ) {
  21196. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21197. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21198. }
  21199. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21200. if ( inPt.y === edgeLowPt.y ) {
  21201. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21202. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21203. } else {
  21204. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21205. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21206. if ( perpEdge < 0 ) continue;
  21207. inside = ! inside; // true intersection left of inPt
  21208. }
  21209. } else {
  21210. // parallel or collinear
  21211. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21212. // edge lies on the same horizontal line as inPt
  21213. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21214. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21215. // continue;
  21216. }
  21217. }
  21218. return inside;
  21219. }
  21220. const isClockWise = ShapeUtils.isClockWise;
  21221. const subPaths = this.subPaths;
  21222. if ( subPaths.length === 0 ) return [];
  21223. let solid, tmpPath, tmpShape;
  21224. const shapes = [];
  21225. if ( subPaths.length === 1 ) {
  21226. tmpPath = subPaths[ 0 ];
  21227. tmpShape = new Shape();
  21228. tmpShape.curves = tmpPath.curves;
  21229. shapes.push( tmpShape );
  21230. return shapes;
  21231. }
  21232. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21233. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21234. // console.log("Holes first", holesFirst);
  21235. const betterShapeHoles = [];
  21236. const newShapes = [];
  21237. let newShapeHoles = [];
  21238. let mainIdx = 0;
  21239. let tmpPoints;
  21240. newShapes[ mainIdx ] = undefined;
  21241. newShapeHoles[ mainIdx ] = [];
  21242. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21243. tmpPath = subPaths[ i ];
  21244. tmpPoints = tmpPath.getPoints();
  21245. solid = isClockWise( tmpPoints );
  21246. solid = isCCW ? ! solid : solid;
  21247. if ( solid ) {
  21248. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21249. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21250. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21251. if ( holesFirst ) mainIdx ++;
  21252. newShapeHoles[ mainIdx ] = [];
  21253. //console.log('cw', i);
  21254. } else {
  21255. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21256. //console.log('ccw', i);
  21257. }
  21258. }
  21259. // only Holes? -> probably all Shapes with wrong orientation
  21260. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21261. if ( newShapes.length > 1 ) {
  21262. let ambiguous = false;
  21263. let toChange = 0;
  21264. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21265. betterShapeHoles[ sIdx ] = [];
  21266. }
  21267. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21268. const sho = newShapeHoles[ sIdx ];
  21269. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21270. const ho = sho[ hIdx ];
  21271. let hole_unassigned = true;
  21272. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21273. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21274. if ( sIdx !== s2Idx ) toChange ++;
  21275. if ( hole_unassigned ) {
  21276. hole_unassigned = false;
  21277. betterShapeHoles[ s2Idx ].push( ho );
  21278. } else {
  21279. ambiguous = true;
  21280. }
  21281. }
  21282. }
  21283. if ( hole_unassigned ) {
  21284. betterShapeHoles[ sIdx ].push( ho );
  21285. }
  21286. }
  21287. }
  21288. if ( toChange > 0 && ambiguous === false ) {
  21289. newShapeHoles = betterShapeHoles;
  21290. }
  21291. }
  21292. let tmpHoles;
  21293. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21294. tmpShape = newShapes[ i ].s;
  21295. shapes.push( tmpShape );
  21296. tmpHoles = newShapeHoles[ i ];
  21297. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21298. tmpShape.holes.push( tmpHoles[ j ].h );
  21299. }
  21300. }
  21301. //console.log("shape", shapes);
  21302. return shapes;
  21303. }
  21304. }
  21305. class Controls extends EventDispatcher {
  21306. constructor( object, domElement ) {
  21307. super();
  21308. this.object = object;
  21309. this.domElement = domElement;
  21310. this.enabled = true;
  21311. this.state = - 1;
  21312. this.keys = {};
  21313. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21314. this.touches = { ONE: null, TWO: null };
  21315. }
  21316. connect() {}
  21317. disconnect() {}
  21318. dispose() {}
  21319. update( /* delta */ ) {}
  21320. }
  21321. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21322. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21323. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21324. super( width, height, { ...options, count } );
  21325. this.isWebGLMultipleRenderTargets = true;
  21326. }
  21327. get texture() {
  21328. return this.textures;
  21329. }
  21330. }
  21331. function getCacheKey$1( object, force = false ) {
  21332. let cacheKey = '{';
  21333. if ( object.isNode === true ) {
  21334. cacheKey += object.id;
  21335. object = object.getSelf();
  21336. }
  21337. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21338. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  21339. }
  21340. cacheKey += '}';
  21341. return cacheKey;
  21342. }
  21343. function* getNodeChildren( node, toJSON = false ) {
  21344. for ( const property in node ) {
  21345. // Ignore private properties.
  21346. if ( property.startsWith( '_' ) === true ) continue;
  21347. const object = node[ property ];
  21348. if ( Array.isArray( object ) === true ) {
  21349. for ( let i = 0; i < object.length; i ++ ) {
  21350. const child = object[ i ];
  21351. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21352. yield { property, index: i, childNode: child };
  21353. }
  21354. }
  21355. } else if ( object && object.isNode === true ) {
  21356. yield { property, childNode: object };
  21357. } else if ( typeof object === 'object' ) {
  21358. for ( const subProperty in object ) {
  21359. const child = object[ subProperty ];
  21360. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21361. yield { property, index: subProperty, childNode: child };
  21362. }
  21363. }
  21364. }
  21365. }
  21366. }
  21367. function getValueType( value ) {
  21368. if ( value === undefined || value === null ) return null;
  21369. const typeOf = typeof value;
  21370. if ( value.isNode === true ) {
  21371. return 'node';
  21372. } else if ( typeOf === 'number' ) {
  21373. return 'float';
  21374. } else if ( typeOf === 'boolean' ) {
  21375. return 'bool';
  21376. } else if ( typeOf === 'string' ) {
  21377. return 'string';
  21378. } else if ( typeOf === 'function' ) {
  21379. return 'shader';
  21380. } else if ( value.isVector2 === true ) {
  21381. return 'vec2';
  21382. } else if ( value.isVector3 === true ) {
  21383. return 'vec3';
  21384. } else if ( value.isVector4 === true ) {
  21385. return 'vec4';
  21386. } else if ( value.isMatrix3 === true ) {
  21387. return 'mat3';
  21388. } else if ( value.isMatrix4 === true ) {
  21389. return 'mat4';
  21390. } else if ( value.isColor === true ) {
  21391. return 'color';
  21392. } else if ( value instanceof ArrayBuffer ) {
  21393. return 'ArrayBuffer';
  21394. }
  21395. return null;
  21396. }
  21397. function getValueFromType( type, ...params ) {
  21398. const last4 = type ? type.slice( - 4 ) : undefined;
  21399. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21400. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21401. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21402. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21403. }
  21404. if ( type === 'color' ) {
  21405. return new Color( ...params );
  21406. } else if ( last4 === 'vec2' ) {
  21407. return new Vector2( ...params );
  21408. } else if ( last4 === 'vec3' ) {
  21409. return new Vector3( ...params );
  21410. } else if ( last4 === 'vec4' ) {
  21411. return new Vector4( ...params );
  21412. } else if ( last4 === 'mat3' ) {
  21413. return new Matrix3( ...params );
  21414. } else if ( last4 === 'mat4' ) {
  21415. return new Matrix4( ...params );
  21416. } else if ( type === 'bool' ) {
  21417. return params[ 0 ] || false;
  21418. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21419. return params[ 0 ] || 0;
  21420. } else if ( type === 'string' ) {
  21421. return params[ 0 ] || '';
  21422. } else if ( type === 'ArrayBuffer' ) {
  21423. return base64ToArrayBuffer( params[ 0 ] );
  21424. }
  21425. return null;
  21426. }
  21427. function arrayBufferToBase64( arrayBuffer ) {
  21428. let chars = '';
  21429. const array = new Uint8Array( arrayBuffer );
  21430. for ( let i = 0; i < array.length; i ++ ) {
  21431. chars += String.fromCharCode( array[ i ] );
  21432. }
  21433. return btoa( chars );
  21434. }
  21435. function base64ToArrayBuffer( base64 ) {
  21436. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21437. }
  21438. var NodeUtils = /*#__PURE__*/Object.freeze({
  21439. __proto__: null,
  21440. arrayBufferToBase64: arrayBufferToBase64,
  21441. base64ToArrayBuffer: base64ToArrayBuffer,
  21442. getCacheKey: getCacheKey$1,
  21443. getNodeChildren: getNodeChildren,
  21444. getValueFromType: getValueFromType,
  21445. getValueType: getValueType
  21446. });
  21447. const NodeShaderStage = {
  21448. VERTEX: 'vertex',
  21449. FRAGMENT: 'fragment'
  21450. };
  21451. const NodeUpdateType = {
  21452. NONE: 'none',
  21453. FRAME: 'frame',
  21454. RENDER: 'render',
  21455. OBJECT: 'object'
  21456. };
  21457. const NodeType = {
  21458. BOOLEAN: 'bool',
  21459. INTEGER: 'int',
  21460. FLOAT: 'float',
  21461. VECTOR2: 'vec2',
  21462. VECTOR3: 'vec3',
  21463. VECTOR4: 'vec4',
  21464. MATRIX2: 'mat2',
  21465. MATRIX3: 'mat3',
  21466. MATRIX4: 'mat4'
  21467. };
  21468. const defaultShaderStages = [ 'fragment', 'vertex' ];
  21469. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  21470. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  21471. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  21472. let _nodeId = 0;
  21473. class Node extends EventDispatcher {
  21474. static get type() {
  21475. return 'Node';
  21476. }
  21477. constructor( nodeType = null ) {
  21478. super();
  21479. this.nodeType = nodeType;
  21480. this.updateType = NodeUpdateType.NONE;
  21481. this.updateBeforeType = NodeUpdateType.NONE;
  21482. this.updateAfterType = NodeUpdateType.NONE;
  21483. this.uuid = MathUtils.generateUUID();
  21484. this.version = 0;
  21485. this._cacheKey = null;
  21486. this._cacheKeyVersion = 0;
  21487. this.global = false;
  21488. this.isNode = true;
  21489. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  21490. }
  21491. set needsUpdate( value ) {
  21492. if ( value === true ) {
  21493. this.version ++;
  21494. }
  21495. }
  21496. get type() {
  21497. return this.constructor.type;
  21498. }
  21499. onUpdate( callback, updateType ) {
  21500. this.updateType = updateType;
  21501. this.update = callback.bind( this.getSelf() );
  21502. return this;
  21503. }
  21504. onFrameUpdate( callback ) {
  21505. return this.onUpdate( callback, NodeUpdateType.FRAME );
  21506. }
  21507. onRenderUpdate( callback ) {
  21508. return this.onUpdate( callback, NodeUpdateType.RENDER );
  21509. }
  21510. onObjectUpdate( callback ) {
  21511. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  21512. }
  21513. onReference( callback ) {
  21514. this.updateReference = callback.bind( this.getSelf() );
  21515. return this;
  21516. }
  21517. getSelf() {
  21518. // Returns non-node object.
  21519. return this.self || this;
  21520. }
  21521. updateReference( /*state*/ ) {
  21522. return this;
  21523. }
  21524. isGlobal( /*builder*/ ) {
  21525. return this.global;
  21526. }
  21527. * getChildren() {
  21528. for ( const { childNode } of getNodeChildren( this ) ) {
  21529. yield childNode;
  21530. }
  21531. }
  21532. dispose() {
  21533. this.dispatchEvent( { type: 'dispose' } );
  21534. }
  21535. traverse( callback ) {
  21536. callback( this );
  21537. for ( const childNode of this.getChildren() ) {
  21538. childNode.traverse( callback );
  21539. }
  21540. }
  21541. getCacheKey( force = false ) {
  21542. force = force || this.version !== this._cacheKeyVersion;
  21543. if ( force === true || this._cacheKey === null ) {
  21544. this._cacheKey = getCacheKey$1( this, force );
  21545. this._cacheKeyVersion = this.version;
  21546. }
  21547. return this._cacheKey;
  21548. }
  21549. getScope() {
  21550. return this;
  21551. }
  21552. getHash( /*builder*/ ) {
  21553. return this.uuid;
  21554. }
  21555. getUpdateType() {
  21556. return this.updateType;
  21557. }
  21558. getUpdateBeforeType() {
  21559. return this.updateBeforeType;
  21560. }
  21561. getUpdateAfterType() {
  21562. return this.updateAfterType;
  21563. }
  21564. getElementType( builder ) {
  21565. const type = this.getNodeType( builder );
  21566. const elementType = builder.getElementType( type );
  21567. return elementType;
  21568. }
  21569. getNodeType( builder ) {
  21570. const nodeProperties = builder.getNodeProperties( this );
  21571. if ( nodeProperties.outputNode ) {
  21572. return nodeProperties.outputNode.getNodeType( builder );
  21573. }
  21574. return this.nodeType;
  21575. }
  21576. getShared( builder ) {
  21577. const hash = this.getHash( builder );
  21578. const nodeFromHash = builder.getNodeFromHash( hash );
  21579. return nodeFromHash || this;
  21580. }
  21581. setup( builder ) {
  21582. const nodeProperties = builder.getNodeProperties( this );
  21583. let index = 0;
  21584. for ( const childNode of this.getChildren() ) {
  21585. nodeProperties[ 'node' + index ++ ] = childNode;
  21586. }
  21587. // return a outputNode if exists
  21588. return null;
  21589. }
  21590. analyze( builder ) {
  21591. const usageCount = builder.increaseUsage( this );
  21592. if ( usageCount === 1 ) {
  21593. // node flow children
  21594. const nodeProperties = builder.getNodeProperties( this );
  21595. for ( const childNode of Object.values( nodeProperties ) ) {
  21596. if ( childNode && childNode.isNode === true ) {
  21597. childNode.build( builder );
  21598. }
  21599. }
  21600. }
  21601. }
  21602. generate( builder, output ) {
  21603. const { outputNode } = builder.getNodeProperties( this );
  21604. if ( outputNode && outputNode.isNode === true ) {
  21605. return outputNode.build( builder, output );
  21606. }
  21607. }
  21608. updateBefore( /*frame*/ ) {
  21609. console.warn( 'Abstract function.' );
  21610. }
  21611. updateAfter( /*frame*/ ) {
  21612. console.warn( 'Abstract function.' );
  21613. }
  21614. update( /*frame*/ ) {
  21615. console.warn( 'Abstract function.' );
  21616. }
  21617. build( builder, output = null ) {
  21618. const refNode = this.getShared( builder );
  21619. if ( this !== refNode ) {
  21620. return refNode.build( builder, output );
  21621. }
  21622. builder.addNode( this );
  21623. builder.addChain( this );
  21624. /* Build stages expected results:
  21625. - "setup" -> Node
  21626. - "analyze" -> null
  21627. - "generate" -> String
  21628. */
  21629. let result = null;
  21630. const buildStage = builder.getBuildStage();
  21631. if ( buildStage === 'setup' ) {
  21632. this.updateReference( builder );
  21633. const properties = builder.getNodeProperties( this );
  21634. if ( properties.initialized !== true ) {
  21635. const stackNodesBeforeSetup = builder.stack.nodes.length;
  21636. properties.initialized = true;
  21637. properties.outputNode = this.setup( builder );
  21638. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  21639. for ( const childNode of Object.values( properties ) ) {
  21640. if ( childNode && childNode.isNode === true ) {
  21641. childNode.build( builder );
  21642. }
  21643. }
  21644. }
  21645. } else if ( buildStage === 'analyze' ) {
  21646. this.analyze( builder );
  21647. } else if ( buildStage === 'generate' ) {
  21648. const isGenerateOnce = this.generate.length === 1;
  21649. if ( isGenerateOnce ) {
  21650. const type = this.getNodeType( builder );
  21651. const nodeData = builder.getDataFromNode( this );
  21652. result = nodeData.snippet;
  21653. if ( result === undefined ) {
  21654. result = this.generate( builder ) || '';
  21655. nodeData.snippet = result;
  21656. }
  21657. result = builder.format( result, type, output );
  21658. } else {
  21659. result = this.generate( builder, output ) || '';
  21660. }
  21661. }
  21662. builder.removeChain( this );
  21663. return result;
  21664. }
  21665. getSerializeChildren() {
  21666. return getNodeChildren( this );
  21667. }
  21668. serialize( json ) {
  21669. const nodeChildren = this.getSerializeChildren();
  21670. const inputNodes = {};
  21671. for ( const { property, index, childNode } of nodeChildren ) {
  21672. if ( index !== undefined ) {
  21673. if ( inputNodes[ property ] === undefined ) {
  21674. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  21675. }
  21676. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  21677. } else {
  21678. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  21679. }
  21680. }
  21681. if ( Object.keys( inputNodes ).length > 0 ) {
  21682. json.inputNodes = inputNodes;
  21683. }
  21684. }
  21685. deserialize( json ) {
  21686. if ( json.inputNodes !== undefined ) {
  21687. const nodes = json.meta.nodes;
  21688. for ( const property in json.inputNodes ) {
  21689. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  21690. const inputArray = [];
  21691. for ( const uuid of json.inputNodes[ property ] ) {
  21692. inputArray.push( nodes[ uuid ] );
  21693. }
  21694. this[ property ] = inputArray;
  21695. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  21696. const inputObject = {};
  21697. for ( const subProperty in json.inputNodes[ property ] ) {
  21698. const uuid = json.inputNodes[ property ][ subProperty ];
  21699. inputObject[ subProperty ] = nodes[ uuid ];
  21700. }
  21701. this[ property ] = inputObject;
  21702. } else {
  21703. const uuid = json.inputNodes[ property ];
  21704. this[ property ] = nodes[ uuid ];
  21705. }
  21706. }
  21707. }
  21708. }
  21709. toJSON( meta ) {
  21710. const { uuid, type } = this;
  21711. const isRoot = ( meta === undefined || typeof meta === 'string' );
  21712. if ( isRoot ) {
  21713. meta = {
  21714. textures: {},
  21715. images: {},
  21716. nodes: {}
  21717. };
  21718. }
  21719. // serialize
  21720. let data = meta.nodes[ uuid ];
  21721. if ( data === undefined ) {
  21722. data = {
  21723. uuid,
  21724. type,
  21725. meta,
  21726. metadata: {
  21727. version: 4.6,
  21728. type: 'Node',
  21729. generator: 'Node.toJSON'
  21730. }
  21731. };
  21732. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  21733. this.serialize( data );
  21734. delete data.meta;
  21735. }
  21736. // TODO: Copied from Object3D.toJSON
  21737. function extractFromCache( cache ) {
  21738. const values = [];
  21739. for ( const key in cache ) {
  21740. const data = cache[ key ];
  21741. delete data.metadata;
  21742. values.push( data );
  21743. }
  21744. return values;
  21745. }
  21746. if ( isRoot ) {
  21747. const textures = extractFromCache( meta.textures );
  21748. const images = extractFromCache( meta.images );
  21749. const nodes = extractFromCache( meta.nodes );
  21750. if ( textures.length > 0 ) data.textures = textures;
  21751. if ( images.length > 0 ) data.images = images;
  21752. if ( nodes.length > 0 ) data.nodes = nodes;
  21753. }
  21754. return data;
  21755. }
  21756. }
  21757. class ArrayElementNode extends Node {
  21758. static get type() {
  21759. return 'ArrayElementNode';
  21760. } // @TODO: If extending from TempNode it breaks webgpu_compute
  21761. constructor( node, indexNode ) {
  21762. super();
  21763. this.node = node;
  21764. this.indexNode = indexNode;
  21765. this.isArrayElementNode = true;
  21766. }
  21767. getNodeType( builder ) {
  21768. return this.node.getElementType( builder );
  21769. }
  21770. generate( builder ) {
  21771. const nodeSnippet = this.node.build( builder );
  21772. const indexSnippet = this.indexNode.build( builder, 'uint' );
  21773. return `${nodeSnippet}[ ${indexSnippet} ]`;
  21774. }
  21775. }
  21776. class ConvertNode extends Node {
  21777. static get type() {
  21778. return 'ConvertNode';
  21779. }
  21780. constructor( node, convertTo ) {
  21781. super();
  21782. this.node = node;
  21783. this.convertTo = convertTo;
  21784. }
  21785. getNodeType( builder ) {
  21786. const requestType = this.node.getNodeType( builder );
  21787. let convertTo = null;
  21788. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  21789. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  21790. convertTo = overloadingType;
  21791. }
  21792. }
  21793. return convertTo;
  21794. }
  21795. serialize( data ) {
  21796. super.serialize( data );
  21797. data.convertTo = this.convertTo;
  21798. }
  21799. deserialize( data ) {
  21800. super.deserialize( data );
  21801. this.convertTo = data.convertTo;
  21802. }
  21803. generate( builder, output ) {
  21804. const node = this.node;
  21805. const type = this.getNodeType( builder );
  21806. const snippet = node.build( builder, type );
  21807. return builder.format( snippet, type, output );
  21808. }
  21809. }
  21810. class TempNode extends Node {
  21811. static get type() {
  21812. return 'TempNode';
  21813. }
  21814. constructor( type ) {
  21815. super( type );
  21816. this.isTempNode = true;
  21817. }
  21818. hasDependencies( builder ) {
  21819. return builder.getDataFromNode( this ).usageCount > 1;
  21820. }
  21821. build( builder, output ) {
  21822. const buildStage = builder.getBuildStage();
  21823. if ( buildStage === 'generate' ) {
  21824. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  21825. const nodeData = builder.getDataFromNode( this );
  21826. if ( nodeData.propertyName !== undefined ) {
  21827. return builder.format( nodeData.propertyName, type, output );
  21828. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  21829. const snippet = super.build( builder, type );
  21830. const nodeVar = builder.getVarFromNode( this, null, type );
  21831. const propertyName = builder.getPropertyName( nodeVar );
  21832. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  21833. nodeData.snippet = snippet;
  21834. nodeData.propertyName = propertyName;
  21835. return builder.format( nodeData.propertyName, type, output );
  21836. }
  21837. }
  21838. return super.build( builder, output );
  21839. }
  21840. }
  21841. class JoinNode extends TempNode {
  21842. static get type() {
  21843. return 'JoinNode';
  21844. }
  21845. constructor( nodes = [], nodeType = null ) {
  21846. super( nodeType );
  21847. this.nodes = nodes;
  21848. }
  21849. getNodeType( builder ) {
  21850. if ( this.nodeType !== null ) {
  21851. return builder.getVectorType( this.nodeType );
  21852. }
  21853. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  21854. }
  21855. generate( builder, output ) {
  21856. const type = this.getNodeType( builder );
  21857. const nodes = this.nodes;
  21858. const primitiveType = builder.getComponentType( type );
  21859. const snippetValues = [];
  21860. for ( const input of nodes ) {
  21861. let inputSnippet = input.build( builder );
  21862. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  21863. if ( inputPrimitiveType !== primitiveType ) {
  21864. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  21865. }
  21866. snippetValues.push( inputSnippet );
  21867. }
  21868. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  21869. return builder.format( snippet, type, output );
  21870. }
  21871. }
  21872. const stringVectorComponents = vectorComponents.join( '' );
  21873. class SplitNode extends Node {
  21874. static get type() {
  21875. return 'SplitNode';
  21876. }
  21877. constructor( node, components = 'x' ) {
  21878. super();
  21879. this.node = node;
  21880. this.components = components;
  21881. this.isSplitNode = true;
  21882. }
  21883. getVectorLength() {
  21884. let vectorLength = this.components.length;
  21885. for ( const c of this.components ) {
  21886. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  21887. }
  21888. return vectorLength;
  21889. }
  21890. getComponentType( builder ) {
  21891. return builder.getComponentType( this.node.getNodeType( builder ) );
  21892. }
  21893. getNodeType( builder ) {
  21894. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  21895. }
  21896. generate( builder, output ) {
  21897. const node = this.node;
  21898. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  21899. let snippet = null;
  21900. if ( nodeTypeLength > 1 ) {
  21901. let type = null;
  21902. const componentsLength = this.getVectorLength();
  21903. if ( componentsLength >= nodeTypeLength ) {
  21904. // needed expand the input node
  21905. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  21906. }
  21907. const nodeSnippet = node.build( builder, type );
  21908. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  21909. // unnecessary swizzle
  21910. snippet = builder.format( nodeSnippet, type, output );
  21911. } else {
  21912. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  21913. }
  21914. } else {
  21915. // ignore .components if .node returns float/integer
  21916. snippet = node.build( builder, output );
  21917. }
  21918. return snippet;
  21919. }
  21920. serialize( data ) {
  21921. super.serialize( data );
  21922. data.components = this.components;
  21923. }
  21924. deserialize( data ) {
  21925. super.deserialize( data );
  21926. this.components = data.components;
  21927. }
  21928. }
  21929. class SetNode extends TempNode {
  21930. static get type() {
  21931. return 'SetNode';
  21932. }
  21933. constructor( sourceNode, components, targetNode ) {
  21934. super();
  21935. this.sourceNode = sourceNode;
  21936. this.components = components;
  21937. this.targetNode = targetNode;
  21938. }
  21939. getNodeType( builder ) {
  21940. return this.sourceNode.getNodeType( builder );
  21941. }
  21942. generate( builder ) {
  21943. const { sourceNode, components, targetNode } = this;
  21944. const sourceType = this.getNodeType( builder );
  21945. const targetType = builder.getTypeFromLength( components.length );
  21946. const targetSnippet = targetNode.build( builder, targetType );
  21947. const sourceSnippet = sourceNode.build( builder, sourceType );
  21948. const length = builder.getTypeLength( sourceType );
  21949. const snippetValues = [];
  21950. for ( let i = 0; i < length; i ++ ) {
  21951. const component = vectorComponents[ i ];
  21952. if ( component === components[ 0 ] ) {
  21953. snippetValues.push( targetSnippet );
  21954. i += components.length - 1;
  21955. } else {
  21956. snippetValues.push( sourceSnippet + '.' + component );
  21957. }
  21958. }
  21959. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  21960. }
  21961. }
  21962. class FlipNode extends TempNode {
  21963. static get type() {
  21964. return 'FlipNode';
  21965. }
  21966. constructor( sourceNode, components ) {
  21967. super();
  21968. this.sourceNode = sourceNode;
  21969. this.components = components;
  21970. }
  21971. getNodeType( builder ) {
  21972. return this.sourceNode.getNodeType( builder );
  21973. }
  21974. generate( builder ) {
  21975. const { components, sourceNode } = this;
  21976. const sourceType = this.getNodeType( builder );
  21977. const sourceSnippet = sourceNode.build( builder );
  21978. const sourceCache = builder.getVarFromNode( this );
  21979. const sourceProperty = builder.getPropertyName( sourceCache );
  21980. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet );
  21981. const length = builder.getTypeLength( sourceType );
  21982. const snippetValues = [];
  21983. let componentIndex = 0;
  21984. for ( let i = 0; i < length; i ++ ) {
  21985. const component = vectorComponents[ i ];
  21986. if ( component === components[ componentIndex ] ) {
  21987. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  21988. componentIndex ++;
  21989. } else {
  21990. snippetValues.push( sourceProperty + '.' + component );
  21991. }
  21992. }
  21993. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  21994. }
  21995. }
  21996. class InputNode extends Node {
  21997. static get type() {
  21998. return 'InputNode';
  21999. }
  22000. constructor( value, nodeType = null ) {
  22001. super( nodeType );
  22002. this.isInputNode = true;
  22003. this.value = value;
  22004. this.precision = null;
  22005. }
  22006. getNodeType( /*builder*/ ) {
  22007. if ( this.nodeType === null ) {
  22008. return getValueType( this.value );
  22009. }
  22010. return this.nodeType;
  22011. }
  22012. getInputType( builder ) {
  22013. return this.getNodeType( builder );
  22014. }
  22015. setPrecision( precision ) {
  22016. this.precision = precision;
  22017. return this;
  22018. }
  22019. serialize( data ) {
  22020. super.serialize( data );
  22021. data.value = this.value;
  22022. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22023. data.valueType = getValueType( this.value );
  22024. data.nodeType = this.nodeType;
  22025. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22026. data.precision = this.precision;
  22027. }
  22028. deserialize( data ) {
  22029. super.deserialize( data );
  22030. this.nodeType = data.nodeType;
  22031. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22032. this.precision = data.precision || null;
  22033. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22034. }
  22035. generate( /*builder, output*/ ) {
  22036. console.warn( 'Abstract function.' );
  22037. }
  22038. }
  22039. class ConstNode extends InputNode {
  22040. static get type() {
  22041. return 'ConstNode';
  22042. }
  22043. constructor( value, nodeType = null ) {
  22044. super( value, nodeType );
  22045. this.isConstNode = true;
  22046. }
  22047. generateConst( builder ) {
  22048. return builder.generateConst( this.getNodeType( builder ), this.value );
  22049. }
  22050. generate( builder, output ) {
  22051. const type = this.getNodeType( builder );
  22052. return builder.format( this.generateConst( builder ), type, output );
  22053. }
  22054. }
  22055. //
  22056. let currentStack = null;
  22057. const NodeElements = new Map();
  22058. function addMethodChaining( name, nodeElement ) {
  22059. if ( NodeElements.has( name ) ) {
  22060. console.warn( `Redefinition of method chaining ${ name }` );
  22061. return;
  22062. }
  22063. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22064. NodeElements.set( name, nodeElement );
  22065. }
  22066. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22067. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22068. const shaderNodeHandler = {
  22069. setup( NodeClosure, params ) {
  22070. const inputs = params.shift();
  22071. return NodeClosure( nodeObjects( inputs ), ...params );
  22072. },
  22073. get( node, prop, nodeObj ) {
  22074. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22075. if ( node.isStackNode !== true && prop === 'assign' ) {
  22076. return ( ...params ) => {
  22077. currentStack.assign( nodeObj, ...params );
  22078. return nodeObj;
  22079. };
  22080. } else if ( NodeElements.has( prop ) ) {
  22081. const nodeElement = NodeElements.get( prop );
  22082. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22083. } else if ( prop === 'self' ) {
  22084. return node;
  22085. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22086. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22087. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22088. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22089. // accessing properties ( swizzle )
  22090. prop = parseSwizzle( prop );
  22091. return nodeObject( new SplitNode( nodeObj, prop ) );
  22092. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22093. // set properties ( swizzle ) and sort to xyzw sequence
  22094. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22095. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22096. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22097. // set properties ( swizzle ) and sort to xyzw sequence
  22098. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22099. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22100. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22101. // accessing property
  22102. if ( prop === 'width' ) prop = 'x';
  22103. else if ( prop === 'height' ) prop = 'y';
  22104. else if ( prop === 'depth' ) prop = 'z';
  22105. return nodeObject( new SplitNode( node, prop ) );
  22106. } else if ( /^\d+$/.test( prop ) === true ) {
  22107. // accessing array
  22108. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22109. }
  22110. }
  22111. return Reflect.get( node, prop, nodeObj );
  22112. },
  22113. set( node, prop, value, nodeObj ) {
  22114. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22115. // setting properties
  22116. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22117. nodeObj[ prop ].assign( value );
  22118. return true;
  22119. }
  22120. }
  22121. return Reflect.set( node, prop, value, nodeObj );
  22122. }
  22123. };
  22124. const nodeObjectsCacheMap = new WeakMap();
  22125. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22126. const ShaderNodeObject = function ( obj, altType = null ) {
  22127. const type = getValueType( obj );
  22128. if ( type === 'node' ) {
  22129. let nodeObject = nodeObjectsCacheMap.get( obj );
  22130. if ( nodeObject === undefined ) {
  22131. nodeObject = new Proxy( obj, shaderNodeHandler );
  22132. nodeObjectsCacheMap.set( obj, nodeObject );
  22133. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22134. }
  22135. return nodeObject;
  22136. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22137. return nodeObject( getConstNode( obj, altType ) );
  22138. } else if ( type === 'shader' ) {
  22139. return Fn( obj );
  22140. }
  22141. return obj;
  22142. };
  22143. const ShaderNodeObjects = function ( objects, altType = null ) {
  22144. for ( const name in objects ) {
  22145. objects[ name ] = nodeObject( objects[ name ], altType );
  22146. }
  22147. return objects;
  22148. };
  22149. const ShaderNodeArray = function ( array, altType = null ) {
  22150. const len = array.length;
  22151. for ( let i = 0; i < len; i ++ ) {
  22152. array[ i ] = nodeObject( array[ i ], altType );
  22153. }
  22154. return array;
  22155. };
  22156. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22157. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22158. if ( scope === null ) {
  22159. return ( ...params ) => {
  22160. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22161. };
  22162. } else if ( factor !== null ) {
  22163. factor = nodeObject( factor );
  22164. return ( ...params ) => {
  22165. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22166. };
  22167. } else {
  22168. return ( ...params ) => {
  22169. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22170. };
  22171. }
  22172. };
  22173. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22174. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22175. };
  22176. class ShaderCallNodeInternal extends Node {
  22177. constructor( shaderNode, inputNodes ) {
  22178. super();
  22179. this.shaderNode = shaderNode;
  22180. this.inputNodes = inputNodes;
  22181. }
  22182. getNodeType( builder ) {
  22183. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22184. }
  22185. call( builder ) {
  22186. const { shaderNode, inputNodes } = this;
  22187. const properties = builder.getNodeProperties( shaderNode );
  22188. if ( properties.onceOutput ) return properties.onceOutput;
  22189. //
  22190. let result = null;
  22191. if ( shaderNode.layout ) {
  22192. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22193. if ( functionNodesCacheMap === undefined ) {
  22194. functionNodesCacheMap = new WeakMap();
  22195. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22196. }
  22197. let functionNode = functionNodesCacheMap.get( shaderNode );
  22198. if ( functionNode === undefined ) {
  22199. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22200. functionNodesCacheMap.set( shaderNode, functionNode );
  22201. }
  22202. if ( builder.currentFunctionNode !== null ) {
  22203. builder.currentFunctionNode.includes.push( functionNode );
  22204. }
  22205. result = nodeObject( functionNode.call( inputNodes ) );
  22206. } else {
  22207. const jsFunc = shaderNode.jsFunc;
  22208. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22209. result = nodeObject( outputNode );
  22210. }
  22211. if ( shaderNode.once ) {
  22212. properties.onceOutput = result;
  22213. }
  22214. return result;
  22215. }
  22216. getOutputNode( builder ) {
  22217. const properties = builder.getNodeProperties( this );
  22218. if ( properties.outputNode === null ) {
  22219. properties.outputNode = this.setupOutput( builder );
  22220. }
  22221. return properties.outputNode;
  22222. }
  22223. setup( builder ) {
  22224. return this.getOutputNode( builder );
  22225. }
  22226. setupOutput( builder ) {
  22227. builder.addStack();
  22228. builder.stack.outputNode = this.call( builder );
  22229. return builder.removeStack();
  22230. }
  22231. generate( builder, output ) {
  22232. const outputNode = this.getOutputNode( builder );
  22233. return outputNode.build( builder, output );
  22234. }
  22235. }
  22236. class ShaderNodeInternal extends Node {
  22237. constructor( jsFunc, nodeType ) {
  22238. super( nodeType );
  22239. this.jsFunc = jsFunc;
  22240. this.layout = null;
  22241. this.global = true;
  22242. this.once = false;
  22243. }
  22244. setLayout( layout ) {
  22245. this.layout = layout;
  22246. return this;
  22247. }
  22248. call( inputs = null ) {
  22249. nodeObjects( inputs );
  22250. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22251. }
  22252. setup() {
  22253. return this.call();
  22254. }
  22255. }
  22256. const bools = [ false, true ];
  22257. const uints = [ 0, 1, 2, 3 ];
  22258. const ints = [ - 1, - 2 ];
  22259. 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 ];
  22260. const boolsCacheMap = new Map();
  22261. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22262. const uintsCacheMap = new Map();
  22263. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22264. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22265. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22266. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22267. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22268. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22269. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22270. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22271. const getConstNode = ( value, type ) => {
  22272. if ( constNodesCacheMap.has( value ) ) {
  22273. return constNodesCacheMap.get( value );
  22274. } else if ( value.isNode === true ) {
  22275. return value;
  22276. } else {
  22277. return new ConstNode( value, type );
  22278. }
  22279. };
  22280. const safeGetNodeType = ( node ) => {
  22281. try {
  22282. return node.getNodeType();
  22283. } catch ( _ ) {
  22284. return undefined;
  22285. }
  22286. };
  22287. const ConvertType = function ( type, cacheMap = null ) {
  22288. return ( ...params ) => {
  22289. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22290. params = [ getValueFromType( type, ...params ) ];
  22291. }
  22292. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22293. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22294. }
  22295. if ( params.length === 1 ) {
  22296. const node = getConstNode( params[ 0 ], type );
  22297. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22298. return nodeObject( new ConvertNode( node, type ) );
  22299. }
  22300. const nodes = params.map( param => getConstNode( param ) );
  22301. return nodeObject( new JoinNode( nodes, type ) );
  22302. };
  22303. };
  22304. // exports
  22305. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22306. // utils
  22307. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22308. // shader node base
  22309. function ShaderNode( jsFunc, nodeType ) {
  22310. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22311. }
  22312. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22313. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22314. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22315. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22316. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22317. const Fn = ( jsFunc, nodeType ) => {
  22318. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22319. const fn = ( ...params ) => {
  22320. let inputs;
  22321. nodeObjects( params );
  22322. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22323. inputs = [ ...params ];
  22324. } else {
  22325. inputs = params[ 0 ];
  22326. }
  22327. return shaderNode.call( inputs );
  22328. };
  22329. fn.shaderNode = shaderNode;
  22330. fn.setLayout = ( layout ) => {
  22331. shaderNode.setLayout( layout );
  22332. return fn;
  22333. };
  22334. fn.once = () => {
  22335. shaderNode.once = true;
  22336. return fn;
  22337. };
  22338. return fn;
  22339. };
  22340. const tslFn = ( ...params ) => { // @deprecated, r168
  22341. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22342. return Fn( ...params );
  22343. };
  22344. //
  22345. addMethodChaining( 'toGlobal', ( node ) => {
  22346. node.global = true;
  22347. return node;
  22348. } );
  22349. //
  22350. const setCurrentStack = ( stack ) => {
  22351. currentStack = stack;
  22352. };
  22353. const getCurrentStack = () => currentStack;
  22354. const If = ( ...params ) => currentStack.If( ...params );
  22355. function append( node ) {
  22356. if ( currentStack ) currentStack.add( node );
  22357. return node;
  22358. }
  22359. addMethodChaining( 'append', append );
  22360. // types
  22361. const color = new ConvertType( 'color' );
  22362. const float = new ConvertType( 'float', cacheMaps.float );
  22363. const int = new ConvertType( 'int', cacheMaps.ints );
  22364. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22365. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22366. const vec2 = new ConvertType( 'vec2' );
  22367. const ivec2 = new ConvertType( 'ivec2' );
  22368. const uvec2 = new ConvertType( 'uvec2' );
  22369. const bvec2 = new ConvertType( 'bvec2' );
  22370. const vec3 = new ConvertType( 'vec3' );
  22371. const ivec3 = new ConvertType( 'ivec3' );
  22372. const uvec3 = new ConvertType( 'uvec3' );
  22373. const bvec3 = new ConvertType( 'bvec3' );
  22374. const vec4 = new ConvertType( 'vec4' );
  22375. const ivec4 = new ConvertType( 'ivec4' );
  22376. const uvec4 = new ConvertType( 'uvec4' );
  22377. const bvec4 = new ConvertType( 'bvec4' );
  22378. const mat2 = new ConvertType( 'mat2' );
  22379. const mat3 = new ConvertType( 'mat3' );
  22380. const mat4 = new ConvertType( 'mat4' );
  22381. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22382. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22383. addMethodChaining( 'toColor', color );
  22384. addMethodChaining( 'toFloat', float );
  22385. addMethodChaining( 'toInt', int );
  22386. addMethodChaining( 'toUint', uint );
  22387. addMethodChaining( 'toBool', bool );
  22388. addMethodChaining( 'toVec2', vec2 );
  22389. addMethodChaining( 'toIVec2', ivec2 );
  22390. addMethodChaining( 'toUVec2', uvec2 );
  22391. addMethodChaining( 'toBVec2', bvec2 );
  22392. addMethodChaining( 'toVec3', vec3 );
  22393. addMethodChaining( 'toIVec3', ivec3 );
  22394. addMethodChaining( 'toUVec3', uvec3 );
  22395. addMethodChaining( 'toBVec3', bvec3 );
  22396. addMethodChaining( 'toVec4', vec4 );
  22397. addMethodChaining( 'toIVec4', ivec4 );
  22398. addMethodChaining( 'toUVec4', uvec4 );
  22399. addMethodChaining( 'toBVec4', bvec4 );
  22400. addMethodChaining( 'toMat2', mat2 );
  22401. addMethodChaining( 'toMat3', mat3 );
  22402. addMethodChaining( 'toMat4', mat4 );
  22403. // basic nodes
  22404. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22405. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22406. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22407. addMethodChaining( 'element', element );
  22408. addMethodChaining( 'convert', convert );
  22409. class UniformGroupNode extends Node {
  22410. static get type() {
  22411. return 'UniformGroupNode';
  22412. }
  22413. constructor( name, shared = false, order = 1 ) {
  22414. super( 'string' );
  22415. this.name = name;
  22416. this.version = 0;
  22417. this.shared = shared;
  22418. this.order = order;
  22419. this.isUniformGroup = true;
  22420. }
  22421. set needsUpdate( value ) {
  22422. if ( value === true ) this.version ++;
  22423. }
  22424. serialize( data ) {
  22425. super.serialize( data );
  22426. data.name = this.name;
  22427. data.version = this.version;
  22428. data.shared = this.shared;
  22429. }
  22430. deserialize( data ) {
  22431. super.deserialize( data );
  22432. this.name = data.name;
  22433. this.version = data.version;
  22434. this.shared = data.shared;
  22435. }
  22436. }
  22437. const uniformGroup = ( name ) => new UniformGroupNode( name );
  22438. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  22439. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  22440. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  22441. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  22442. class UniformNode extends InputNode {
  22443. static get type() {
  22444. return 'UniformNode';
  22445. }
  22446. constructor( value, nodeType = null ) {
  22447. super( value, nodeType );
  22448. this.isUniformNode = true;
  22449. this.name = '';
  22450. this.groupNode = objectGroup;
  22451. }
  22452. label( name ) {
  22453. this.name = name;
  22454. return this;
  22455. }
  22456. setGroup( group ) {
  22457. this.groupNode = group;
  22458. return this;
  22459. }
  22460. getGroup() {
  22461. return this.groupNode;
  22462. }
  22463. getUniformHash( builder ) {
  22464. return this.getHash( builder );
  22465. }
  22466. onUpdate( callback, updateType ) {
  22467. const self = this.getSelf();
  22468. callback = callback.bind( self );
  22469. return super.onUpdate( ( frame ) => {
  22470. const value = callback( frame, self );
  22471. if ( value !== undefined ) {
  22472. this.value = value;
  22473. }
  22474. }, updateType );
  22475. }
  22476. generate( builder, output ) {
  22477. const type = this.getNodeType( builder );
  22478. const hash = this.getUniformHash( builder );
  22479. let sharedNode = builder.getNodeFromHash( hash );
  22480. if ( sharedNode === undefined ) {
  22481. builder.setHashNode( this, hash );
  22482. sharedNode = this;
  22483. }
  22484. const sharedNodeType = sharedNode.getInputType( builder );
  22485. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  22486. const propertyName = builder.getPropertyName( nodeUniform );
  22487. if ( builder.context.label !== undefined ) delete builder.context.label;
  22488. return builder.format( propertyName, type, output );
  22489. }
  22490. }
  22491. const uniform = ( arg1, arg2 ) => {
  22492. const nodeType = getConstNodeType( arg2 || arg1 );
  22493. // @TODO: get ConstNode from .traverse() in the future
  22494. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  22495. return nodeObject( new UniformNode( value, nodeType ) );
  22496. };
  22497. class PropertyNode extends Node {
  22498. static get type() {
  22499. return 'PropertyNode';
  22500. }
  22501. constructor( nodeType, name = null, varying = false ) {
  22502. super( nodeType );
  22503. this.name = name;
  22504. this.varying = varying;
  22505. this.isPropertyNode = true;
  22506. }
  22507. getHash( builder ) {
  22508. return this.name || super.getHash( builder );
  22509. }
  22510. isGlobal( /*builder*/ ) {
  22511. return true;
  22512. }
  22513. generate( builder ) {
  22514. let nodeVar;
  22515. if ( this.varying === true ) {
  22516. nodeVar = builder.getVaryingFromNode( this, this.name );
  22517. nodeVar.needsInterpolation = true;
  22518. } else {
  22519. nodeVar = builder.getVarFromNode( this, this.name );
  22520. }
  22521. return builder.getPropertyName( nodeVar );
  22522. }
  22523. }
  22524. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  22525. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  22526. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  22527. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  22528. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  22529. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  22530. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  22531. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  22532. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  22533. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  22534. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  22535. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  22536. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  22537. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  22538. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  22539. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  22540. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  22541. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  22542. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  22543. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  22544. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  22545. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  22546. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  22547. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  22548. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  22549. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  22550. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  22551. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  22552. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  22553. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  22554. class AssignNode extends TempNode {
  22555. static get type() {
  22556. return 'AssignNode';
  22557. }
  22558. constructor( targetNode, sourceNode ) {
  22559. super();
  22560. this.targetNode = targetNode;
  22561. this.sourceNode = sourceNode;
  22562. }
  22563. hasDependencies() {
  22564. return false;
  22565. }
  22566. getNodeType( builder, output ) {
  22567. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  22568. }
  22569. needsSplitAssign( builder ) {
  22570. const { targetNode } = this;
  22571. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  22572. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  22573. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  22574. return assignDiferentVector;
  22575. }
  22576. return false;
  22577. }
  22578. generate( builder, output ) {
  22579. const { targetNode, sourceNode } = this;
  22580. const needsSplitAssign = this.needsSplitAssign( builder );
  22581. const targetType = targetNode.getNodeType( builder );
  22582. const target = targetNode.context( { assign: true } ).build( builder );
  22583. const source = sourceNode.build( builder, targetType );
  22584. const sourceType = sourceNode.getNodeType( builder );
  22585. const nodeData = builder.getDataFromNode( this );
  22586. //
  22587. let snippet;
  22588. if ( nodeData.initialized === true ) {
  22589. if ( output !== 'void' ) {
  22590. snippet = target;
  22591. }
  22592. } else if ( needsSplitAssign ) {
  22593. const sourceVar = builder.getVarFromNode( this, null, targetType );
  22594. const sourceProperty = builder.getPropertyName( sourceVar );
  22595. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  22596. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  22597. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  22598. const component = targetNode.components[ i ];
  22599. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  22600. }
  22601. if ( output !== 'void' ) {
  22602. snippet = target;
  22603. }
  22604. } else {
  22605. snippet = `${ target } = ${ source }`;
  22606. if ( output === 'void' || sourceType === 'void' ) {
  22607. builder.addLineFlowCode( snippet );
  22608. if ( output !== 'void' ) {
  22609. snippet = target;
  22610. }
  22611. }
  22612. }
  22613. nodeData.initialized = true;
  22614. return builder.format( snippet, targetType, output );
  22615. }
  22616. }
  22617. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  22618. addMethodChaining( 'assign', assign );
  22619. class FunctionCallNode extends TempNode {
  22620. static get type() {
  22621. return 'FunctionCallNode';
  22622. }
  22623. constructor( functionNode = null, parameters = {} ) {
  22624. super();
  22625. this.functionNode = functionNode;
  22626. this.parameters = parameters;
  22627. }
  22628. setParameters( parameters ) {
  22629. this.parameters = parameters;
  22630. return this;
  22631. }
  22632. getParameters() {
  22633. return this.parameters;
  22634. }
  22635. getNodeType( builder ) {
  22636. return this.functionNode.getNodeType( builder );
  22637. }
  22638. generate( builder ) {
  22639. const params = [];
  22640. const functionNode = this.functionNode;
  22641. const inputs = functionNode.getInputs( builder );
  22642. const parameters = this.parameters;
  22643. if ( Array.isArray( parameters ) ) {
  22644. for ( let i = 0; i < parameters.length; i ++ ) {
  22645. const inputNode = inputs[ i ];
  22646. const node = parameters[ i ];
  22647. params.push( node.build( builder, inputNode.type ) );
  22648. }
  22649. } else {
  22650. for ( const inputNode of inputs ) {
  22651. const node = parameters[ inputNode.name ];
  22652. if ( node !== undefined ) {
  22653. params.push( node.build( builder, inputNode.type ) );
  22654. } else {
  22655. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  22656. }
  22657. }
  22658. }
  22659. const functionName = functionNode.build( builder, 'property' );
  22660. return `${functionName}( ${params.join( ', ' )} )`;
  22661. }
  22662. }
  22663. const call = ( func, ...params ) => {
  22664. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  22665. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  22666. };
  22667. addMethodChaining( 'call', call );
  22668. class OperatorNode extends TempNode {
  22669. static get type() {
  22670. return 'OperatorNode';
  22671. }
  22672. constructor( op, aNode, bNode, ...params ) {
  22673. super();
  22674. if ( params.length > 0 ) {
  22675. let finalOp = new OperatorNode( op, aNode, bNode );
  22676. for ( let i = 0; i < params.length - 1; i ++ ) {
  22677. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  22678. }
  22679. aNode = finalOp;
  22680. bNode = params[ params.length - 1 ];
  22681. }
  22682. this.op = op;
  22683. this.aNode = aNode;
  22684. this.bNode = bNode;
  22685. }
  22686. getNodeType( builder, output ) {
  22687. const op = this.op;
  22688. const aNode = this.aNode;
  22689. const bNode = this.bNode;
  22690. const typeA = aNode.getNodeType( builder );
  22691. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  22692. if ( typeA === 'void' || typeB === 'void' ) {
  22693. return 'void';
  22694. } else if ( op === '%' ) {
  22695. return typeA;
  22696. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  22697. return builder.getIntegerType( typeA );
  22698. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  22699. return 'bool';
  22700. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  22701. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  22702. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  22703. } else {
  22704. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  22705. return typeB;
  22706. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  22707. // matrix x vector
  22708. return builder.getVectorFromMatrix( typeA );
  22709. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  22710. // vector x matrix
  22711. return builder.getVectorFromMatrix( typeB );
  22712. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  22713. // anytype x anytype: use the greater length vector
  22714. return typeB;
  22715. }
  22716. return typeA;
  22717. }
  22718. }
  22719. generate( builder, output ) {
  22720. const op = this.op;
  22721. const aNode = this.aNode;
  22722. const bNode = this.bNode;
  22723. const type = this.getNodeType( builder, output );
  22724. let typeA = null;
  22725. let typeB = null;
  22726. if ( type !== 'void' ) {
  22727. typeA = aNode.getNodeType( builder );
  22728. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  22729. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  22730. if ( builder.isVector( typeA ) ) {
  22731. typeB = typeA;
  22732. } else if ( typeA !== typeB ) {
  22733. typeA = typeB = 'float';
  22734. }
  22735. } else if ( op === '>>' || op === '<<' ) {
  22736. typeA = type;
  22737. typeB = builder.changeComponentType( typeB, 'uint' );
  22738. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  22739. // matrix x vector
  22740. typeB = builder.getVectorFromMatrix( typeA );
  22741. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  22742. // vector x matrix
  22743. typeA = builder.getVectorFromMatrix( typeB );
  22744. } else {
  22745. // anytype x anytype
  22746. typeA = typeB = type;
  22747. }
  22748. } else {
  22749. typeA = typeB = type;
  22750. }
  22751. const a = aNode.build( builder, typeA );
  22752. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  22753. const outputLength = builder.getTypeLength( output );
  22754. const fnOpSnippet = builder.getFunctionOperator( op );
  22755. if ( output !== 'void' ) {
  22756. if ( op === '<' && outputLength > 1 ) {
  22757. if ( builder.useComparisonMethod ) {
  22758. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  22759. } else {
  22760. return builder.format( `( ${ a } < ${ b } )`, type, output );
  22761. }
  22762. } else if ( op === '<=' && outputLength > 1 ) {
  22763. if ( builder.useComparisonMethod ) {
  22764. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  22765. } else {
  22766. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  22767. }
  22768. } else if ( op === '>' && outputLength > 1 ) {
  22769. if ( builder.useComparisonMethod ) {
  22770. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  22771. } else {
  22772. return builder.format( `( ${ a } > ${ b } )`, type, output );
  22773. }
  22774. } else if ( op === '>=' && outputLength > 1 ) {
  22775. if ( builder.useComparisonMethod ) {
  22776. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  22777. } else {
  22778. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  22779. }
  22780. } else if ( op === '!' || op === '~' ) {
  22781. return builder.format( `(${op}${a})`, typeA, output );
  22782. } else if ( fnOpSnippet ) {
  22783. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  22784. } else {
  22785. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  22786. }
  22787. } else if ( typeA !== 'void' ) {
  22788. if ( fnOpSnippet ) {
  22789. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  22790. } else {
  22791. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  22792. }
  22793. }
  22794. }
  22795. serialize( data ) {
  22796. super.serialize( data );
  22797. data.op = this.op;
  22798. }
  22799. deserialize( data ) {
  22800. super.deserialize( data );
  22801. this.op = data.op;
  22802. }
  22803. }
  22804. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  22805. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  22806. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  22807. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  22808. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  22809. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  22810. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  22811. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  22812. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  22813. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  22814. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  22815. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  22816. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  22817. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  22818. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  22819. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  22820. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  22821. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  22822. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  22823. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  22824. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  22825. addMethodChaining( 'add', add );
  22826. addMethodChaining( 'sub', sub );
  22827. addMethodChaining( 'mul', mul );
  22828. addMethodChaining( 'div', div );
  22829. addMethodChaining( 'modInt', modInt );
  22830. addMethodChaining( 'equal', equal );
  22831. addMethodChaining( 'notEqual', notEqual );
  22832. addMethodChaining( 'lessThan', lessThan );
  22833. addMethodChaining( 'greaterThan', greaterThan );
  22834. addMethodChaining( 'lessThanEqual', lessThanEqual );
  22835. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  22836. addMethodChaining( 'and', and );
  22837. addMethodChaining( 'or', or );
  22838. addMethodChaining( 'not', not );
  22839. addMethodChaining( 'xor', xor );
  22840. addMethodChaining( 'bitAnd', bitAnd );
  22841. addMethodChaining( 'bitNot', bitNot );
  22842. addMethodChaining( 'bitOr', bitOr );
  22843. addMethodChaining( 'bitXor', bitXor );
  22844. addMethodChaining( 'shiftLeft', shiftLeft );
  22845. addMethodChaining( 'shiftRight', shiftRight );
  22846. const remainder = ( ...params ) => { // @deprecated, r168
  22847. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  22848. return modInt( ...params );
  22849. };
  22850. addMethodChaining( 'remainder', remainder );
  22851. class MathNode extends TempNode {
  22852. static get type() {
  22853. return 'MathNode';
  22854. }
  22855. constructor( method, aNode, bNode = null, cNode = null ) {
  22856. super();
  22857. this.method = method;
  22858. this.aNode = aNode;
  22859. this.bNode = bNode;
  22860. this.cNode = cNode;
  22861. }
  22862. getInputType( builder ) {
  22863. const aType = this.aNode.getNodeType( builder );
  22864. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  22865. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  22866. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  22867. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  22868. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  22869. if ( aLen > bLen && aLen > cLen ) {
  22870. return aType;
  22871. } else if ( bLen > cLen ) {
  22872. return bType;
  22873. } else if ( cLen > aLen ) {
  22874. return cType;
  22875. }
  22876. return aType;
  22877. }
  22878. getNodeType( builder ) {
  22879. const method = this.method;
  22880. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  22881. return 'float';
  22882. } else if ( method === MathNode.CROSS ) {
  22883. return 'vec3';
  22884. } else if ( method === MathNode.ALL ) {
  22885. return 'bool';
  22886. } else if ( method === MathNode.EQUALS ) {
  22887. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  22888. } else if ( method === MathNode.MOD ) {
  22889. return this.aNode.getNodeType( builder );
  22890. } else {
  22891. return this.getInputType( builder );
  22892. }
  22893. }
  22894. generate( builder, output ) {
  22895. const method = this.method;
  22896. const type = this.getNodeType( builder );
  22897. const inputType = this.getInputType( builder );
  22898. const a = this.aNode;
  22899. const b = this.bNode;
  22900. const c = this.cNode;
  22901. const isWebGL = builder.renderer.isWebGLRenderer === true;
  22902. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  22903. // dir can be either a direction vector or a normal vector
  22904. // upper-left 3x3 of matrix is assumed to be orthogonal
  22905. let tA = a;
  22906. let tB = b;
  22907. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  22908. tB = vec4( vec3( tB ), 0.0 );
  22909. } else {
  22910. tA = vec4( vec3( tA ), 0.0 );
  22911. }
  22912. const mulNode = mul( tA, tB ).xyz;
  22913. return normalize( mulNode ).build( builder, output );
  22914. } else if ( method === MathNode.NEGATE ) {
  22915. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  22916. } else if ( method === MathNode.ONE_MINUS ) {
  22917. return sub( 1.0, a ).build( builder, output );
  22918. } else if ( method === MathNode.RECIPROCAL ) {
  22919. return div( 1.0, a ).build( builder, output );
  22920. } else if ( method === MathNode.DIFFERENCE ) {
  22921. return abs( sub( a, b ) ).build( builder, output );
  22922. } else {
  22923. const params = [];
  22924. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  22925. params.push(
  22926. a.build( builder, type ),
  22927. b.build( builder, type )
  22928. );
  22929. } else if ( isWebGL && method === MathNode.STEP ) {
  22930. params.push(
  22931. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  22932. b.build( builder, inputType )
  22933. );
  22934. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  22935. params.push(
  22936. a.build( builder, inputType ),
  22937. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  22938. );
  22939. } else if ( method === MathNode.REFRACT ) {
  22940. params.push(
  22941. a.build( builder, inputType ),
  22942. b.build( builder, inputType ),
  22943. c.build( builder, 'float' )
  22944. );
  22945. } else if ( method === MathNode.MIX ) {
  22946. params.push(
  22947. a.build( builder, inputType ),
  22948. b.build( builder, inputType ),
  22949. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  22950. );
  22951. } else {
  22952. params.push( a.build( builder, inputType ) );
  22953. if ( b !== null ) params.push( b.build( builder, inputType ) );
  22954. if ( c !== null ) params.push( c.build( builder, inputType ) );
  22955. }
  22956. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  22957. }
  22958. }
  22959. serialize( data ) {
  22960. super.serialize( data );
  22961. data.method = this.method;
  22962. }
  22963. deserialize( data ) {
  22964. super.deserialize( data );
  22965. this.method = data.method;
  22966. }
  22967. }
  22968. // 1 input
  22969. MathNode.ALL = 'all';
  22970. MathNode.ANY = 'any';
  22971. MathNode.EQUALS = 'equals';
  22972. MathNode.RADIANS = 'radians';
  22973. MathNode.DEGREES = 'degrees';
  22974. MathNode.EXP = 'exp';
  22975. MathNode.EXP2 = 'exp2';
  22976. MathNode.LOG = 'log';
  22977. MathNode.LOG2 = 'log2';
  22978. MathNode.SQRT = 'sqrt';
  22979. MathNode.INVERSE_SQRT = 'inversesqrt';
  22980. MathNode.FLOOR = 'floor';
  22981. MathNode.CEIL = 'ceil';
  22982. MathNode.NORMALIZE = 'normalize';
  22983. MathNode.FRACT = 'fract';
  22984. MathNode.SIN = 'sin';
  22985. MathNode.COS = 'cos';
  22986. MathNode.TAN = 'tan';
  22987. MathNode.ASIN = 'asin';
  22988. MathNode.ACOS = 'acos';
  22989. MathNode.ATAN = 'atan';
  22990. MathNode.ABS = 'abs';
  22991. MathNode.SIGN = 'sign';
  22992. MathNode.LENGTH = 'length';
  22993. MathNode.NEGATE = 'negate';
  22994. MathNode.ONE_MINUS = 'oneMinus';
  22995. MathNode.DFDX = 'dFdx';
  22996. MathNode.DFDY = 'dFdy';
  22997. MathNode.ROUND = 'round';
  22998. MathNode.RECIPROCAL = 'reciprocal';
  22999. MathNode.TRUNC = 'trunc';
  23000. MathNode.FWIDTH = 'fwidth';
  23001. MathNode.BITCAST = 'bitcast';
  23002. MathNode.TRANSPOSE = 'transpose';
  23003. // 2 inputs
  23004. MathNode.ATAN2 = 'atan2';
  23005. MathNode.MIN = 'min';
  23006. MathNode.MAX = 'max';
  23007. MathNode.MOD = 'mod';
  23008. MathNode.STEP = 'step';
  23009. MathNode.REFLECT = 'reflect';
  23010. MathNode.DISTANCE = 'distance';
  23011. MathNode.DIFFERENCE = 'difference';
  23012. MathNode.DOT = 'dot';
  23013. MathNode.CROSS = 'cross';
  23014. MathNode.POW = 'pow';
  23015. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23016. // 3 inputs
  23017. MathNode.MIX = 'mix';
  23018. MathNode.CLAMP = 'clamp';
  23019. MathNode.REFRACT = 'refract';
  23020. MathNode.SMOOTHSTEP = 'smoothstep';
  23021. MathNode.FACEFORWARD = 'faceforward';
  23022. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23023. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23024. const PI = /*@__PURE__*/ float( Math.PI );
  23025. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23026. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23027. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23028. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23029. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23030. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23031. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23032. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23033. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23034. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23035. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23036. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23037. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23038. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23039. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23040. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23041. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23042. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23043. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23044. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23045. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23046. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23047. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23048. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23049. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23050. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23051. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23052. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23053. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23054. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23055. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23056. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23057. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23058. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23059. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23060. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23061. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23062. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23063. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23064. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23065. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23066. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23067. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23068. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23069. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23070. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23071. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23072. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23073. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23074. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23075. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23076. const lengthSq = ( a ) => dot( a, a );
  23077. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23078. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23079. const saturate = ( value ) => clamp( value );
  23080. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23081. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23082. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23083. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23084. const a = 12.9898, b = 78.233, c = 43758.5453;
  23085. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23086. return fract( sin( sn ).mul( c ) );
  23087. } );
  23088. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23089. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23090. addMethodChaining( 'all', all );
  23091. addMethodChaining( 'any', any );
  23092. addMethodChaining( 'equals', equals );
  23093. addMethodChaining( 'radians', radians );
  23094. addMethodChaining( 'degrees', degrees );
  23095. addMethodChaining( 'exp', exp );
  23096. addMethodChaining( 'exp2', exp2 );
  23097. addMethodChaining( 'log', log );
  23098. addMethodChaining( 'log2', log2 );
  23099. addMethodChaining( 'sqrt', sqrt );
  23100. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23101. addMethodChaining( 'floor', floor );
  23102. addMethodChaining( 'ceil', ceil );
  23103. addMethodChaining( 'normalize', normalize );
  23104. addMethodChaining( 'fract', fract );
  23105. addMethodChaining( 'sin', sin );
  23106. addMethodChaining( 'cos', cos );
  23107. addMethodChaining( 'tan', tan );
  23108. addMethodChaining( 'asin', asin );
  23109. addMethodChaining( 'acos', acos );
  23110. addMethodChaining( 'atan', atan );
  23111. addMethodChaining( 'abs', abs );
  23112. addMethodChaining( 'sign', sign );
  23113. addMethodChaining( 'length', length );
  23114. addMethodChaining( 'lengthSq', lengthSq );
  23115. addMethodChaining( 'negate', negate );
  23116. addMethodChaining( 'oneMinus', oneMinus );
  23117. addMethodChaining( 'dFdx', dFdx );
  23118. addMethodChaining( 'dFdy', dFdy );
  23119. addMethodChaining( 'round', round );
  23120. addMethodChaining( 'reciprocal', reciprocal );
  23121. addMethodChaining( 'trunc', trunc );
  23122. addMethodChaining( 'fwidth', fwidth );
  23123. addMethodChaining( 'atan2', atan2 );
  23124. addMethodChaining( 'min', min$1 );
  23125. addMethodChaining( 'max', max$1 );
  23126. addMethodChaining( 'mod', mod );
  23127. addMethodChaining( 'step', step );
  23128. addMethodChaining( 'reflect', reflect );
  23129. addMethodChaining( 'distance', distance );
  23130. addMethodChaining( 'dot', dot );
  23131. addMethodChaining( 'cross', cross );
  23132. addMethodChaining( 'pow', pow );
  23133. addMethodChaining( 'pow2', pow2 );
  23134. addMethodChaining( 'pow3', pow3 );
  23135. addMethodChaining( 'pow4', pow4 );
  23136. addMethodChaining( 'transformDirection', transformDirection );
  23137. addMethodChaining( 'mix', mixElement );
  23138. addMethodChaining( 'clamp', clamp );
  23139. addMethodChaining( 'refract', refract );
  23140. addMethodChaining( 'smoothstep', smoothstepElement );
  23141. addMethodChaining( 'faceForward', faceForward );
  23142. addMethodChaining( 'difference', difference );
  23143. addMethodChaining( 'saturate', saturate );
  23144. addMethodChaining( 'cbrt', cbrt );
  23145. addMethodChaining( 'transpose', transpose );
  23146. addMethodChaining( 'rand', rand );
  23147. class ConditionalNode extends Node {
  23148. static get type() {
  23149. return 'ConditionalNode';
  23150. }
  23151. constructor( condNode, ifNode, elseNode = null ) {
  23152. super();
  23153. this.condNode = condNode;
  23154. this.ifNode = ifNode;
  23155. this.elseNode = elseNode;
  23156. }
  23157. getNodeType( builder ) {
  23158. const ifType = this.ifNode.getNodeType( builder );
  23159. if ( this.elseNode !== null ) {
  23160. const elseType = this.elseNode.getNodeType( builder );
  23161. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23162. return elseType;
  23163. }
  23164. }
  23165. return ifType;
  23166. }
  23167. setup( builder ) {
  23168. const properties = builder.getNodeProperties( this );
  23169. properties.condNode = this.condNode.cache();
  23170. properties.ifNode = this.ifNode.cache();
  23171. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  23172. }
  23173. generate( builder, output ) {
  23174. const type = this.getNodeType( builder );
  23175. const nodeData = builder.getDataFromNode( this );
  23176. if ( nodeData.nodeProperty !== undefined ) {
  23177. return nodeData.nodeProperty;
  23178. }
  23179. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23180. const needsOutput = output !== 'void';
  23181. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23182. nodeData.nodeProperty = nodeProperty;
  23183. const nodeSnippet = condNode.build( builder, 'bool' );
  23184. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23185. let ifSnippet = ifNode.build( builder, type );
  23186. if ( ifSnippet ) {
  23187. if ( needsOutput ) {
  23188. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23189. } else {
  23190. ifSnippet = 'return ' + ifSnippet + ';';
  23191. }
  23192. }
  23193. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23194. if ( elseNode !== null ) {
  23195. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23196. let elseSnippet = elseNode.build( builder, type );
  23197. if ( elseSnippet ) {
  23198. if ( needsOutput ) {
  23199. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23200. } else {
  23201. elseSnippet = 'return ' + elseSnippet + ';';
  23202. }
  23203. }
  23204. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23205. } else {
  23206. builder.addFlowCode( '\n\n' );
  23207. }
  23208. return builder.format( nodeProperty, type, output );
  23209. }
  23210. }
  23211. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23212. addMethodChaining( 'select', select );
  23213. //
  23214. const cond = ( ...params ) => { // @deprecated, r168
  23215. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23216. return select( ...params );
  23217. };
  23218. addMethodChaining( 'cond', cond );
  23219. class ContextNode extends Node {
  23220. static get type() {
  23221. return 'ContextNode';
  23222. }
  23223. constructor( node, value = {} ) {
  23224. super();
  23225. this.isContextNode = true;
  23226. this.node = node;
  23227. this.value = value;
  23228. }
  23229. getScope() {
  23230. return this.node.getScope();
  23231. }
  23232. getNodeType( builder ) {
  23233. return this.node.getNodeType( builder );
  23234. }
  23235. analyze( builder ) {
  23236. this.node.build( builder );
  23237. }
  23238. setup( builder ) {
  23239. const previousContext = builder.getContext();
  23240. builder.setContext( { ...builder.context, ...this.value } );
  23241. const node = this.node.build( builder );
  23242. builder.setContext( previousContext );
  23243. return node;
  23244. }
  23245. generate( builder, output ) {
  23246. const previousContext = builder.getContext();
  23247. builder.setContext( { ...builder.context, ...this.value } );
  23248. const snippet = this.node.build( builder, output );
  23249. builder.setContext( previousContext );
  23250. return snippet;
  23251. }
  23252. }
  23253. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23254. const label = ( node, name ) => context( node, { label: name } );
  23255. addMethodChaining( 'context', context );
  23256. addMethodChaining( 'label', label );
  23257. class VarNode extends Node {
  23258. static get type() {
  23259. return 'VarNode';
  23260. }
  23261. constructor( node, name = null ) {
  23262. super();
  23263. this.node = node;
  23264. this.name = name;
  23265. this.global = true;
  23266. this.isVarNode = true;
  23267. }
  23268. getHash( builder ) {
  23269. return this.name || super.getHash( builder );
  23270. }
  23271. getNodeType( builder ) {
  23272. return this.node.getNodeType( builder );
  23273. }
  23274. generate( builder ) {
  23275. const { node, name } = this;
  23276. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23277. const propertyName = builder.getPropertyName( nodeVar );
  23278. const snippet = node.build( builder, nodeVar.type );
  23279. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23280. return propertyName;
  23281. }
  23282. }
  23283. const temp = /*@__PURE__*/ nodeProxy( VarNode );
  23284. addMethodChaining( 'temp', temp ); // @TODO: Will be removed in the future
  23285. addMethodChaining( 'toVar', ( ...params ) => temp( ...params ).append() );
  23286. class VaryingNode extends Node {
  23287. static get type() {
  23288. return 'VaryingNode';
  23289. }
  23290. constructor( node, name = null ) {
  23291. super();
  23292. this.node = node;
  23293. this.name = name;
  23294. this.isVaryingNode = true;
  23295. }
  23296. isGlobal() {
  23297. return true;
  23298. }
  23299. getHash( builder ) {
  23300. return this.name || super.getHash( builder );
  23301. }
  23302. getNodeType( builder ) {
  23303. // VaryingNode is auto type
  23304. return this.node.getNodeType( builder );
  23305. }
  23306. setupVarying( builder ) {
  23307. const properties = builder.getNodeProperties( this );
  23308. let varying = properties.varying;
  23309. if ( varying === undefined ) {
  23310. const name = this.name;
  23311. const type = this.getNodeType( builder );
  23312. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23313. properties.node = this.node;
  23314. }
  23315. // this property can be used to check if the varying can be optimized for a variable
  23316. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23317. return varying;
  23318. }
  23319. setup( builder ) {
  23320. this.setupVarying( builder );
  23321. }
  23322. analyze( builder ) {
  23323. this.setupVarying( builder );
  23324. return this.node.analyze( builder );
  23325. }
  23326. generate( builder ) {
  23327. const properties = builder.getNodeProperties( this );
  23328. const varying = this.setupVarying( builder );
  23329. if ( properties.propertyName === undefined ) {
  23330. const type = this.getNodeType( builder );
  23331. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23332. // force node run in vertex stage
  23333. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23334. properties.propertyName = propertyName;
  23335. }
  23336. return builder.getPropertyName( varying );
  23337. }
  23338. }
  23339. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23340. addMethodChaining( 'varying', varying );
  23341. const getColorSpaceName = ( colorSpace ) => {
  23342. let method = null;
  23343. if ( colorSpace === LinearSRGBColorSpace ) {
  23344. method = 'Linear';
  23345. } else if ( colorSpace === SRGBColorSpace ) {
  23346. method = 'sRGB';
  23347. }
  23348. return method;
  23349. };
  23350. const getColorSpaceMethod = ( source, target ) => {
  23351. return getColorSpaceName( source ) + 'To' + getColorSpaceName( target );
  23352. };
  23353. class ColorSpaceNode extends TempNode {
  23354. static get type() {
  23355. return 'ColorSpaceNode';
  23356. }
  23357. constructor( colorNode, target = null, source = null ) {
  23358. super( 'vec4' );
  23359. this.colorNode = colorNode;
  23360. this.target = target;
  23361. this.source = source;
  23362. }
  23363. setup( builder ) {
  23364. const { renderer, context } = builder;
  23365. const source = this.source || context.outputColorSpace || renderer.outputColorSpace;
  23366. const target = this.target || context.outputColorSpace || renderer.outputColorSpace;
  23367. const colorNode = this.colorNode;
  23368. if ( source === target ) return colorNode;
  23369. const colorSpace = getColorSpaceMethod( source, target );
  23370. let outputNode = null;
  23371. const colorSpaceFn = renderer.nodes.library.getColorSpaceFunction( colorSpace );
  23372. if ( colorSpaceFn !== null ) {
  23373. outputNode = vec4( colorSpaceFn( colorNode.rgb ), colorNode.a );
  23374. } else {
  23375. console.error( 'ColorSpaceNode: Unsupported Color Space configuration.', colorSpace );
  23376. outputNode = colorNode;
  23377. }
  23378. return outputNode;
  23379. }
  23380. }
  23381. const toOutputColorSpace = ( node, colorSpace = null ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, LinearSRGBColorSpace ) );
  23382. const toWorkingColorSpace = ( node, colorSpace = null ) => nodeObject( new ColorSpaceNode( nodeObject( node ), LinearSRGBColorSpace, colorSpace ) );
  23383. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23384. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  23385. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  23386. static get type() {
  23387. return 'ReferenceElementNode';
  23388. }
  23389. constructor( referenceNode, indexNode ) {
  23390. super( referenceNode, indexNode );
  23391. this.referenceNode = referenceNode;
  23392. this.isReferenceElementNode = true;
  23393. }
  23394. getNodeType() {
  23395. return this.referenceNode.uniformType;
  23396. }
  23397. generate( builder ) {
  23398. const snippet = super.generate( builder );
  23399. const arrayType = this.referenceNode.getNodeType();
  23400. const elementType = this.getNodeType();
  23401. return builder.format( snippet, arrayType, elementType );
  23402. }
  23403. };
  23404. class ReferenceBaseNode extends Node {
  23405. static get type() {
  23406. return 'ReferenceBaseNode';
  23407. }
  23408. constructor( property, uniformType, object = null, count = null ) {
  23409. super();
  23410. this.property = property;
  23411. this.uniformType = uniformType;
  23412. this.object = object;
  23413. this.count = count;
  23414. this.properties = property.split( '.' );
  23415. this.reference = object;
  23416. this.node = null;
  23417. this.updateType = NodeUpdateType.OBJECT;
  23418. }
  23419. element( indexNode ) {
  23420. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  23421. }
  23422. setNodeType( uniformType ) {
  23423. this.node = uniform( null, uniformType ).getSelf();
  23424. }
  23425. getNodeType( builder ) {
  23426. if ( this.node === null ) {
  23427. this.updateValue();
  23428. }
  23429. return this.node.getNodeType( builder );
  23430. }
  23431. getValueFromReference( object = this.reference ) {
  23432. const { properties } = this;
  23433. let value = object[ properties[ 0 ] ];
  23434. for ( let i = 1; i < properties.length; i ++ ) {
  23435. value = value[ properties[ i ] ];
  23436. }
  23437. return value;
  23438. }
  23439. updateReference( state ) {
  23440. this.reference = this.object !== null ? this.object : state.object;
  23441. return this.reference;
  23442. }
  23443. setup() {
  23444. this.updateValue();
  23445. return this.node;
  23446. }
  23447. update( /*frame*/ ) {
  23448. this.updateValue();
  23449. }
  23450. updateValue() {
  23451. if ( this.node === null ) this.setNodeType( this.uniformType );
  23452. const value = this.getValueFromReference();
  23453. if ( Array.isArray( value ) ) {
  23454. this.node.array = value;
  23455. } else {
  23456. this.node.value = value;
  23457. }
  23458. }
  23459. }
  23460. class RendererReferenceNode extends ReferenceBaseNode {
  23461. static get type() {
  23462. return 'RendererReferenceNode';
  23463. }
  23464. constructor( property, inputType, renderer = null ) {
  23465. super( property, inputType, renderer );
  23466. this.renderer = renderer;
  23467. }
  23468. updateReference( state ) {
  23469. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  23470. return this.reference;
  23471. }
  23472. }
  23473. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  23474. class ToneMappingNode extends TempNode {
  23475. static get type() {
  23476. return 'ToneMappingNode';
  23477. }
  23478. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  23479. super( 'vec3' );
  23480. this.toneMapping = toneMapping;
  23481. this.exposureNode = exposureNode;
  23482. this.colorNode = colorNode;
  23483. }
  23484. getCacheKey() {
  23485. let cacheKey = super.getCacheKey();
  23486. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  23487. return cacheKey;
  23488. }
  23489. setup( builder ) {
  23490. const colorNode = this.colorNode || builder.context.color;
  23491. const toneMapping = this.toneMapping;
  23492. if ( toneMapping === NoToneMapping ) return colorNode;
  23493. let outputNode = null;
  23494. const toneMappingFn = builder.renderer.nodes.library.getToneMappingFunction( toneMapping );
  23495. if ( toneMappingFn !== null ) {
  23496. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  23497. } else {
  23498. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  23499. outputNode = colorNode;
  23500. }
  23501. return outputNode;
  23502. }
  23503. }
  23504. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  23505. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  23506. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  23507. class BufferAttributeNode extends InputNode {
  23508. static get type() {
  23509. return 'BufferAttributeNode';
  23510. }
  23511. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  23512. super( value, bufferType );
  23513. this.isBufferNode = true;
  23514. this.bufferType = bufferType;
  23515. this.bufferStride = bufferStride;
  23516. this.bufferOffset = bufferOffset;
  23517. this.usage = StaticDrawUsage;
  23518. this.instanced = false;
  23519. this.attribute = null;
  23520. this.global = true;
  23521. if ( value && value.isBufferAttribute === true ) {
  23522. this.attribute = value;
  23523. this.usage = value.usage;
  23524. this.instanced = value.isInstancedBufferAttribute;
  23525. }
  23526. }
  23527. getHash( builder ) {
  23528. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  23529. let bufferData = builder.globalCache.getData( this.value );
  23530. if ( bufferData === undefined ) {
  23531. bufferData = {
  23532. node: this
  23533. };
  23534. builder.globalCache.setData( this.value, bufferData );
  23535. }
  23536. return bufferData.node.uuid;
  23537. }
  23538. return this.uuid;
  23539. }
  23540. getNodeType( builder ) {
  23541. if ( this.bufferType === null ) {
  23542. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  23543. }
  23544. return this.bufferType;
  23545. }
  23546. setup( builder ) {
  23547. if ( this.attribute !== null ) return;
  23548. const type = this.getNodeType( builder );
  23549. const array = this.value;
  23550. const itemSize = builder.getTypeLength( type );
  23551. const stride = this.bufferStride || itemSize;
  23552. const offset = this.bufferOffset;
  23553. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  23554. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  23555. buffer.setUsage( this.usage );
  23556. this.attribute = bufferAttribute;
  23557. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  23558. }
  23559. generate( builder ) {
  23560. const nodeType = this.getNodeType( builder );
  23561. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  23562. const propertyName = builder.getPropertyName( nodeAttribute );
  23563. let output = null;
  23564. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23565. this.name = propertyName;
  23566. output = propertyName;
  23567. } else {
  23568. const nodeVarying = varying( this );
  23569. output = nodeVarying.build( builder, nodeType );
  23570. }
  23571. return output;
  23572. }
  23573. getInputType( /*builder*/ ) {
  23574. return 'bufferAttribute';
  23575. }
  23576. setUsage( value ) {
  23577. this.usage = value;
  23578. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  23579. this.attribute.usage = value;
  23580. }
  23581. return this;
  23582. }
  23583. setInstanced( value ) {
  23584. this.instanced = value;
  23585. return this;
  23586. }
  23587. }
  23588. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  23589. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  23590. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  23591. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  23592. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  23593. class ComputeNode extends Node {
  23594. static get type() {
  23595. return 'ComputeNode';
  23596. }
  23597. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  23598. super( 'void' );
  23599. this.isComputeNode = true;
  23600. this.computeNode = computeNode;
  23601. this.count = count;
  23602. this.workgroupSize = workgroupSize;
  23603. this.dispatchCount = 0;
  23604. this.version = 1;
  23605. this.updateBeforeType = NodeUpdateType.OBJECT;
  23606. this.updateDispatchCount();
  23607. }
  23608. dispose() {
  23609. this.dispatchEvent( { type: 'dispose' } );
  23610. }
  23611. set needsUpdate( value ) {
  23612. if ( value === true ) this.version ++;
  23613. }
  23614. updateDispatchCount() {
  23615. const { count, workgroupSize } = this;
  23616. let size = workgroupSize[ 0 ];
  23617. for ( let i = 1; i < workgroupSize.length; i ++ )
  23618. size *= workgroupSize[ i ];
  23619. this.dispatchCount = Math.ceil( count / size );
  23620. }
  23621. onInit() { }
  23622. updateBefore( { renderer } ) {
  23623. renderer.compute( this );
  23624. }
  23625. generate( builder ) {
  23626. const { shaderStage } = builder;
  23627. if ( shaderStage === 'compute' ) {
  23628. const snippet = this.computeNode.build( builder, 'void' );
  23629. if ( snippet !== '' ) {
  23630. builder.addLineFlowCode( snippet );
  23631. }
  23632. }
  23633. }
  23634. }
  23635. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  23636. addMethodChaining( 'compute', compute );
  23637. class CacheNode extends Node {
  23638. static get type() {
  23639. return 'CacheNode';
  23640. }
  23641. constructor( node, parent = true ) {
  23642. super();
  23643. this.node = node;
  23644. this.parent = parent;
  23645. this.isCacheNode = true;
  23646. }
  23647. getNodeType( builder ) {
  23648. return this.node.getNodeType( builder );
  23649. }
  23650. build( builder, ...params ) {
  23651. const previousCache = builder.getCache();
  23652. const cache = builder.getCacheFromNode( this, parent );
  23653. builder.setCache( cache );
  23654. const data = this.node.build( builder, ...params );
  23655. builder.setCache( previousCache );
  23656. return data;
  23657. }
  23658. }
  23659. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23660. addMethodChaining( 'cache', cache );
  23661. class BypassNode extends Node {
  23662. static get type() {
  23663. return 'BypassNode';
  23664. }
  23665. constructor( returnNode, callNode ) {
  23666. super();
  23667. this.isBypassNode = true;
  23668. this.outputNode = returnNode;
  23669. this.callNode = callNode;
  23670. }
  23671. getNodeType( builder ) {
  23672. return this.outputNode.getNodeType( builder );
  23673. }
  23674. generate( builder ) {
  23675. const snippet = this.callNode.build( builder, 'void' );
  23676. if ( snippet !== '' ) {
  23677. builder.addLineFlowCode( snippet );
  23678. }
  23679. return this.outputNode.build( builder );
  23680. }
  23681. }
  23682. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  23683. addMethodChaining( 'bypass', bypass );
  23684. class RemapNode extends Node {
  23685. static get type() {
  23686. return 'RemapNode';
  23687. }
  23688. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  23689. super();
  23690. this.node = node;
  23691. this.inLowNode = inLowNode;
  23692. this.inHighNode = inHighNode;
  23693. this.outLowNode = outLowNode;
  23694. this.outHighNode = outHighNode;
  23695. this.doClamp = true;
  23696. }
  23697. setup() {
  23698. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  23699. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  23700. if ( doClamp === true ) t = t.clamp();
  23701. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  23702. }
  23703. }
  23704. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  23705. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  23706. addMethodChaining( 'remap', remap );
  23707. addMethodChaining( 'remapClamp', remapClamp );
  23708. class ExpressionNode extends Node {
  23709. static get type() {
  23710. return 'ExpressionNode';
  23711. }
  23712. constructor( snippet = '', nodeType = 'void' ) {
  23713. super( nodeType );
  23714. this.snippet = snippet;
  23715. }
  23716. generate( builder, output ) {
  23717. const type = this.getNodeType( builder );
  23718. const snippet = this.snippet;
  23719. if ( type === 'void' ) {
  23720. builder.addLineFlowCode( snippet );
  23721. } else {
  23722. return builder.format( `( ${ snippet } )`, type, output );
  23723. }
  23724. }
  23725. }
  23726. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  23727. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  23728. const Return = () => expression( 'return' ).append();
  23729. addMethodChaining( 'discard', Discard );
  23730. class RenderOutputNode extends TempNode {
  23731. static get type() {
  23732. return 'RenderOutputNode';
  23733. }
  23734. constructor( colorNode, toneMapping, outputColorSpace ) {
  23735. super( 'vec4' );
  23736. this.colorNode = colorNode;
  23737. this.toneMapping = toneMapping;
  23738. this.outputColorSpace = outputColorSpace;
  23739. this.isRenderOutput = true;
  23740. }
  23741. setup( { context } ) {
  23742. let outputNode = this.colorNode || context.color;
  23743. // tone mapping
  23744. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  23745. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || LinearSRGBColorSpace;
  23746. if ( toneMapping !== NoToneMapping ) {
  23747. outputNode = outputNode.toneMapping( toneMapping );
  23748. }
  23749. // output color space
  23750. if ( outputColorSpace === SRGBColorSpace ) {
  23751. outputNode = outputNode.toOutputColorSpace( outputColorSpace );
  23752. }
  23753. return outputNode;
  23754. }
  23755. }
  23756. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  23757. addMethodChaining( 'renderOutput', renderOutput );
  23758. // Non-PURE exports list, side-effects are required here.
  23759. // TSL Base Syntax
  23760. function addNodeElement( name/*, nodeElement*/ ) {
  23761. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  23762. }
  23763. class AttributeNode extends Node {
  23764. static get type() {
  23765. return 'AttributeNode';
  23766. }
  23767. constructor( attributeName, nodeType = null ) {
  23768. super( nodeType );
  23769. this.global = true;
  23770. this._attributeName = attributeName;
  23771. }
  23772. getHash( builder ) {
  23773. return this.getAttributeName( builder );
  23774. }
  23775. getNodeType( builder ) {
  23776. let nodeType = this.nodeType;
  23777. if ( nodeType === null ) {
  23778. const attributeName = this.getAttributeName( builder );
  23779. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23780. const attribute = builder.geometry.getAttribute( attributeName );
  23781. nodeType = builder.getTypeFromAttribute( attribute );
  23782. } else {
  23783. nodeType = 'float';
  23784. }
  23785. }
  23786. return nodeType;
  23787. }
  23788. setAttributeName( attributeName ) {
  23789. this._attributeName = attributeName;
  23790. return this;
  23791. }
  23792. getAttributeName( /*builder*/ ) {
  23793. return this._attributeName;
  23794. }
  23795. generate( builder ) {
  23796. const attributeName = this.getAttributeName( builder );
  23797. const nodeType = this.getNodeType( builder );
  23798. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23799. if ( geometryAttribute === true ) {
  23800. const attribute = builder.geometry.getAttribute( attributeName );
  23801. const attributeType = builder.getTypeFromAttribute( attribute );
  23802. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23803. if ( builder.shaderStage === 'vertex' ) {
  23804. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23805. } else {
  23806. const nodeVarying = varying( this );
  23807. return nodeVarying.build( builder, nodeType );
  23808. }
  23809. } else {
  23810. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23811. return builder.generateConst( nodeType );
  23812. }
  23813. }
  23814. serialize( data ) {
  23815. super.serialize( data );
  23816. data.global = this.global;
  23817. data._attributeName = this._attributeName;
  23818. }
  23819. deserialize( data ) {
  23820. super.deserialize( data );
  23821. this.global = data.global;
  23822. this._attributeName = data._attributeName;
  23823. }
  23824. }
  23825. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  23826. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  23827. class TextureSizeNode extends Node {
  23828. static get type() {
  23829. return 'TextureSizeNode';
  23830. }
  23831. constructor( textureNode, levelNode = null ) {
  23832. super( 'uvec2' );
  23833. this.isTextureSizeNode = true;
  23834. this.textureNode = textureNode;
  23835. this.levelNode = levelNode;
  23836. }
  23837. generate( builder, output ) {
  23838. const textureProperty = this.textureNode.build( builder, 'property' );
  23839. const levelNode = this.levelNode.build( builder, 'int' );
  23840. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  23841. }
  23842. }
  23843. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  23844. class MaxMipLevelNode extends UniformNode {
  23845. static get type() {
  23846. return 'MaxMipLevelNode';
  23847. }
  23848. constructor( textureNode ) {
  23849. super( 0 );
  23850. this._textureNode = textureNode;
  23851. this.updateType = NodeUpdateType.FRAME;
  23852. }
  23853. get textureNode() {
  23854. return this._textureNode;
  23855. }
  23856. get texture() {
  23857. return this._textureNode.value;
  23858. }
  23859. update() {
  23860. const texture = this.texture;
  23861. const images = texture.images;
  23862. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  23863. if ( image && image.width !== undefined ) {
  23864. const { width, height } = image;
  23865. this.value = Math.log2( Math.max( width, height ) );
  23866. }
  23867. }
  23868. }
  23869. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  23870. class TextureNode extends UniformNode {
  23871. static get type() {
  23872. return 'TextureNode';
  23873. }
  23874. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  23875. super( value );
  23876. this.isTextureNode = true;
  23877. this.uvNode = uvNode;
  23878. this.levelNode = levelNode;
  23879. this.biasNode = biasNode;
  23880. this.compareNode = null;
  23881. this.depthNode = null;
  23882. this.gradNode = null;
  23883. this.sampler = true;
  23884. this.updateMatrix = false;
  23885. this.updateType = NodeUpdateType.NONE;
  23886. this.referenceNode = null;
  23887. this._value = value;
  23888. this._matrixUniform = null;
  23889. this.setUpdateMatrix( uvNode === null );
  23890. }
  23891. set value( value ) {
  23892. if ( this.referenceNode ) {
  23893. this.referenceNode.value = value;
  23894. } else {
  23895. this._value = value;
  23896. }
  23897. }
  23898. get value() {
  23899. return this.referenceNode ? this.referenceNode.value : this._value;
  23900. }
  23901. getUniformHash( /*builder*/ ) {
  23902. return this.value.uuid;
  23903. }
  23904. getNodeType( /*builder*/ ) {
  23905. if ( this.value.isDepthTexture === true ) return 'float';
  23906. if ( this.value.type === UnsignedIntType ) {
  23907. return 'uvec4';
  23908. } else if ( this.value.type === IntType ) {
  23909. return 'ivec4';
  23910. }
  23911. return 'vec4';
  23912. }
  23913. getInputType( /*builder*/ ) {
  23914. return 'texture';
  23915. }
  23916. getDefaultUV() {
  23917. return uv( this.value.channel );
  23918. }
  23919. updateReference( /*state*/ ) {
  23920. return this.value;
  23921. }
  23922. getTransformedUV( uvNode ) {
  23923. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  23924. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  23925. }
  23926. setUpdateMatrix( value ) {
  23927. this.updateMatrix = value;
  23928. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  23929. return this;
  23930. }
  23931. setupUV( builder, uvNode ) {
  23932. const texture = this.value;
  23933. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  23934. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  23935. }
  23936. return uvNode;
  23937. }
  23938. setup( builder ) {
  23939. const properties = builder.getNodeProperties( this );
  23940. properties.referenceNode = this.referenceNode;
  23941. //
  23942. let uvNode = this.uvNode;
  23943. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  23944. uvNode = builder.context.getUV( this );
  23945. }
  23946. if ( ! uvNode ) uvNode = this.getDefaultUV();
  23947. if ( this.updateMatrix === true ) {
  23948. uvNode = this.getTransformedUV( uvNode );
  23949. }
  23950. uvNode = this.setupUV( builder, uvNode );
  23951. //
  23952. let levelNode = this.levelNode;
  23953. if ( levelNode === null && builder.context.getTextureLevel ) {
  23954. levelNode = builder.context.getTextureLevel( this );
  23955. }
  23956. //
  23957. properties.uvNode = uvNode;
  23958. properties.levelNode = levelNode;
  23959. properties.biasNode = this.biasNode;
  23960. properties.compareNode = this.compareNode;
  23961. properties.gradNode = this.gradNode;
  23962. properties.depthNode = this.depthNode;
  23963. }
  23964. generateUV( builder, uvNode ) {
  23965. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  23966. }
  23967. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  23968. const texture = this.value;
  23969. let snippet;
  23970. if ( levelSnippet ) {
  23971. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  23972. } else if ( biasSnippet ) {
  23973. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  23974. } else if ( gradSnippet ) {
  23975. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  23976. } else if ( compareSnippet ) {
  23977. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  23978. } else if ( this.sampler === false ) {
  23979. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  23980. } else {
  23981. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  23982. }
  23983. return snippet;
  23984. }
  23985. generate( builder, output ) {
  23986. const properties = builder.getNodeProperties( this );
  23987. const texture = this.value;
  23988. if ( ! texture || texture.isTexture !== true ) {
  23989. throw new Error( 'TextureNode: Need a three.js texture.' );
  23990. }
  23991. const textureProperty = super.generate( builder, 'property' );
  23992. if ( output === 'sampler' ) {
  23993. return textureProperty + '_sampler';
  23994. } else if ( builder.isReference( output ) ) {
  23995. return textureProperty;
  23996. } else {
  23997. const nodeData = builder.getDataFromNode( this );
  23998. let propertyName = nodeData.propertyName;
  23999. if ( propertyName === undefined ) {
  24000. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24001. const uvSnippet = this.generateUV( builder, uvNode );
  24002. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24003. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24004. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24005. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24006. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24007. const nodeVar = builder.getVarFromNode( this );
  24008. propertyName = builder.getPropertyName( nodeVar );
  24009. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24010. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24011. nodeData.snippet = snippet;
  24012. nodeData.propertyName = propertyName;
  24013. }
  24014. let snippet = propertyName;
  24015. const nodeType = this.getNodeType( builder );
  24016. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24017. snippet = toWorkingColorSpace( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24018. }
  24019. return builder.format( snippet, nodeType, output );
  24020. }
  24021. }
  24022. setSampler( value ) {
  24023. this.sampler = value;
  24024. return this;
  24025. }
  24026. getSampler() {
  24027. return this.sampler;
  24028. }
  24029. // @TODO: Move to TSL
  24030. uv( uvNode ) {
  24031. const textureNode = this.clone();
  24032. textureNode.uvNode = nodeObject( uvNode );
  24033. textureNode.referenceNode = this.getSelf();
  24034. return nodeObject( textureNode );
  24035. }
  24036. blur( amountNode ) {
  24037. const textureNode = this.clone();
  24038. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24039. textureNode.referenceNode = this.getSelf();
  24040. return nodeObject( textureNode );
  24041. }
  24042. level( levelNode ) {
  24043. const textureNode = this.clone();
  24044. textureNode.levelNode = nodeObject( levelNode );
  24045. textureNode.referenceNode = this.getSelf();
  24046. return nodeObject( textureNode );
  24047. }
  24048. size( levelNode ) {
  24049. return textureSize( this, levelNode );
  24050. }
  24051. bias( biasNode ) {
  24052. const textureNode = this.clone();
  24053. textureNode.biasNode = nodeObject( biasNode );
  24054. textureNode.referenceNode = this.getSelf();
  24055. return nodeObject( textureNode );
  24056. }
  24057. compare( compareNode ) {
  24058. const textureNode = this.clone();
  24059. textureNode.compareNode = nodeObject( compareNode );
  24060. textureNode.referenceNode = this.getSelf();
  24061. return nodeObject( textureNode );
  24062. }
  24063. grad( gradNodeX, gradNodeY ) {
  24064. const textureNode = this.clone();
  24065. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24066. textureNode.referenceNode = this.getSelf();
  24067. return nodeObject( textureNode );
  24068. }
  24069. depth( depthNode ) {
  24070. const textureNode = this.clone();
  24071. textureNode.depthNode = nodeObject( depthNode );
  24072. textureNode.referenceNode = this.getSelf();
  24073. return nodeObject( textureNode );
  24074. }
  24075. // --
  24076. serialize( data ) {
  24077. super.serialize( data );
  24078. data.value = this.value.toJSON( data.meta ).uuid;
  24079. data.sampler = this.sampler;
  24080. data.updateMatrix = this.updateMatrix;
  24081. data.updateType = this.updateType;
  24082. }
  24083. deserialize( data ) {
  24084. super.deserialize( data );
  24085. this.value = data.meta.textures[ data.value ];
  24086. this.sampler = data.sampler;
  24087. this.updateMatrix = data.updateMatrix;
  24088. this.updateType = data.updateType;
  24089. }
  24090. update() {
  24091. const texture = this.value;
  24092. const matrixUniform = this._matrixUniform;
  24093. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24094. if ( texture.matrixAutoUpdate === true ) {
  24095. texture.updateMatrix();
  24096. }
  24097. }
  24098. clone() {
  24099. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24100. newNode.sampler = this.sampler;
  24101. return newNode;
  24102. }
  24103. }
  24104. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24105. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24106. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24107. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24108. const cameraGroup = /*@__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  24109. cameraGroup.needsUpdate = true;
  24110. } );
  24111. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24112. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24113. const cameraLogDepth = /*@__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24114. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24115. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24116. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24117. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24118. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24119. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24120. class Object3DNode extends Node {
  24121. static get type() {
  24122. return 'Object3DNode';
  24123. }
  24124. constructor( scope, object3d = null ) {
  24125. super();
  24126. this.scope = scope;
  24127. this.object3d = object3d;
  24128. this.updateType = NodeUpdateType.OBJECT;
  24129. this._uniformNode = new UniformNode( null );
  24130. }
  24131. getNodeType() {
  24132. const scope = this.scope;
  24133. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24134. return 'mat4';
  24135. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24136. return 'vec3';
  24137. }
  24138. }
  24139. update( frame ) {
  24140. const object = this.object3d;
  24141. const uniformNode = this._uniformNode;
  24142. const scope = this.scope;
  24143. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24144. uniformNode.value = object.matrixWorld;
  24145. } else if ( scope === Object3DNode.POSITION ) {
  24146. uniformNode.value = uniformNode.value || new Vector3();
  24147. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24148. } else if ( scope === Object3DNode.SCALE ) {
  24149. uniformNode.value = uniformNode.value || new Vector3();
  24150. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24151. } else if ( scope === Object3DNode.DIRECTION ) {
  24152. uniformNode.value = uniformNode.value || new Vector3();
  24153. object.getWorldDirection( uniformNode.value );
  24154. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24155. const camera = frame.camera;
  24156. uniformNode.value = uniformNode.value || new Vector3();
  24157. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24158. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24159. }
  24160. }
  24161. generate( builder ) {
  24162. const scope = this.scope;
  24163. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24164. this._uniformNode.nodeType = 'mat4';
  24165. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24166. this._uniformNode.nodeType = 'vec3';
  24167. }
  24168. return this._uniformNode.build( builder );
  24169. }
  24170. serialize( data ) {
  24171. super.serialize( data );
  24172. data.scope = this.scope;
  24173. }
  24174. deserialize( data ) {
  24175. super.deserialize( data );
  24176. this.scope = data.scope;
  24177. }
  24178. }
  24179. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24180. Object3DNode.POSITION = 'position';
  24181. Object3DNode.SCALE = 'scale';
  24182. Object3DNode.VIEW_POSITION = 'viewPosition';
  24183. Object3DNode.DIRECTION = 'direction';
  24184. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24185. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24186. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24187. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24188. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24189. class ModelNode extends Object3DNode {
  24190. static get type() {
  24191. return 'ModelNode';
  24192. }
  24193. constructor( scope ) {
  24194. super( scope );
  24195. }
  24196. update( frame ) {
  24197. this.object3d = frame.object;
  24198. super.update( frame );
  24199. }
  24200. }
  24201. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24202. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24203. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24204. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24205. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24206. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24207. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24208. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24209. builder.context.isHighPrecisionModelViewMatrix = true;
  24210. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24211. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24212. } );
  24213. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24214. const highPrecisionModelNormalMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24215. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24216. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24217. if ( isHighPrecisionModelViewMatrix !== true ) {
  24218. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24219. }
  24220. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24221. } );
  24222. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24223. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24224. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24225. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24226. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24227. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24228. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24229. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24230. class FrontFacingNode extends Node {
  24231. static get type() {
  24232. return 'FrontFacingNode';
  24233. }
  24234. constructor() {
  24235. super( 'bool' );
  24236. this.isFrontFacingNode = true;
  24237. }
  24238. generate( builder ) {
  24239. const { renderer, material } = builder;
  24240. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24241. if ( material.side === BackSide ) {
  24242. return 'false';
  24243. }
  24244. }
  24245. return builder.getFrontFacing();
  24246. }
  24247. }
  24248. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24249. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24250. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24251. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24252. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24253. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24254. return vec3( 0, 1, 0 );
  24255. }
  24256. return normalGeometry;
  24257. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24258. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24259. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24260. let node;
  24261. if ( builder.material.flatShading === true ) {
  24262. node = normalFlat;
  24263. } else {
  24264. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24265. }
  24266. return node;
  24267. }, 'vec3' ).once() )().toVar( 'normalView' );
  24268. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24269. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24270. return builder.context.setupNormal();
  24271. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24272. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24273. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24274. return builder.context.setupClearcoatNormal();
  24275. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24276. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24277. const m = mat3( matrix );
  24278. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24279. return m.mul( transformedNormal ).xyz;
  24280. } );
  24281. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ], builder ) => {
  24282. const modelNormalMatrix = builder.renderer.nodes.modelNormalMatrix;
  24283. if ( modelNormalMatrix !== null ) {
  24284. return modelNormalMatrix.transformDirection( normal );
  24285. }
  24286. return cameraViewMatrix.transformDirection( transformNormal( normal, matrix ) );
  24287. } );
  24288. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24289. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24290. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24291. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24292. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24293. class CubeTextureNode extends TextureNode {
  24294. static get type() {
  24295. return 'CubeTextureNode';
  24296. }
  24297. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24298. super( value, uvNode, levelNode, biasNode );
  24299. this.isCubeTextureNode = true;
  24300. }
  24301. getInputType( /*builder*/ ) {
  24302. return 'cubeTexture';
  24303. }
  24304. getDefaultUV() {
  24305. const texture = this.value;
  24306. if ( texture.mapping === CubeReflectionMapping ) {
  24307. return reflectVector;
  24308. } else if ( texture.mapping === CubeRefractionMapping ) {
  24309. return refractVector;
  24310. } else {
  24311. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24312. return vec3( 0, 0, 0 );
  24313. }
  24314. }
  24315. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24316. setupUV( builder, uvNode ) {
  24317. const texture = this.value;
  24318. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24319. return vec3( uvNode.x.negate(), uvNode.yz );
  24320. } else {
  24321. return uvNode;
  24322. }
  24323. }
  24324. generateUV( builder, cubeUV ) {
  24325. return cubeUV.build( builder, 'vec3' );
  24326. }
  24327. }
  24328. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24329. class BufferNode extends UniformNode {
  24330. static get type() {
  24331. return 'BufferNode';
  24332. }
  24333. constructor( value, bufferType, bufferCount = 0 ) {
  24334. super( value, bufferType );
  24335. this.isBufferNode = true;
  24336. this.bufferType = bufferType;
  24337. this.bufferCount = bufferCount;
  24338. }
  24339. getElementType( builder ) {
  24340. return this.getNodeType( builder );
  24341. }
  24342. getInputType( /*builder*/ ) {
  24343. return 'buffer';
  24344. }
  24345. }
  24346. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24347. class UniformArrayElementNode extends ArrayElementNode {
  24348. static get type() {
  24349. return 'UniformArrayElementNode';
  24350. }
  24351. constructor( arrayBuffer, indexNode ) {
  24352. super( arrayBuffer, indexNode );
  24353. this.isArrayBufferElementNode = true;
  24354. }
  24355. getNodeType( builder ) {
  24356. return this.node.getElementType( builder );
  24357. }
  24358. generate( builder ) {
  24359. const snippet = super.generate( builder );
  24360. const type = this.getNodeType();
  24361. return builder.format( snippet, 'vec4', type );
  24362. }
  24363. }
  24364. class UniformArrayNode extends BufferNode {
  24365. static get type() {
  24366. return 'UniformArrayNode';
  24367. }
  24368. constructor( value, elementType = null ) {
  24369. super( null, 'vec4' );
  24370. this.array = value;
  24371. this.elementType = elementType;
  24372. this._elementType = null;
  24373. this._elementLength = 0;
  24374. this.updateType = NodeUpdateType.RENDER;
  24375. this.isArrayBufferNode = true;
  24376. }
  24377. getElementType() {
  24378. return this.elementType || this._elementType;
  24379. }
  24380. getElementLength() {
  24381. return this._elementLength;
  24382. }
  24383. update( /*frame*/ ) {
  24384. const { array, value } = this;
  24385. const elementLength = this.getElementLength();
  24386. const elementType = this.getElementType();
  24387. if ( elementLength === 1 ) {
  24388. for ( let i = 0; i < array.length; i ++ ) {
  24389. const index = i * 4;
  24390. value[ index ] = array[ i ];
  24391. }
  24392. } else if ( elementType === 'color' ) {
  24393. for ( let i = 0; i < array.length; i ++ ) {
  24394. const index = i * 4;
  24395. const vector = array[ i ];
  24396. value[ index ] = vector.r;
  24397. value[ index + 1 ] = vector.g;
  24398. value[ index + 2 ] = vector.b || 0;
  24399. //value[ index + 3 ] = vector.a || 0;
  24400. }
  24401. } else {
  24402. for ( let i = 0; i < array.length; i ++ ) {
  24403. const index = i * 4;
  24404. const vector = array[ i ];
  24405. value[ index ] = vector.x;
  24406. value[ index + 1 ] = vector.y;
  24407. value[ index + 2 ] = vector.z || 0;
  24408. value[ index + 3 ] = vector.w || 0;
  24409. }
  24410. }
  24411. }
  24412. setup( builder ) {
  24413. const length = this.array.length;
  24414. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24415. this._elementLength = builder.getTypeLength( this._elementType );
  24416. let arrayType = Float32Array;
  24417. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24418. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24419. this.value = new arrayType( length * 4 );
  24420. this.bufferCount = length;
  24421. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24422. return super.setup( builder );
  24423. }
  24424. element( indexNode ) {
  24425. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  24426. }
  24427. }
  24428. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  24429. //
  24430. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  24431. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  24432. return nodeObject( new UniformArrayNode( values, nodeType ) );
  24433. };
  24434. class ReferenceElementNode extends ArrayElementNode {
  24435. static get type() {
  24436. return 'ReferenceElementNode';
  24437. }
  24438. constructor( referenceNode, indexNode ) {
  24439. super( referenceNode, indexNode );
  24440. this.referenceNode = referenceNode;
  24441. this.isReferenceElementNode = true;
  24442. }
  24443. getNodeType() {
  24444. return this.referenceNode.uniformType;
  24445. }
  24446. generate( builder ) {
  24447. const snippet = super.generate( builder );
  24448. const arrayType = this.referenceNode.getNodeType();
  24449. const elementType = this.getNodeType();
  24450. return builder.format( snippet, arrayType, elementType );
  24451. }
  24452. }
  24453. // TODO: Extends this from ReferenceBaseNode
  24454. class ReferenceNode extends Node {
  24455. static get type() {
  24456. return 'ReferenceNode';
  24457. }
  24458. constructor( property, uniformType, object = null, count = null ) {
  24459. super();
  24460. this.property = property;
  24461. this.uniformType = uniformType;
  24462. this.object = object;
  24463. this.count = count;
  24464. this.properties = property.split( '.' );
  24465. this.reference = object;
  24466. this.node = null;
  24467. this.updateType = NodeUpdateType.OBJECT;
  24468. }
  24469. element( indexNode ) {
  24470. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24471. }
  24472. setNodeType( uniformType ) {
  24473. let node = null;
  24474. if ( this.count !== null ) {
  24475. node = buffer( null, uniformType, this.count );
  24476. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24477. node = uniformArray( null, uniformType );
  24478. } else if ( uniformType === 'texture' ) {
  24479. node = texture( null );
  24480. } else if ( uniformType === 'cubeTexture' ) {
  24481. node = cubeTexture( null );
  24482. } else {
  24483. node = uniform( null, uniformType );
  24484. }
  24485. this.node = node.getSelf();
  24486. }
  24487. getNodeType( builder ) {
  24488. if ( this.node === null ) {
  24489. this.updateValue();
  24490. }
  24491. return this.node.getNodeType( builder );
  24492. }
  24493. getValueFromReference( object = this.reference ) {
  24494. const { properties } = this;
  24495. let value = object[ properties[ 0 ] ];
  24496. for ( let i = 1; i < properties.length; i ++ ) {
  24497. value = value[ properties[ i ] ];
  24498. }
  24499. return value;
  24500. }
  24501. updateReference( state ) {
  24502. this.reference = this.object !== null ? this.object : state.object;
  24503. return this.reference;
  24504. }
  24505. setup() {
  24506. this.updateValue();
  24507. return this.node;
  24508. }
  24509. update( /*frame*/ ) {
  24510. this.updateValue();
  24511. }
  24512. updateValue() {
  24513. if ( this.node === null ) this.setNodeType( this.uniformType );
  24514. const value = this.getValueFromReference();
  24515. if ( Array.isArray( value ) ) {
  24516. this.node.array = value;
  24517. } else {
  24518. this.node.value = value;
  24519. }
  24520. }
  24521. }
  24522. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24523. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24524. class MaterialReferenceNode extends ReferenceNode {
  24525. static get type() {
  24526. return 'MaterialReferenceNode';
  24527. }
  24528. constructor( property, inputType, material = null ) {
  24529. super( property, inputType, material );
  24530. this.material = material;
  24531. //this.updateType = NodeUpdateType.RENDER;
  24532. this.isMaterialReferenceNode = true;
  24533. }
  24534. /*setNodeType( node ) {
  24535. super.setNodeType( node );
  24536. this.node.groupNode = renderGroup;
  24537. }*/
  24538. updateReference( state ) {
  24539. this.reference = this.material !== null ? this.material : state.material;
  24540. return this.reference;
  24541. }
  24542. }
  24543. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24544. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  24545. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  24546. builder.geometry.computeTangents();
  24547. }
  24548. return attribute( 'tangent', 'vec4' );
  24549. } )();
  24550. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  24551. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  24552. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  24553. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  24554. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  24555. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  24556. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  24557. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  24558. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  24559. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  24560. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  24561. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  24562. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  24563. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  24564. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  24565. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  24566. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  24567. let bentNormal = anisotropyB.cross( positionViewDirection );
  24568. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  24569. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  24570. return bentNormal;
  24571. } )();
  24572. // Normal Mapping Without Precomputed Tangents
  24573. // http://www.thetenthplanet.de/archives/1180
  24574. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  24575. const { eye_pos, surf_norm, mapN, uv } = inputs;
  24576. const q0 = eye_pos.dFdx();
  24577. const q1 = eye_pos.dFdy();
  24578. const st0 = uv.dFdx();
  24579. const st1 = uv.dFdy();
  24580. const N = surf_norm; // normalized
  24581. const q1perp = q1.cross( N );
  24582. const q0perp = N.cross( q0 );
  24583. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  24584. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  24585. const det = T.dot( T ).max( B.dot( B ) );
  24586. const scale = faceDirection.mul( det.inverseSqrt() );
  24587. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  24588. } );
  24589. class NormalMapNode extends TempNode {
  24590. static get type() {
  24591. return 'NormalMapNode';
  24592. }
  24593. constructor( node, scaleNode = null ) {
  24594. super( 'vec3' );
  24595. this.node = node;
  24596. this.scaleNode = scaleNode;
  24597. this.normalMapType = TangentSpaceNormalMap;
  24598. }
  24599. setup( builder ) {
  24600. const { normalMapType, scaleNode } = this;
  24601. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  24602. if ( scaleNode !== null ) {
  24603. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  24604. }
  24605. let outputNode = null;
  24606. if ( normalMapType === ObjectSpaceNormalMap ) {
  24607. outputNode = transformNormalToView( normalMap );
  24608. } else if ( normalMapType === TangentSpaceNormalMap ) {
  24609. const tangent = builder.hasGeometryAttribute( 'tangent' );
  24610. if ( tangent === true ) {
  24611. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  24612. } else {
  24613. outputNode = perturbNormal2Arb( {
  24614. eye_pos: positionView,
  24615. surf_norm: normalView,
  24616. mapN: normalMap,
  24617. uv: uv()
  24618. } );
  24619. }
  24620. }
  24621. return outputNode;
  24622. }
  24623. }
  24624. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  24625. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  24626. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  24627. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  24628. // It's used to preserve the same TextureNode instance
  24629. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  24630. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  24631. return vec2(
  24632. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  24633. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  24634. ).mul( bumpScale );
  24635. } );
  24636. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  24637. const perturbNormalArb = Fn( ( inputs ) => {
  24638. const { surf_pos, surf_norm, dHdxy } = inputs;
  24639. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  24640. const vSigmaX = surf_pos.dFdx().normalize();
  24641. const vSigmaY = surf_pos.dFdy().normalize();
  24642. const vN = surf_norm; // normalized
  24643. const R1 = vSigmaY.cross( vN );
  24644. const R2 = vN.cross( vSigmaX );
  24645. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  24646. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  24647. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  24648. } );
  24649. class BumpMapNode extends TempNode {
  24650. static get type() {
  24651. return 'BumpMapNode';
  24652. }
  24653. constructor( textureNode, scaleNode = null ) {
  24654. super( 'vec3' );
  24655. this.textureNode = textureNode;
  24656. this.scaleNode = scaleNode;
  24657. }
  24658. setup() {
  24659. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  24660. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  24661. return perturbNormalArb( {
  24662. surf_pos: positionView,
  24663. surf_norm: normalView,
  24664. dHdxy
  24665. } );
  24666. }
  24667. }
  24668. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  24669. const _propertyCache = new Map();
  24670. class MaterialNode extends Node {
  24671. static get type() {
  24672. return 'MaterialNode';
  24673. }
  24674. constructor( scope ) {
  24675. super();
  24676. this.scope = scope;
  24677. }
  24678. getCache( property, type ) {
  24679. let node = _propertyCache.get( property );
  24680. if ( node === undefined ) {
  24681. node = materialReference( property, type );
  24682. _propertyCache.set( property, node );
  24683. }
  24684. return node;
  24685. }
  24686. getFloat( property ) {
  24687. return this.getCache( property, 'float' );
  24688. }
  24689. getColor( property ) {
  24690. return this.getCache( property, 'color' );
  24691. }
  24692. getTexture( property ) {
  24693. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  24694. }
  24695. setup( builder ) {
  24696. const material = builder.context.material;
  24697. const scope = this.scope;
  24698. let node = null;
  24699. if ( scope === MaterialNode.COLOR ) {
  24700. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  24701. if ( material.map && material.map.isTexture === true ) {
  24702. node = colorNode.mul( this.getTexture( 'map' ) );
  24703. } else {
  24704. node = colorNode;
  24705. }
  24706. } else if ( scope === MaterialNode.OPACITY ) {
  24707. const opacityNode = this.getFloat( scope );
  24708. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  24709. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  24710. } else {
  24711. node = opacityNode;
  24712. }
  24713. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  24714. if ( material.specularMap && material.specularMap.isTexture === true ) {
  24715. node = this.getTexture( 'specular' ).r;
  24716. } else {
  24717. node = float( 1 );
  24718. }
  24719. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  24720. const specularIntensity = this.getFloat( scope );
  24721. if ( material.specularMap ) {
  24722. node = specularIntensity.mul( this.getTexture( scope ).a );
  24723. } else {
  24724. node = specularIntensity;
  24725. }
  24726. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  24727. const specularColorNode = this.getColor( scope );
  24728. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  24729. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  24730. } else {
  24731. node = specularColorNode;
  24732. }
  24733. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  24734. const roughnessNode = this.getFloat( scope );
  24735. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  24736. node = roughnessNode.mul( this.getTexture( scope ).g );
  24737. } else {
  24738. node = roughnessNode;
  24739. }
  24740. } else if ( scope === MaterialNode.METALNESS ) {
  24741. const metalnessNode = this.getFloat( scope );
  24742. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  24743. node = metalnessNode.mul( this.getTexture( scope ).b );
  24744. } else {
  24745. node = metalnessNode;
  24746. }
  24747. } else if ( scope === MaterialNode.EMISSIVE ) {
  24748. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  24749. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  24750. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  24751. node = emissiveNode.mul( this.getTexture( scope ) );
  24752. } else {
  24753. node = emissiveNode;
  24754. }
  24755. } else if ( scope === MaterialNode.NORMAL ) {
  24756. if ( material.normalMap ) {
  24757. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  24758. node.normalMapType = material.normalMapType;
  24759. } else if ( material.bumpMap ) {
  24760. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  24761. } else {
  24762. node = normalView;
  24763. }
  24764. } else if ( scope === MaterialNode.CLEARCOAT ) {
  24765. const clearcoatNode = this.getFloat( scope );
  24766. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  24767. node = clearcoatNode.mul( this.getTexture( scope ).r );
  24768. } else {
  24769. node = clearcoatNode;
  24770. }
  24771. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  24772. const clearcoatRoughnessNode = this.getFloat( scope );
  24773. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  24774. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  24775. } else {
  24776. node = clearcoatRoughnessNode;
  24777. }
  24778. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  24779. if ( material.clearcoatNormalMap ) {
  24780. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  24781. } else {
  24782. node = normalView;
  24783. }
  24784. } else if ( scope === MaterialNode.SHEEN ) {
  24785. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  24786. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  24787. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  24788. } else {
  24789. node = sheenNode;
  24790. }
  24791. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  24792. const sheenRoughnessNode = this.getFloat( scope );
  24793. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  24794. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  24795. } else {
  24796. node = sheenRoughnessNode;
  24797. }
  24798. node = node.clamp( 0.07, 1.0 );
  24799. } else if ( scope === MaterialNode.ANISOTROPY ) {
  24800. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  24801. const anisotropyPolar = this.getTexture( scope );
  24802. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  24803. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  24804. } else {
  24805. node = materialAnisotropyVector;
  24806. }
  24807. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  24808. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  24809. if ( material.iridescenceThicknessMap ) {
  24810. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  24811. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  24812. } else {
  24813. node = iridescenceThicknessMaximum;
  24814. }
  24815. } else if ( scope === MaterialNode.TRANSMISSION ) {
  24816. const transmissionNode = this.getFloat( scope );
  24817. if ( material.transmissionMap ) {
  24818. node = transmissionNode.mul( this.getTexture( scope ).r );
  24819. } else {
  24820. node = transmissionNode;
  24821. }
  24822. } else if ( scope === MaterialNode.THICKNESS ) {
  24823. const thicknessNode = this.getFloat( scope );
  24824. if ( material.thicknessMap ) {
  24825. node = thicknessNode.mul( this.getTexture( scope ).g );
  24826. } else {
  24827. node = thicknessNode;
  24828. }
  24829. } else if ( scope === MaterialNode.IOR ) {
  24830. node = this.getFloat( scope );
  24831. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  24832. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  24833. } else if ( scope === MaterialNode.AO_MAP ) {
  24834. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  24835. } else {
  24836. const outputType = this.getNodeType( builder );
  24837. node = this.getCache( scope, outputType );
  24838. }
  24839. return node;
  24840. }
  24841. }
  24842. MaterialNode.ALPHA_TEST = 'alphaTest';
  24843. MaterialNode.COLOR = 'color';
  24844. MaterialNode.OPACITY = 'opacity';
  24845. MaterialNode.SHININESS = 'shininess';
  24846. MaterialNode.SPECULAR = 'specular';
  24847. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  24848. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  24849. MaterialNode.SPECULAR_COLOR = 'specularColor';
  24850. MaterialNode.REFLECTIVITY = 'reflectivity';
  24851. MaterialNode.ROUGHNESS = 'roughness';
  24852. MaterialNode.METALNESS = 'metalness';
  24853. MaterialNode.NORMAL = 'normal';
  24854. MaterialNode.CLEARCOAT = 'clearcoat';
  24855. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  24856. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  24857. MaterialNode.EMISSIVE = 'emissive';
  24858. MaterialNode.ROTATION = 'rotation';
  24859. MaterialNode.SHEEN = 'sheen';
  24860. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  24861. MaterialNode.ANISOTROPY = 'anisotropy';
  24862. MaterialNode.IRIDESCENCE = 'iridescence';
  24863. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  24864. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  24865. MaterialNode.IOR = 'ior';
  24866. MaterialNode.TRANSMISSION = 'transmission';
  24867. MaterialNode.THICKNESS = 'thickness';
  24868. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  24869. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  24870. MaterialNode.LINE_SCALE = 'scale';
  24871. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  24872. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  24873. MaterialNode.LINE_WIDTH = 'linewidth';
  24874. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  24875. MaterialNode.POINT_WIDTH = 'pointWidth';
  24876. MaterialNode.DISPERSION = 'dispersion';
  24877. MaterialNode.LIGHT_MAP = 'light';
  24878. MaterialNode.AO_MAP = 'ao';
  24879. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  24880. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  24881. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  24882. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  24883. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  24884. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  24885. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  24886. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  24887. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  24888. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  24889. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  24890. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  24891. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  24892. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  24893. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  24894. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  24895. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  24896. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  24897. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  24898. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  24899. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  24900. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  24901. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  24902. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  24903. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  24904. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  24905. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  24906. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  24907. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  24908. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  24909. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  24910. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  24911. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  24912. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  24913. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  24914. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  24915. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  24916. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  24917. return frame.material;
  24918. } ).onRenderUpdate( function ( { material } ) {
  24919. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  24920. } );
  24921. class ModelViewProjectionNode extends TempNode {
  24922. static get type() {
  24923. return 'ModelViewProjectionNode';
  24924. }
  24925. constructor( positionNode = null ) {
  24926. super( 'vec4' );
  24927. this.positionNode = positionNode;
  24928. }
  24929. setup( builder ) {
  24930. if ( builder.shaderStage === 'fragment' ) {
  24931. return varying( builder.context.mvp );
  24932. }
  24933. const position = this.positionNode || positionLocal;
  24934. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  24935. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  24936. }
  24937. }
  24938. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  24939. class IndexNode extends Node {
  24940. static get type() {
  24941. return 'IndexNode';
  24942. }
  24943. constructor( scope ) {
  24944. super( 'uint' );
  24945. this.scope = scope;
  24946. this.isInstanceIndexNode = true;
  24947. }
  24948. generate( builder ) {
  24949. const nodeType = this.getNodeType( builder );
  24950. const scope = this.scope;
  24951. let propertyName;
  24952. if ( scope === IndexNode.VERTEX ) {
  24953. propertyName = builder.getVertexIndex();
  24954. } else if ( scope === IndexNode.INSTANCE ) {
  24955. propertyName = builder.getInstanceIndex();
  24956. } else if ( scope === IndexNode.DRAW ) {
  24957. propertyName = builder.getDrawIndex();
  24958. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  24959. propertyName = builder.getInvocationLocalIndex();
  24960. } else {
  24961. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  24962. }
  24963. let output;
  24964. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  24965. output = propertyName;
  24966. } else {
  24967. const nodeVarying = varying( this );
  24968. output = nodeVarying.build( builder, nodeType );
  24969. }
  24970. return output;
  24971. }
  24972. }
  24973. IndexNode.VERTEX = 'vertex';
  24974. IndexNode.INSTANCE = 'instance';
  24975. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  24976. IndexNode.DRAW = 'draw';
  24977. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  24978. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  24979. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  24980. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  24981. class InstanceNode extends Node {
  24982. static get type() {
  24983. return 'InstanceNode';
  24984. }
  24985. constructor( instanceMesh ) {
  24986. super( 'void' );
  24987. this.instanceMesh = instanceMesh;
  24988. this.instanceMatrixNode = null;
  24989. this.instanceColorNode = null;
  24990. this.updateType = NodeUpdateType.FRAME;
  24991. this.buffer = null;
  24992. this.bufferColor = null;
  24993. }
  24994. setup( builder ) {
  24995. let instanceMatrixNode = this.instanceMatrixNode;
  24996. let instanceColorNode = this.instanceColorNode;
  24997. const instanceMesh = this.instanceMesh;
  24998. if ( instanceMatrixNode === null ) {
  24999. const instanceAttribute = instanceMesh.instanceMatrix;
  25000. // 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.
  25001. if ( instanceMesh.count <= 1000 ) {
  25002. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', instanceMesh.count ).element( instanceIndex );
  25003. } else {
  25004. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25005. this.buffer = buffer;
  25006. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25007. const instanceBuffers = [
  25008. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25009. bufferFn( buffer, 'vec4', 16, 0 ),
  25010. bufferFn( buffer, 'vec4', 16, 4 ),
  25011. bufferFn( buffer, 'vec4', 16, 8 ),
  25012. bufferFn( buffer, 'vec4', 16, 12 )
  25013. ];
  25014. instanceMatrixNode = mat4( ...instanceBuffers );
  25015. }
  25016. this.instanceMatrixNode = instanceMatrixNode;
  25017. }
  25018. const instanceColorAttribute = instanceMesh.instanceColor;
  25019. if ( instanceColorAttribute && instanceColorNode === null ) {
  25020. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25021. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25022. this.bufferColor = buffer;
  25023. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25024. this.instanceColorNode = instanceColorNode;
  25025. }
  25026. // POSITION
  25027. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25028. positionLocal.assign( instancePosition );
  25029. // NORMAL
  25030. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25031. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25032. // ASSIGNS
  25033. normalLocal.assign( instanceNormal );
  25034. }
  25035. // COLOR
  25036. if ( this.instanceColorNode !== null ) {
  25037. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25038. }
  25039. }
  25040. update( /*frame*/ ) {
  25041. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25042. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25043. }
  25044. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25045. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25046. }
  25047. }
  25048. }
  25049. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25050. class BatchNode extends Node {
  25051. static get type() {
  25052. return 'BatchNode';
  25053. }
  25054. constructor( batchMesh ) {
  25055. super( 'void' );
  25056. this.batchMesh = batchMesh;
  25057. this.batchingIdNode = null;
  25058. }
  25059. setup( builder ) {
  25060. // POSITION
  25061. if ( this.batchingIdNode === null ) {
  25062. if ( builder.getDrawIndex() === null ) {
  25063. this.batchingIdNode = instanceIndex;
  25064. } else {
  25065. this.batchingIdNode = drawIndex;
  25066. }
  25067. }
  25068. const getIndirectIndex = Fn( ( [ id ] ) => {
  25069. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25070. const x = int( id ).modInt( int( size ) );
  25071. const y = int( id ).div( int( size ) );
  25072. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25073. } ).setLayout( {
  25074. name: 'getIndirectIndex',
  25075. type: 'uint',
  25076. inputs: [
  25077. { name: 'id', type: 'int' }
  25078. ]
  25079. } );
  25080. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25081. const matricesTexture = this.batchMesh._matricesTexture;
  25082. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25083. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25084. const x = j.modInt( size );
  25085. const y = j.div( int( size ) );
  25086. const batchingMatrix = mat4(
  25087. textureLoad( matricesTexture, ivec2( x, y ) ),
  25088. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25089. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25090. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25091. );
  25092. const colorsTexture = this.batchMesh._colorsTexture;
  25093. if ( colorsTexture !== null ) {
  25094. const getBatchingColor = Fn( ( [ id ] ) => {
  25095. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25096. const j = id;
  25097. const x = j.modInt( size );
  25098. const y = j.div( size );
  25099. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25100. } ).setLayout( {
  25101. name: 'getBatchingColor',
  25102. type: 'vec3',
  25103. inputs: [
  25104. { name: 'id', type: 'int' }
  25105. ]
  25106. } );
  25107. const color = getBatchingColor( indirectId );
  25108. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25109. }
  25110. const bm = mat3( batchingMatrix );
  25111. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25112. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25113. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25114. normalLocal.assign( batchingNormal );
  25115. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25116. tangentLocal.mulAssign( bm );
  25117. }
  25118. }
  25119. }
  25120. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25121. const _frameId = new WeakMap();
  25122. class SkinningNode extends Node {
  25123. static get type() {
  25124. return 'SkinningNode';
  25125. }
  25126. constructor( skinnedMesh, useReference = false ) {
  25127. super( 'void' );
  25128. this.skinnedMesh = skinnedMesh;
  25129. this.useReference = useReference;
  25130. this.updateType = NodeUpdateType.OBJECT;
  25131. //
  25132. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25133. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25134. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25135. if ( useReference ) {
  25136. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25137. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25138. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25139. } else {
  25140. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25141. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25142. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25143. }
  25144. this.bindMatrixNode = bindMatrixNode;
  25145. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25146. this.boneMatricesNode = boneMatricesNode;
  25147. this.previousBoneMatricesNode = null;
  25148. }
  25149. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25150. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25151. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25152. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25153. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25154. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25155. // POSITION
  25156. const skinVertex = bindMatrixNode.mul( position );
  25157. const skinned = add(
  25158. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25159. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25160. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25161. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25162. );
  25163. return bindMatrixInverseNode.mul( skinned ).xyz;
  25164. }
  25165. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25166. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25167. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25168. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25169. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25170. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25171. // NORMAL
  25172. let skinMatrix = add(
  25173. skinWeightNode.x.mul( boneMatX ),
  25174. skinWeightNode.y.mul( boneMatY ),
  25175. skinWeightNode.z.mul( boneMatZ ),
  25176. skinWeightNode.w.mul( boneMatW )
  25177. );
  25178. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25179. return skinMatrix.transformDirection( normal ).xyz;
  25180. }
  25181. getPreviousSkinnedPosition( builder ) {
  25182. const skinnedMesh = builder.object;
  25183. if ( this.previousBoneMatricesNode === null ) {
  25184. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25185. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25186. }
  25187. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25188. }
  25189. needsPreviousBoneMatrices( builder ) {
  25190. const mrt = builder.renderer.getMRT();
  25191. return mrt && mrt.has( 'velocity' );
  25192. }
  25193. setup( builder ) {
  25194. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25195. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25196. }
  25197. const skinPosition = this.getSkinnedPosition();
  25198. positionLocal.assign( skinPosition );
  25199. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25200. const skinNormal = this.getSkinnedNormal();
  25201. normalLocal.assign( skinNormal );
  25202. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25203. tangentLocal.assign( skinNormal );
  25204. }
  25205. }
  25206. }
  25207. generate( builder, output ) {
  25208. if ( output !== 'void' ) {
  25209. return positionLocal.build( builder, output );
  25210. }
  25211. }
  25212. update( frame ) {
  25213. const object = this.useReference ? frame.object : this.skinnedMesh;
  25214. const skeleton = object.skeleton;
  25215. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25216. _frameId.set( skeleton, frame.frameId );
  25217. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25218. skeleton.update();
  25219. }
  25220. }
  25221. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25222. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25223. class LoopNode extends Node {
  25224. static get type() {
  25225. return 'LoopNode';
  25226. }
  25227. constructor( params = [] ) {
  25228. super();
  25229. this.params = params;
  25230. }
  25231. getVarName( index ) {
  25232. return String.fromCharCode( 'i'.charCodeAt() + index );
  25233. }
  25234. getProperties( builder ) {
  25235. const properties = builder.getNodeProperties( this );
  25236. if ( properties.stackNode !== undefined ) return properties;
  25237. //
  25238. const inputs = {};
  25239. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25240. const param = this.params[ i ];
  25241. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25242. const type = ( param.isNode !== true && param.type ) || 'int';
  25243. inputs[ name ] = expression( name, type );
  25244. }
  25245. const stack = builder.addStack(); // TODO: cache() it
  25246. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25247. properties.stackNode = stack;
  25248. builder.removeStack();
  25249. return properties;
  25250. }
  25251. getNodeType( builder ) {
  25252. const { returnsNode } = this.getProperties( builder );
  25253. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25254. }
  25255. setup( builder ) {
  25256. // setup properties
  25257. this.getProperties( builder );
  25258. }
  25259. generate( builder ) {
  25260. const properties = this.getProperties( builder );
  25261. const params = this.params;
  25262. const stackNode = properties.stackNode;
  25263. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25264. const param = params[ i ];
  25265. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25266. if ( param.isNode ) {
  25267. type = 'int';
  25268. name = this.getVarName( i );
  25269. start = '0';
  25270. end = param.build( builder, type );
  25271. condition = '<';
  25272. } else {
  25273. type = param.type || 'int';
  25274. name = param.name || this.getVarName( i );
  25275. start = param.start;
  25276. end = param.end;
  25277. condition = param.condition;
  25278. update = param.update;
  25279. if ( typeof start === 'number' ) start = start.toString();
  25280. else if ( start && start.isNode ) start = start.build( builder, type );
  25281. if ( typeof end === 'number' ) end = end.toString();
  25282. else if ( end && end.isNode ) end = end.build( builder, type );
  25283. if ( start !== undefined && end === undefined ) {
  25284. start = start + ' - 1';
  25285. end = '0';
  25286. condition = '>=';
  25287. } else if ( end !== undefined && start === undefined ) {
  25288. start = '0';
  25289. condition = '<';
  25290. }
  25291. if ( condition === undefined ) {
  25292. if ( Number( start ) > Number( end ) ) {
  25293. condition = '>=';
  25294. } else {
  25295. condition = '<';
  25296. }
  25297. }
  25298. }
  25299. const internalParam = { start, end, condition };
  25300. //
  25301. const startSnippet = internalParam.start;
  25302. const endSnippet = internalParam.end;
  25303. let declarationSnippet = '';
  25304. let conditionalSnippet = '';
  25305. let updateSnippet = '';
  25306. if ( ! update ) {
  25307. if ( type === 'int' || type === 'uint' ) {
  25308. if ( condition.includes( '<' ) ) update = '++';
  25309. else update = '--';
  25310. } else {
  25311. if ( condition.includes( '<' ) ) update = '+= 1.';
  25312. else update = '-= 1.';
  25313. }
  25314. }
  25315. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25316. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25317. updateSnippet += name + ' ' + update;
  25318. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25319. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25320. }
  25321. const stackSnippet = stackNode.build( builder, 'void' );
  25322. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25323. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25324. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25325. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25326. }
  25327. builder.addFlowTab();
  25328. return returnsSnippet;
  25329. }
  25330. }
  25331. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25332. const Continue = () => expression( 'continue' ).append();
  25333. const Break = () => expression( 'break' ).append();
  25334. //
  25335. const loop = ( ...params ) => { // @deprecated, r168
  25336. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25337. return Loop( ...params );
  25338. };
  25339. const _morphTextures = /*@__PURE__*/ new WeakMap();
  25340. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25341. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25342. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25343. const y = texelIndex.div( width );
  25344. const x = texelIndex.sub( y.mul( width ) );
  25345. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25346. return bufferAttrib.mul( influence );
  25347. } );
  25348. function getEntry( geometry ) {
  25349. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25350. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25351. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25352. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25353. // into an array of data textures. Each layer represents a single morph target.
  25354. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25355. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25356. let entry = _morphTextures.get( geometry );
  25357. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25358. if ( entry !== undefined ) entry.texture.dispose();
  25359. const morphTargets = geometry.morphAttributes.position || [];
  25360. const morphNormals = geometry.morphAttributes.normal || [];
  25361. const morphColors = geometry.morphAttributes.color || [];
  25362. let vertexDataCount = 0;
  25363. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25364. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25365. if ( hasMorphColors === true ) vertexDataCount = 3;
  25366. let width = geometry.attributes.position.count * vertexDataCount;
  25367. let height = 1;
  25368. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25369. if ( width > maxTextureSize ) {
  25370. height = Math.ceil( width / maxTextureSize );
  25371. width = maxTextureSize;
  25372. }
  25373. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25374. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25375. bufferTexture.type = FloatType;
  25376. bufferTexture.needsUpdate = true;
  25377. // fill buffer
  25378. const vertexDataStride = vertexDataCount * 4;
  25379. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25380. const morphTarget = morphTargets[ i ];
  25381. const morphNormal = morphNormals[ i ];
  25382. const morphColor = morphColors[ i ];
  25383. const offset = width * height * 4 * i;
  25384. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25385. const stride = j * vertexDataStride;
  25386. if ( hasMorphPosition === true ) {
  25387. _morphVec4.fromBufferAttribute( morphTarget, j );
  25388. buffer[ offset + stride + 0 ] = _morphVec4.x;
  25389. buffer[ offset + stride + 1 ] = _morphVec4.y;
  25390. buffer[ offset + stride + 2 ] = _morphVec4.z;
  25391. buffer[ offset + stride + 3 ] = 0;
  25392. }
  25393. if ( hasMorphNormals === true ) {
  25394. _morphVec4.fromBufferAttribute( morphNormal, j );
  25395. buffer[ offset + stride + 4 ] = _morphVec4.x;
  25396. buffer[ offset + stride + 5 ] = _morphVec4.y;
  25397. buffer[ offset + stride + 6 ] = _morphVec4.z;
  25398. buffer[ offset + stride + 7 ] = 0;
  25399. }
  25400. if ( hasMorphColors === true ) {
  25401. _morphVec4.fromBufferAttribute( morphColor, j );
  25402. buffer[ offset + stride + 8 ] = _morphVec4.x;
  25403. buffer[ offset + stride + 9 ] = _morphVec4.y;
  25404. buffer[ offset + stride + 10 ] = _morphVec4.z;
  25405. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  25406. }
  25407. }
  25408. }
  25409. entry = {
  25410. count: morphTargetsCount,
  25411. texture: bufferTexture,
  25412. stride: vertexDataCount,
  25413. size: new Vector2( width, height )
  25414. };
  25415. _morphTextures.set( geometry, entry );
  25416. function disposeTexture() {
  25417. bufferTexture.dispose();
  25418. _morphTextures.delete( geometry );
  25419. geometry.removeEventListener( 'dispose', disposeTexture );
  25420. }
  25421. geometry.addEventListener( 'dispose', disposeTexture );
  25422. }
  25423. return entry;
  25424. }
  25425. class MorphNode extends Node {
  25426. static get type() {
  25427. return 'MorphNode';
  25428. }
  25429. constructor( mesh ) {
  25430. super( 'void' );
  25431. this.mesh = mesh;
  25432. this.morphBaseInfluence = uniform( 1 );
  25433. this.updateType = NodeUpdateType.OBJECT;
  25434. }
  25435. setup( builder ) {
  25436. const { geometry } = builder;
  25437. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25438. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  25439. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25440. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25441. // nodes
  25442. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25443. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25444. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25445. const width = int( size.width );
  25446. Loop( morphTargetsCount, ( { i } ) => {
  25447. const influence = float( 0 ).toVar();
  25448. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25449. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25450. } else {
  25451. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25452. }
  25453. if ( hasMorphPosition === true ) {
  25454. positionLocal.addAssign( getMorph( {
  25455. bufferMap,
  25456. influence,
  25457. stride,
  25458. width,
  25459. depth: i,
  25460. offset: int( 0 )
  25461. } ) );
  25462. }
  25463. if ( hasMorphNormals === true ) {
  25464. normalLocal.addAssign( getMorph( {
  25465. bufferMap,
  25466. influence,
  25467. stride,
  25468. width,
  25469. depth: i,
  25470. offset: int( 1 )
  25471. } ) );
  25472. }
  25473. } );
  25474. }
  25475. update() {
  25476. const morphBaseInfluence = this.morphBaseInfluence;
  25477. if ( this.mesh.geometry.morphTargetsRelative ) {
  25478. morphBaseInfluence.value = 1;
  25479. } else {
  25480. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25481. }
  25482. }
  25483. }
  25484. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  25485. const sortLights = ( lights ) => {
  25486. return lights.sort( ( a, b ) => a.id - b.id );
  25487. };
  25488. const getLightNodeById = ( id, lightNodes ) => {
  25489. for ( const lightNode of lightNodes ) {
  25490. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  25491. return lightNode;
  25492. }
  25493. }
  25494. return null;
  25495. };
  25496. class LightsNode extends Node {
  25497. static get type() {
  25498. return 'LightsNode';
  25499. }
  25500. constructor( lights = [] ) {
  25501. super( 'vec3' );
  25502. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  25503. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  25504. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  25505. this._lights = lights;
  25506. this._lightNodes = null;
  25507. this._lightNodesHash = null;
  25508. this.global = true;
  25509. }
  25510. getHash( builder ) {
  25511. if ( this._lightNodesHash === null ) {
  25512. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25513. const hash = [];
  25514. for ( const lightNode of this._lightNodes ) {
  25515. hash.push( lightNode.getHash() );
  25516. }
  25517. this._lightNodesHash = 'lights-' + hash.join( ',' );
  25518. }
  25519. return this._lightNodesHash;
  25520. }
  25521. analyze( builder ) {
  25522. const properties = builder.getDataFromNode( this );
  25523. for ( const node of properties.nodes ) {
  25524. node.build( builder );
  25525. }
  25526. }
  25527. setupLightsNode( builder ) {
  25528. const lightNodes = [];
  25529. const previousLightNodes = this._lightNodes;
  25530. const lights = sortLights( this._lights );
  25531. const nodeLibrary = builder.renderer.nodes.library;
  25532. for ( const light of lights ) {
  25533. if ( light.isNode ) {
  25534. lightNodes.push( nodeObject( light ) );
  25535. } else {
  25536. let lightNode = null;
  25537. if ( previousLightNodes !== null ) {
  25538. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  25539. }
  25540. if ( lightNode === null ) {
  25541. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  25542. if ( lightNodeClass === null ) {
  25543. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  25544. continue;
  25545. }
  25546. lightNodes.push( nodeObject( new lightNodeClass( light ) ) );
  25547. }
  25548. }
  25549. }
  25550. this._lightNodes = lightNodes;
  25551. }
  25552. setup( builder ) {
  25553. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25554. const context = builder.context;
  25555. const lightingModel = context.lightingModel;
  25556. let outgoingLightNode = this.outgoingLightNode;
  25557. if ( lightingModel ) {
  25558. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  25559. context.outgoingLight = outgoingLightNode;
  25560. const stack = builder.addStack();
  25561. //
  25562. const properties = builder.getDataFromNode( this );
  25563. properties.nodes = stack.nodes;
  25564. //
  25565. lightingModel.start( context, stack, builder );
  25566. // lights
  25567. for ( const lightNode of _lightNodes ) {
  25568. lightNode.build( builder );
  25569. }
  25570. //
  25571. lightingModel.indirect( context, stack, builder );
  25572. //
  25573. const { backdrop, backdropAlpha } = context;
  25574. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  25575. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  25576. if ( backdrop !== null ) {
  25577. if ( backdropAlpha !== null ) {
  25578. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  25579. } else {
  25580. totalDiffuse = vec3( backdrop );
  25581. }
  25582. context.material.transparent = true;
  25583. }
  25584. totalDiffuseNode.assign( totalDiffuse );
  25585. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  25586. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  25587. //
  25588. lightingModel.finish( context, stack, builder );
  25589. //
  25590. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  25591. }
  25592. return outgoingLightNode;
  25593. }
  25594. setLights( lights ) {
  25595. this._lights = lights;
  25596. this._lightNodes = null;
  25597. this._lightNodesHash = null;
  25598. return this;
  25599. }
  25600. getLights() {
  25601. return this._lights;
  25602. }
  25603. }
  25604. const lights = /*@__PURE__*/ nodeProxy( LightsNode );
  25605. class LightingNode extends Node {
  25606. static get type() {
  25607. return 'LightingNode';
  25608. }
  25609. constructor() {
  25610. super( 'vec3' );
  25611. this.isLightingNode = true;
  25612. }
  25613. generate( /*builder*/ ) {
  25614. console.warn( 'Abstract function.' );
  25615. }
  25616. }
  25617. class AONode extends LightingNode {
  25618. static get type() {
  25619. return 'AONode';
  25620. }
  25621. constructor( aoNode = null ) {
  25622. super();
  25623. this.aoNode = aoNode;
  25624. }
  25625. setup( builder ) {
  25626. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  25627. }
  25628. }
  25629. class LightingContextNode extends ContextNode {
  25630. static get type() {
  25631. return 'LightingContextNode';
  25632. }
  25633. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  25634. super( node );
  25635. this.lightingModel = lightingModel;
  25636. this.backdropNode = backdropNode;
  25637. this.backdropAlphaNode = backdropAlphaNode;
  25638. this._value = null;
  25639. }
  25640. getContext() {
  25641. const { backdropNode, backdropAlphaNode } = this;
  25642. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  25643. directSpecular = vec3().toVar( 'directSpecular' ),
  25644. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  25645. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  25646. const reflectedLight = {
  25647. directDiffuse,
  25648. directSpecular,
  25649. indirectDiffuse,
  25650. indirectSpecular
  25651. };
  25652. const context = {
  25653. radiance: vec3().toVar( 'radiance' ),
  25654. irradiance: vec3().toVar( 'irradiance' ),
  25655. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  25656. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  25657. reflectedLight,
  25658. backdrop: backdropNode,
  25659. backdropAlpha: backdropAlphaNode
  25660. };
  25661. return context;
  25662. }
  25663. setup( builder ) {
  25664. this.value = this._value || ( this._value = this.getContext() );
  25665. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  25666. return super.setup( builder );
  25667. }
  25668. }
  25669. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  25670. class IrradianceNode extends LightingNode {
  25671. static get type() {
  25672. return 'IrradianceNode';
  25673. }
  25674. constructor( node ) {
  25675. super();
  25676. this.node = node;
  25677. }
  25678. setup( builder ) {
  25679. builder.context.irradiance.addAssign( this.node );
  25680. }
  25681. }
  25682. let resolution, viewportResult;
  25683. class ViewportNode extends Node {
  25684. static get type() {
  25685. return 'ViewportNode';
  25686. }
  25687. constructor( scope ) {
  25688. super();
  25689. this.scope = scope;
  25690. this.isViewportNode = true;
  25691. }
  25692. getNodeType() {
  25693. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  25694. else return 'vec2';
  25695. }
  25696. getUpdateType() {
  25697. let updateType = NodeUpdateType.NONE;
  25698. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  25699. updateType = NodeUpdateType.RENDER;
  25700. }
  25701. this.updateType = updateType;
  25702. return updateType;
  25703. }
  25704. update( { renderer } ) {
  25705. if ( this.scope === ViewportNode.VIEWPORT ) {
  25706. renderer.getViewport( viewportResult );
  25707. } else {
  25708. renderer.getDrawingBufferSize( resolution );
  25709. }
  25710. }
  25711. setup( /*builder*/ ) {
  25712. const scope = this.scope;
  25713. let output = null;
  25714. if ( scope === ViewportNode.RESOLUTION ) {
  25715. output = uniform( resolution || ( resolution = new Vector2() ) );
  25716. } else if ( scope === ViewportNode.VIEWPORT ) {
  25717. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  25718. } else {
  25719. output = vec2( viewportCoordinate.div( viewportResolution ) );
  25720. }
  25721. return output;
  25722. }
  25723. generate( builder ) {
  25724. if ( this.scope === ViewportNode.COORDINATE ) {
  25725. let coord = builder.getFragCoord();
  25726. if ( builder.isFlipY() ) {
  25727. // follow webgpu standards
  25728. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  25729. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y )`;
  25730. }
  25731. return coord;
  25732. }
  25733. return super.generate( builder );
  25734. }
  25735. }
  25736. ViewportNode.COORDINATE = 'coordinate';
  25737. ViewportNode.RESOLUTION = 'resolution';
  25738. ViewportNode.VIEWPORT = 'viewport';
  25739. ViewportNode.UV = 'uv';
  25740. const viewportCoordinate = /*@__PURE__*/ nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  25741. const viewportResolution = /*@__PURE__*/ nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  25742. const viewport = /*@__PURE__*/ nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  25743. const viewportUV = /*@__PURE__*/ nodeImmutable( ViewportNode, ViewportNode.UV );
  25744. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  25745. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "viewportUV" instead.' );
  25746. return viewportUV;
  25747. }, 'vec2' ).once() )();
  25748. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  25749. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "viewportUV.flipY()" instead.' );
  25750. return viewportUV.flipY();
  25751. }, 'vec2' ).once() )();
  25752. const _size$a = /*@__PURE__*/ new Vector2();
  25753. class ViewportTextureNode extends TextureNode {
  25754. static get type() {
  25755. return 'ViewportTextureNode';
  25756. }
  25757. constructor( uvNode = viewportUV, levelNode = null, framebufferTexture = null ) {
  25758. if ( framebufferTexture === null ) {
  25759. framebufferTexture = new FramebufferTexture();
  25760. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  25761. }
  25762. super( framebufferTexture, uvNode, levelNode );
  25763. this.generateMipmaps = false;
  25764. this.isOutputTextureNode = true;
  25765. this.updateBeforeType = NodeUpdateType.FRAME;
  25766. }
  25767. updateBefore( frame ) {
  25768. const renderer = frame.renderer;
  25769. renderer.getDrawingBufferSize( _size$a );
  25770. //
  25771. const framebufferTexture = this.value;
  25772. if ( framebufferTexture.image.width !== _size$a.width || framebufferTexture.image.height !== _size$a.height ) {
  25773. framebufferTexture.image.width = _size$a.width;
  25774. framebufferTexture.image.height = _size$a.height;
  25775. framebufferTexture.needsUpdate = true;
  25776. }
  25777. //
  25778. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  25779. framebufferTexture.generateMipmaps = this.generateMipmaps;
  25780. renderer.copyFramebufferToTexture( framebufferTexture );
  25781. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  25782. }
  25783. clone() {
  25784. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  25785. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  25786. return viewportTextureNode;
  25787. }
  25788. }
  25789. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  25790. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  25791. let sharedDepthbuffer = null;
  25792. class ViewportDepthTextureNode extends ViewportTextureNode {
  25793. static get type() {
  25794. return 'ViewportDepthTextureNode';
  25795. }
  25796. constructor( uvNode = viewportUV, levelNode = null ) {
  25797. if ( sharedDepthbuffer === null ) {
  25798. sharedDepthbuffer = new DepthTexture();
  25799. }
  25800. super( uvNode, levelNode, sharedDepthbuffer );
  25801. }
  25802. }
  25803. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  25804. class ViewportDepthNode extends Node {
  25805. static get type() {
  25806. return 'ViewportDepthNode';
  25807. }
  25808. constructor( scope, valueNode = null ) {
  25809. super( 'float' );
  25810. this.scope = scope;
  25811. this.valueNode = valueNode;
  25812. this.isViewportDepthNode = true;
  25813. }
  25814. generate( builder ) {
  25815. const { scope } = this;
  25816. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  25817. return builder.getFragDepth();
  25818. }
  25819. return super.generate( builder );
  25820. }
  25821. setup( { camera } ) {
  25822. const { scope } = this;
  25823. const value = this.valueNode;
  25824. let node = null;
  25825. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  25826. if ( value !== null ) {
  25827. node = depthBase().assign( value );
  25828. }
  25829. } else if ( scope === ViewportDepthNode.DEPTH ) {
  25830. if ( camera.isPerspectiveCamera ) {
  25831. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  25832. } else {
  25833. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  25834. }
  25835. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  25836. if ( value !== null ) {
  25837. if ( camera.isPerspectiveCamera ) {
  25838. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  25839. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  25840. } else {
  25841. node = value;
  25842. }
  25843. } else {
  25844. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  25845. }
  25846. }
  25847. return node;
  25848. }
  25849. }
  25850. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  25851. ViewportDepthNode.DEPTH = 'depth';
  25852. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  25853. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  25854. // -near maps to 0; -far maps to 1
  25855. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  25856. // maps orthographic depth in [ 0, 1 ] to viewZ
  25857. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  25858. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  25859. // -near maps to 0; -far maps to 1
  25860. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  25861. // maps perspective depth in [ 0, 1 ] to viewZ
  25862. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  25863. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  25864. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  25865. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  25866. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  25867. depth.assign = ( value ) => depthBase( value );
  25868. class ClippingNode extends Node {
  25869. static get type() {
  25870. return 'ClippingNode';
  25871. }
  25872. constructor( scope = ClippingNode.DEFAULT ) {
  25873. super();
  25874. this.scope = scope;
  25875. }
  25876. setup( builder ) {
  25877. super.setup( builder );
  25878. const clippingContext = builder.clippingContext;
  25879. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  25880. const numClippingPlanes = globalClippingCount + localClippingCount;
  25881. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  25882. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  25883. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  25884. } else {
  25885. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  25886. }
  25887. }
  25888. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  25889. return Fn( () => {
  25890. const clippingPlanes = uniformArray( planes );
  25891. const distanceToPlane = property( 'float', 'distanceToPlane' );
  25892. const distanceGradient = property( 'float', 'distanceToGradient' );
  25893. const clipOpacity = property( 'float', 'clipOpacity' );
  25894. clipOpacity.assign( 1 );
  25895. let plane;
  25896. Loop( numUnionClippingPlanes, ( { i } ) => {
  25897. plane = clippingPlanes.element( i );
  25898. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  25899. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  25900. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  25901. clipOpacity.equal( 0.0 ).discard();
  25902. } );
  25903. if ( numUnionClippingPlanes < numClippingPlanes ) {
  25904. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  25905. unionClipOpacity.assign( 1 );
  25906. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  25907. plane = clippingPlanes.element( i );
  25908. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  25909. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  25910. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  25911. } );
  25912. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  25913. }
  25914. diffuseColor.a.mulAssign( clipOpacity );
  25915. diffuseColor.a.equal( 0.0 ).discard();
  25916. } )();
  25917. }
  25918. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  25919. return Fn( () => {
  25920. const clippingPlanes = uniformArray( planes );
  25921. let plane;
  25922. Loop( numUnionClippingPlanes, ( { i } ) => {
  25923. plane = clippingPlanes.element( i );
  25924. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  25925. } );
  25926. if ( numUnionClippingPlanes < numClippingPlanes ) {
  25927. const clipped = property( 'bool', 'clipped' );
  25928. clipped.assign( true );
  25929. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  25930. plane = clippingPlanes.element( i );
  25931. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  25932. } );
  25933. clipped.discard();
  25934. }
  25935. } )();
  25936. }
  25937. }
  25938. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  25939. ClippingNode.DEFAULT = 'default';
  25940. const clipping = () => nodeObject( new ClippingNode() );
  25941. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  25942. class NodeMaterial extends Material {
  25943. static get type() {
  25944. return 'NodeMaterial';
  25945. }
  25946. constructor() {
  25947. super();
  25948. this.isNodeMaterial = true;
  25949. this.type = this.constructor.type;
  25950. this.forceSinglePass = false;
  25951. this.fog = true;
  25952. this.lights = false;
  25953. this.lightsNode = null;
  25954. this.envNode = null;
  25955. this.aoNode = null;
  25956. this.colorNode = null;
  25957. this.normalNode = null;
  25958. this.opacityNode = null;
  25959. this.backdropNode = null;
  25960. this.backdropAlphaNode = null;
  25961. this.alphaTestNode = null;
  25962. this.positionNode = null;
  25963. this.depthNode = null;
  25964. this.shadowNode = null;
  25965. this.shadowPositionNode = null;
  25966. this.outputNode = null;
  25967. this.mrtNode = null;
  25968. this.fragmentNode = null;
  25969. this.vertexNode = null;
  25970. }
  25971. customProgramCacheKey() {
  25972. return this.type + getCacheKey$1( this );
  25973. }
  25974. build( builder ) {
  25975. this.setup( builder );
  25976. }
  25977. setup( builder ) {
  25978. builder.context.setupNormal = () => this.setupNormal( builder );
  25979. // < VERTEX STAGE >
  25980. builder.addStack();
  25981. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  25982. builder.addFlow( 'vertex', builder.removeStack() );
  25983. // < FRAGMENT STAGE >
  25984. builder.addStack();
  25985. let resultNode;
  25986. const clippingNode = this.setupClipping( builder );
  25987. if ( this.depthWrite === true ) this.setupDepth( builder );
  25988. if ( this.fragmentNode === null ) {
  25989. this.setupDiffuseColor( builder );
  25990. this.setupVariants( builder );
  25991. const outgoingLightNode = this.setupLighting( builder );
  25992. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  25993. // force unsigned floats - useful for RenderTargets
  25994. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  25995. resultNode = this.setupOutput( builder, basicOutput );
  25996. // OUTPUT NODE
  25997. output.assign( resultNode );
  25998. //
  25999. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26000. // MRT
  26001. const renderTarget = builder.renderer.getRenderTarget();
  26002. if ( renderTarget !== null ) {
  26003. const mrt = builder.renderer.getMRT();
  26004. const materialMRT = this.mrtNode;
  26005. if ( mrt !== null ) {
  26006. resultNode = mrt;
  26007. if ( materialMRT !== null ) {
  26008. resultNode = mrt.merge( materialMRT );
  26009. }
  26010. } else if ( materialMRT !== null ) {
  26011. resultNode = materialMRT;
  26012. }
  26013. }
  26014. } else {
  26015. let fragmentNode = this.fragmentNode;
  26016. if ( fragmentNode.isOutputStructNode !== true ) {
  26017. fragmentNode = vec4( fragmentNode );
  26018. }
  26019. resultNode = this.setupOutput( builder, fragmentNode );
  26020. }
  26021. builder.stack.outputNode = resultNode;
  26022. builder.addFlow( 'fragment', builder.removeStack() );
  26023. }
  26024. setupClipping( builder ) {
  26025. if ( builder.clippingContext === null ) return null;
  26026. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26027. let result = null;
  26028. if ( globalClippingCount || localClippingCount ) {
  26029. if ( this.alphaToCoverage ) {
  26030. // to be added to flow when the color/alpha value has been determined
  26031. result = clippingAlpha();
  26032. } else {
  26033. builder.stack.add( clipping() );
  26034. }
  26035. }
  26036. return result;
  26037. }
  26038. setupDepth( builder ) {
  26039. const { renderer } = builder;
  26040. // Depth
  26041. let depthNode = this.depthNode;
  26042. if ( depthNode === null ) {
  26043. const mrt = renderer.getMRT();
  26044. if ( mrt && mrt.has( 'depth' ) ) {
  26045. depthNode = mrt.get( 'depth' );
  26046. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26047. const fragDepth = modelViewProjection().w.add( 1 );
  26048. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26049. }
  26050. }
  26051. if ( depthNode !== null ) {
  26052. depth.assign( depthNode ).append();
  26053. }
  26054. }
  26055. setupPosition( builder ) {
  26056. const { object } = builder;
  26057. const geometry = object.geometry;
  26058. builder.addStack();
  26059. // Vertex
  26060. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26061. morphReference( object ).append();
  26062. }
  26063. if ( object.isSkinnedMesh === true ) {
  26064. skinningReference( object ).append();
  26065. }
  26066. if ( this.displacementMap ) {
  26067. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26068. const displacementScale = materialReference( 'displacementScale', 'float' );
  26069. const displacementBias = materialReference( 'displacementBias', 'float' );
  26070. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26071. }
  26072. if ( object.isBatchedMesh ) {
  26073. batch( object ).append();
  26074. }
  26075. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26076. instance( object ).append();
  26077. }
  26078. if ( this.positionNode !== null ) {
  26079. positionLocal.assign( this.positionNode );
  26080. }
  26081. const mvp = modelViewProjection();
  26082. builder.context.vertex = builder.removeStack();
  26083. builder.context.mvp = mvp;
  26084. return mvp;
  26085. }
  26086. setupDiffuseColor( { object, geometry } ) {
  26087. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26088. // VERTEX COLORS
  26089. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26090. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26091. }
  26092. // Instanced colors
  26093. if ( object.instanceColor ) {
  26094. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26095. colorNode = instanceColor.mul( colorNode );
  26096. }
  26097. if ( object.isBatchedMesh && object._colorsTexture ) {
  26098. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26099. colorNode = batchColor.mul( colorNode );
  26100. }
  26101. // COLOR
  26102. diffuseColor.assign( colorNode );
  26103. // OPACITY
  26104. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26105. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26106. // ALPHA TEST
  26107. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26108. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26109. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26110. }
  26111. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26112. diffuseColor.a.assign( 1.0 );
  26113. }
  26114. }
  26115. setupVariants( /*builder*/ ) {
  26116. // Interface function.
  26117. }
  26118. setupOutgoingLight() {
  26119. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26120. }
  26121. setupNormal() {
  26122. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26123. }
  26124. setupEnvironment( /*builder*/ ) {
  26125. let node = null;
  26126. if ( this.envNode ) {
  26127. node = this.envNode;
  26128. } else if ( this.envMap ) {
  26129. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26130. }
  26131. return node;
  26132. }
  26133. setupLightMap( builder ) {
  26134. let node = null;
  26135. if ( builder.material.lightMap ) {
  26136. node = new IrradianceNode( materialLightMap );
  26137. }
  26138. return node;
  26139. }
  26140. setupLights( builder ) {
  26141. const materialLightsNode = [];
  26142. //
  26143. const envNode = this.setupEnvironment( builder );
  26144. if ( envNode && envNode.isLightingNode ) {
  26145. materialLightsNode.push( envNode );
  26146. }
  26147. const lightMapNode = this.setupLightMap( builder );
  26148. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26149. materialLightsNode.push( lightMapNode );
  26150. }
  26151. if ( this.aoNode !== null || builder.material.aoMap ) {
  26152. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26153. materialLightsNode.push( new AONode( aoNode ) );
  26154. }
  26155. let lightsN = this.lightsNode || builder.lightsNode;
  26156. if ( materialLightsNode.length > 0 ) {
  26157. lightsN = lights( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26158. }
  26159. return lightsN;
  26160. }
  26161. setupLightingModel( /*builder*/ ) {
  26162. // Interface function.
  26163. }
  26164. setupLighting( builder ) {
  26165. const { material } = builder;
  26166. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26167. // OUTGOING LIGHT
  26168. const lights = this.lights === true || this.lightsNode !== null;
  26169. const lightsNode = lights ? this.setupLights( builder ) : null;
  26170. let outgoingLightNode = this.setupOutgoingLight( builder );
  26171. if ( lightsNode && lightsNode.getScope().getLights().length > 0 ) {
  26172. const lightingModel = this.setupLightingModel( builder );
  26173. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26174. } else if ( backdropNode !== null ) {
  26175. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26176. }
  26177. // EMISSIVE
  26178. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26179. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26180. outgoingLightNode = outgoingLightNode.add( emissive );
  26181. }
  26182. return outgoingLightNode;
  26183. }
  26184. setupOutput( builder, outputNode ) {
  26185. // FOG
  26186. if ( this.fog === true ) {
  26187. const fogNode = builder.fogNode;
  26188. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26189. }
  26190. return outputNode;
  26191. }
  26192. setDefaultValues( material ) {
  26193. // This approach is to reuse the native refreshUniforms*
  26194. // and turn available the use of features like transmission and environment in core
  26195. for ( const property in material ) {
  26196. const value = material[ property ];
  26197. if ( this[ property ] === undefined ) {
  26198. this[ property ] = value;
  26199. if ( value && value.clone ) this[ property ] = value.clone();
  26200. }
  26201. }
  26202. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26203. for ( const key in descriptors ) {
  26204. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26205. descriptors[ key ].get !== undefined ) {
  26206. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26207. }
  26208. }
  26209. }
  26210. toJSON( meta ) {
  26211. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26212. if ( isRoot ) {
  26213. meta = {
  26214. textures: {},
  26215. images: {},
  26216. nodes: {}
  26217. };
  26218. }
  26219. const data = Material.prototype.toJSON.call( this, meta );
  26220. const nodeChildren = getNodeChildren( this );
  26221. data.inputNodes = {};
  26222. for ( const { property, childNode } of nodeChildren ) {
  26223. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26224. }
  26225. // TODO: Copied from Object3D.toJSON
  26226. function extractFromCache( cache ) {
  26227. const values = [];
  26228. for ( const key in cache ) {
  26229. const data = cache[ key ];
  26230. delete data.metadata;
  26231. values.push( data );
  26232. }
  26233. return values;
  26234. }
  26235. if ( isRoot ) {
  26236. const textures = extractFromCache( meta.textures );
  26237. const images = extractFromCache( meta.images );
  26238. const nodes = extractFromCache( meta.nodes );
  26239. if ( textures.length > 0 ) data.textures = textures;
  26240. if ( images.length > 0 ) data.images = images;
  26241. if ( nodes.length > 0 ) data.nodes = nodes;
  26242. }
  26243. return data;
  26244. }
  26245. copy( source ) {
  26246. this.lightsNode = source.lightsNode;
  26247. this.envNode = source.envNode;
  26248. this.colorNode = source.colorNode;
  26249. this.normalNode = source.normalNode;
  26250. this.opacityNode = source.opacityNode;
  26251. this.backdropNode = source.backdropNode;
  26252. this.backdropAlphaNode = source.backdropAlphaNode;
  26253. this.alphaTestNode = source.alphaTestNode;
  26254. this.positionNode = source.positionNode;
  26255. this.depthNode = source.depthNode;
  26256. this.shadowNode = source.shadowNode;
  26257. this.shadowPositionNode = source.shadowPositionNode;
  26258. this.outputNode = source.outputNode;
  26259. this.mrtNode = source.mrtNode;
  26260. this.fragmentNode = source.fragmentNode;
  26261. this.vertexNode = source.vertexNode;
  26262. return super.copy( source );
  26263. }
  26264. }
  26265. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26266. class InstancedPointsNodeMaterial extends NodeMaterial {
  26267. static get type() {
  26268. return 'InstancedPointsNodeMaterial';
  26269. }
  26270. constructor( params = {} ) {
  26271. super();
  26272. this.lights = false;
  26273. this.useAlphaToCoverage = true;
  26274. this.useColor = params.vertexColors;
  26275. this.pointWidth = 1;
  26276. this.pointColorNode = null;
  26277. this.pointWidthNode = null;
  26278. this.setDefaultValues( _defaultValues$e );
  26279. this.setupShaders();
  26280. this.setValues( params );
  26281. }
  26282. setup( builder ) {
  26283. this.setupShaders();
  26284. super.setup( builder );
  26285. }
  26286. setupShaders() {
  26287. const useAlphaToCoverage = this.alphaToCoverage;
  26288. const useColor = this.useColor;
  26289. this.vertexNode = Fn( () => {
  26290. //vUv = uv;
  26291. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  26292. const instancePosition = attribute( 'instancePosition' ).xyz;
  26293. // camera space
  26294. const mvPos = property( 'vec4', 'mvPos' );
  26295. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26296. const aspect = viewport.z.div( viewport.w );
  26297. // clip space
  26298. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26299. // offset in ndc space
  26300. const offset = property( 'vec2', 'offset' );
  26301. offset.assign( positionGeometry.xy );
  26302. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26303. offset.assign( offset.div( viewport.z ) );
  26304. offset.y.assign( offset.y.mul( aspect ) );
  26305. // back to clip space
  26306. offset.assign( offset.mul( clipPos.w ) );
  26307. //clipPos.xy += offset;
  26308. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  26309. return clipPos;
  26310. //vec4 mvPosition = mvPos; // this was used for somethihng...
  26311. } )();
  26312. this.fragmentNode = Fn( () => {
  26313. const vUv = varying( vec2(), 'vUv' );
  26314. // force assignment into correct place in flow
  26315. const alpha = property( 'float', 'alpha' );
  26316. alpha.assign( 1 );
  26317. const a = vUv.x;
  26318. const b = vUv.y;
  26319. const len2 = a.mul( a ).add( b.mul( b ) );
  26320. if ( useAlphaToCoverage ) {
  26321. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  26322. const dlen = property( 'float', 'dlen' );
  26323. dlen.assign( len2.fwidth() );
  26324. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26325. } else {
  26326. len2.greaterThan( 1.0 ).discard();
  26327. }
  26328. let pointColorNode;
  26329. if ( this.pointColorNode ) {
  26330. pointColorNode = this.pointColorNode;
  26331. } else {
  26332. if ( useColor ) {
  26333. const instanceColor = attribute( 'instanceColor' );
  26334. pointColorNode = instanceColor.mul( materialColor );
  26335. } else {
  26336. pointColorNode = materialColor;
  26337. }
  26338. }
  26339. alpha.mulAssign( materialOpacity );
  26340. return vec4( pointColorNode, alpha );
  26341. } )();
  26342. }
  26343. get alphaToCoverage() {
  26344. return this.useAlphaToCoverage;
  26345. }
  26346. set alphaToCoverage( value ) {
  26347. if ( this.useAlphaToCoverage !== value ) {
  26348. this.useAlphaToCoverage = value;
  26349. this.needsUpdate = true;
  26350. }
  26351. }
  26352. }
  26353. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  26354. class LineBasicNodeMaterial extends NodeMaterial {
  26355. static get type() {
  26356. return 'LineBasicNodeMaterial';
  26357. }
  26358. constructor( parameters ) {
  26359. super();
  26360. this.isLineBasicNodeMaterial = true;
  26361. this.lights = false;
  26362. this.setDefaultValues( _defaultValues$d );
  26363. this.setValues( parameters );
  26364. }
  26365. }
  26366. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  26367. class LineDashedNodeMaterial extends NodeMaterial {
  26368. static get type() {
  26369. return 'LineDashedNodeMaterial';
  26370. }
  26371. constructor( parameters ) {
  26372. super();
  26373. this.isLineDashedNodeMaterial = true;
  26374. this.lights = false;
  26375. this.setDefaultValues( _defaultValues$c );
  26376. this.offsetNode = null;
  26377. this.dashScaleNode = null;
  26378. this.dashSizeNode = null;
  26379. this.gapSizeNode = null;
  26380. this.setValues( parameters );
  26381. }
  26382. setupVariants() {
  26383. const offsetNode = this.offsetNode;
  26384. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26385. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26386. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26387. dashSize.assign( dashSizeNode );
  26388. gapSize.assign( gapSizeNode );
  26389. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  26390. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26391. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  26392. }
  26393. }
  26394. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  26395. class Line2NodeMaterial extends NodeMaterial {
  26396. static get type() {
  26397. return 'Line2NodeMaterial';
  26398. }
  26399. constructor( params = {} ) {
  26400. super();
  26401. this.lights = false;
  26402. this.setDefaultValues( _defaultValues$b );
  26403. this.useAlphaToCoverage = true;
  26404. this.useColor = params.vertexColors;
  26405. this.useDash = params.dashed;
  26406. this.useWorldUnits = false;
  26407. this.dashOffset = 0;
  26408. this.lineWidth = 1;
  26409. this.lineColorNode = null;
  26410. this.offsetNode = null;
  26411. this.dashScaleNode = null;
  26412. this.dashSizeNode = null;
  26413. this.gapSizeNode = null;
  26414. this.setValues( params );
  26415. }
  26416. setup( builder ) {
  26417. this.setupShaders();
  26418. super.setup( builder );
  26419. }
  26420. setupShaders() {
  26421. const useAlphaToCoverage = this.alphaToCoverage;
  26422. const useColor = this.useColor;
  26423. const useDash = this.dashed;
  26424. const useWorldUnits = this.worldUnits;
  26425. const trimSegment = Fn( ( { start, end } ) => {
  26426. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  26427. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  26428. const nearEstimate = b.mul( - 0.5 ).div( a );
  26429. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  26430. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  26431. } );
  26432. this.vertexNode = Fn( () => {
  26433. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  26434. const instanceStart = attribute( 'instanceStart' );
  26435. const instanceEnd = attribute( 'instanceEnd' );
  26436. // camera space
  26437. const start = property( 'vec4', 'start' );
  26438. const end = property( 'vec4', 'end' );
  26439. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  26440. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  26441. if ( useWorldUnits ) {
  26442. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  26443. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  26444. }
  26445. const aspect = viewport.z.div( viewport.w );
  26446. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  26447. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  26448. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  26449. // perhaps there is a more elegant solution -- WestLangley
  26450. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  26451. If( perspective, () => {
  26452. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  26453. end.assign( trimSegment( { start: start, end: end } ) );
  26454. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  26455. start.assign( trimSegment( { start: end, end: start } ) );
  26456. } );
  26457. } );
  26458. // clip space
  26459. const clipStart = cameraProjectionMatrix.mul( start );
  26460. const clipEnd = cameraProjectionMatrix.mul( end );
  26461. // ndc space
  26462. const ndcStart = clipStart.xyz.div( clipStart.w );
  26463. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  26464. // direction
  26465. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  26466. // account for clip-space aspect ratio
  26467. dir.x.assign( dir.x.mul( aspect ) );
  26468. dir.assign( dir.normalize() );
  26469. const clip = vec4().toVar();
  26470. if ( useWorldUnits ) {
  26471. // get the offset direction as perpendicular to the view vector
  26472. const worldDir = end.xyz.sub( start.xyz ).normalize();
  26473. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  26474. const worldUp = worldDir.cross( tmpFwd ).normalize();
  26475. const worldFwd = worldDir.cross( worldUp );
  26476. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  26477. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  26478. // height offset
  26479. const hw = materialLineWidth.mul( 0.5 );
  26480. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  26481. // don't extend the line if we're rendering dashes because we
  26482. // won't be rendering the endcaps
  26483. if ( ! useDash ) {
  26484. // cap extension
  26485. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  26486. // add width to the box
  26487. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  26488. // endcaps
  26489. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  26490. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  26491. } );
  26492. }
  26493. // project the worldpos
  26494. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  26495. // shift the depth of the projected points so the line
  26496. // segments overlap neatly
  26497. const clipPose = vec3().toVar();
  26498. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  26499. clip.z.assign( clipPose.z.mul( clip.w ) );
  26500. } else {
  26501. const offset = property( 'vec2', 'offset' );
  26502. offset.assign( vec2( dir.y, dir.x.negate() ) );
  26503. // undo aspect ratio adjustment
  26504. dir.x.assign( dir.x.div( aspect ) );
  26505. offset.x.assign( offset.x.div( aspect ) );
  26506. // sign flip
  26507. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  26508. // endcaps
  26509. If( positionGeometry.y.lessThan( 0.0 ), () => {
  26510. offset.assign( offset.sub( dir ) );
  26511. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  26512. offset.assign( offset.add( dir ) );
  26513. } );
  26514. // adjust for linewidth
  26515. offset.assign( offset.mul( materialLineWidth ) );
  26516. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  26517. offset.assign( offset.div( viewport.w ) );
  26518. // select end
  26519. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  26520. // back to clip space
  26521. offset.assign( offset.mul( clip.w ) );
  26522. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  26523. }
  26524. return clip;
  26525. } )();
  26526. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  26527. const p13 = p1.sub( p3 );
  26528. const p43 = p4.sub( p3 );
  26529. const p21 = p2.sub( p1 );
  26530. const d1343 = p13.dot( p43 );
  26531. const d4321 = p43.dot( p21 );
  26532. const d1321 = p13.dot( p21 );
  26533. const d4343 = p43.dot( p43 );
  26534. const d2121 = p21.dot( p21 );
  26535. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  26536. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  26537. const mua = numer.div( denom ).clamp();
  26538. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  26539. return vec2( mua, mub );
  26540. } );
  26541. this.fragmentNode = Fn( () => {
  26542. const vUv = varyingProperty( 'vec2', 'vUv' );
  26543. if ( useDash ) {
  26544. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  26545. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26546. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26547. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26548. dashSize.assign( dashSizeNode );
  26549. gapSize.assign( gapSizeNode );
  26550. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  26551. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  26552. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  26553. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  26554. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26555. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  26556. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  26557. }
  26558. // force assignment into correct place in flow
  26559. const alpha = property( 'float', 'alpha' );
  26560. alpha.assign( 1 );
  26561. if ( useWorldUnits ) {
  26562. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  26563. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  26564. // Find the closest points on the view ray and the line segment
  26565. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  26566. const lineDir = worldEnd.sub( worldStart );
  26567. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  26568. const p1 = worldStart.add( lineDir.mul( params.x ) );
  26569. const p2 = rayEnd.mul( params.y );
  26570. const delta = p1.sub( p2 );
  26571. const len = delta.length();
  26572. const norm = len.div( materialLineWidth );
  26573. if ( ! useDash ) {
  26574. if ( useAlphaToCoverage ) {
  26575. const dnorm = norm.fwidth();
  26576. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  26577. } else {
  26578. norm.greaterThan( 0.5 ).discard();
  26579. }
  26580. }
  26581. } else {
  26582. // round endcaps
  26583. if ( useAlphaToCoverage ) {
  26584. const a = vUv.x;
  26585. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  26586. const len2 = a.mul( a ).add( b.mul( b ) );
  26587. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  26588. const dlen = property( 'float', 'dlen' );
  26589. dlen.assign( len2.fwidth() );
  26590. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  26591. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26592. } );
  26593. } else {
  26594. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  26595. const a = vUv.x;
  26596. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  26597. const len2 = a.mul( a ).add( b.mul( b ) );
  26598. len2.greaterThan( 1.0 ).discard();
  26599. } );
  26600. }
  26601. }
  26602. let lineColorNode;
  26603. if ( this.lineColorNode ) {
  26604. lineColorNode = this.lineColorNode;
  26605. } else {
  26606. if ( useColor ) {
  26607. const instanceColorStart = attribute( 'instanceColorStart' );
  26608. const instanceColorEnd = attribute( 'instanceColorEnd' );
  26609. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  26610. lineColorNode = instanceColor.mul( materialColor );
  26611. } else {
  26612. lineColorNode = materialColor;
  26613. }
  26614. }
  26615. return vec4( lineColorNode, alpha );
  26616. } )();
  26617. }
  26618. get worldUnits() {
  26619. return this.useWorldUnits;
  26620. }
  26621. set worldUnits( value ) {
  26622. if ( this.useWorldUnits !== value ) {
  26623. this.useWorldUnits = value;
  26624. this.needsUpdate = true;
  26625. }
  26626. }
  26627. get dashed() {
  26628. return this.useDash;
  26629. }
  26630. set dashed( value ) {
  26631. if ( this.useDash !== value ) {
  26632. this.useDash = value;
  26633. this.needsUpdate = true;
  26634. }
  26635. }
  26636. get alphaToCoverage() {
  26637. return this.useAlphaToCoverage;
  26638. }
  26639. set alphaToCoverage( value ) {
  26640. if ( this.useAlphaToCoverage !== value ) {
  26641. this.useAlphaToCoverage = value;
  26642. this.needsUpdate = true;
  26643. }
  26644. }
  26645. }
  26646. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  26647. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  26648. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  26649. class MeshNormalNodeMaterial extends NodeMaterial {
  26650. static get type() {
  26651. return 'MeshNormalNodeMaterial';
  26652. }
  26653. constructor( parameters ) {
  26654. super();
  26655. this.lights = false;
  26656. this.isMeshNormalNodeMaterial = true;
  26657. this.setDefaultValues( _defaultValues$a );
  26658. this.setValues( parameters );
  26659. }
  26660. setupDiffuseColor() {
  26661. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26662. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  26663. }
  26664. }
  26665. class EquirectUVNode extends TempNode {
  26666. static get type() {
  26667. return 'EquirectUVNode';
  26668. }
  26669. constructor( dirNode = positionWorldDirection ) {
  26670. super( 'vec2' );
  26671. this.dirNode = dirNode;
  26672. }
  26673. setup() {
  26674. const dir = this.dirNode;
  26675. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  26676. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  26677. return vec2( u, v );
  26678. }
  26679. }
  26680. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  26681. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  26682. class CubeRenderTarget extends WebGLCubeRenderTarget {
  26683. constructor( size = 1, options = {} ) {
  26684. super( size, options );
  26685. this.isCubeRenderTarget = true;
  26686. }
  26687. fromEquirectangularTexture( renderer, texture$1 ) {
  26688. const currentMinFilter = texture$1.minFilter;
  26689. const currentGenerateMipmaps = texture$1.generateMipmaps;
  26690. texture$1.generateMipmaps = true;
  26691. this.texture.type = texture$1.type;
  26692. this.texture.colorSpace = texture$1.colorSpace;
  26693. this.texture.generateMipmaps = texture$1.generateMipmaps;
  26694. this.texture.minFilter = texture$1.minFilter;
  26695. this.texture.magFilter = texture$1.magFilter;
  26696. const geometry = new BoxGeometry( 5, 5, 5 );
  26697. const uvNode = equirectUV( positionWorldDirection );
  26698. const material = new NodeMaterial();
  26699. material.colorNode = texture( texture$1, uvNode, 0 );
  26700. material.side = BackSide;
  26701. material.blending = NoBlending;
  26702. const mesh = new Mesh( geometry, material );
  26703. const scene = new Scene();
  26704. scene.add( mesh );
  26705. // Avoid blurred poles
  26706. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  26707. const camera = new CubeCamera( 1, 10, this );
  26708. const currentMRT = renderer.getMRT();
  26709. renderer.setMRT( null );
  26710. camera.update( renderer, scene );
  26711. renderer.setMRT( currentMRT );
  26712. texture$1.minFilter = currentMinFilter;
  26713. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  26714. mesh.geometry.dispose();
  26715. mesh.material.dispose();
  26716. return this;
  26717. }
  26718. }
  26719. const _cache$1 = new WeakMap();
  26720. class CubeMapNode extends TempNode {
  26721. static get type() {
  26722. return 'CubeMapNode';
  26723. }
  26724. constructor( envNode ) {
  26725. super( 'vec3' );
  26726. this.envNode = envNode;
  26727. this._cubeTexture = null;
  26728. this._cubeTextureNode = cubeTexture();
  26729. const defaultTexture = new CubeTexture();
  26730. defaultTexture.isRenderTargetTexture = true;
  26731. this._defaultTexture = defaultTexture;
  26732. this.updateBeforeType = NodeUpdateType.RENDER;
  26733. }
  26734. updateBefore( frame ) {
  26735. const { renderer, material } = frame;
  26736. const envNode = this.envNode;
  26737. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  26738. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  26739. if ( texture && texture.isTexture ) {
  26740. const mapping = texture.mapping;
  26741. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  26742. // check for converted cubemap map
  26743. if ( _cache$1.has( texture ) ) {
  26744. const cubeMap = _cache$1.get( texture );
  26745. mapTextureMapping( cubeMap, texture.mapping );
  26746. this._cubeTexture = cubeMap;
  26747. } else {
  26748. // create cube map from equirectangular map
  26749. const image = texture.image;
  26750. if ( isEquirectangularMapReady$1( image ) ) {
  26751. const renderTarget = new CubeRenderTarget( image.height );
  26752. renderTarget.fromEquirectangularTexture( renderer, texture );
  26753. mapTextureMapping( renderTarget.texture, texture.mapping );
  26754. this._cubeTexture = renderTarget.texture;
  26755. _cache$1.set( texture, renderTarget.texture );
  26756. texture.addEventListener( 'dispose', onTextureDispose );
  26757. } else {
  26758. // default cube texture as fallback when equirectangular texture is not yet loaded
  26759. this._cubeTexture = this._defaultTexture;
  26760. }
  26761. }
  26762. //
  26763. this._cubeTextureNode.value = this._cubeTexture;
  26764. } else {
  26765. // envNode already refers to a cube map
  26766. this._cubeTextureNode = this.envNode;
  26767. }
  26768. }
  26769. }
  26770. }
  26771. setup( builder ) {
  26772. this.updateBefore( builder );
  26773. return this._cubeTextureNode;
  26774. }
  26775. }
  26776. function isEquirectangularMapReady$1( image ) {
  26777. if ( image === null || image === undefined ) return false;
  26778. return image.height > 0;
  26779. }
  26780. function onTextureDispose( event ) {
  26781. const texture = event.target;
  26782. texture.removeEventListener( 'dispose', onTextureDispose );
  26783. const renderTarget = _cache$1.get( texture );
  26784. if ( renderTarget !== undefined ) {
  26785. _cache$1.delete( texture );
  26786. renderTarget.dispose();
  26787. }
  26788. }
  26789. function mapTextureMapping( texture, mapping ) {
  26790. if ( mapping === EquirectangularReflectionMapping ) {
  26791. texture.mapping = CubeReflectionMapping;
  26792. } else if ( mapping === EquirectangularRefractionMapping ) {
  26793. texture.mapping = CubeRefractionMapping;
  26794. }
  26795. }
  26796. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  26797. class BasicEnvironmentNode extends LightingNode {
  26798. static get type() {
  26799. return 'BasicEnvironmentNode';
  26800. }
  26801. constructor( envNode = null ) {
  26802. super();
  26803. this.envNode = envNode;
  26804. }
  26805. setup( builder ) {
  26806. // environment property is used in the finish() method of BasicLightingModel
  26807. builder.context.environment = cubeMapNode( this.envNode );
  26808. }
  26809. }
  26810. class BasicLightMapNode extends LightingNode {
  26811. static get type() {
  26812. return 'BasicLightMapNode';
  26813. }
  26814. constructor( lightMapNode = null ) {
  26815. super();
  26816. this.lightMapNode = lightMapNode;
  26817. }
  26818. setup( builder ) {
  26819. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  26820. const RECIPROCAL_PI = float( 1 / Math.PI );
  26821. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  26822. }
  26823. }
  26824. class LightingModel {
  26825. start( /*input, stack, builder*/ ) { }
  26826. finish( /*input, stack, builder*/ ) { }
  26827. direct( /*input, stack, builder*/ ) { }
  26828. directRectArea( /*input, stack, builder*/ ) {}
  26829. indirect( /*input, stack, builder*/ ) { }
  26830. ambientOcclusion( /*input, stack, builder*/ ) { }
  26831. }
  26832. class BasicLightingModel extends LightingModel {
  26833. constructor() {
  26834. super();
  26835. }
  26836. indirect( context, stack, builder ) {
  26837. const ambientOcclusion = context.ambientOcclusion;
  26838. const reflectedLight = context.reflectedLight;
  26839. const irradianceLightMap = builder.context.irradianceLightMap;
  26840. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  26841. // accumulation (baked indirect lighting only)
  26842. if ( irradianceLightMap ) {
  26843. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  26844. } else {
  26845. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  26846. }
  26847. // modulation
  26848. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  26849. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  26850. }
  26851. finish( context, stack, builder ) {
  26852. const material = builder.material;
  26853. const outgoingLight = context.outgoingLight;
  26854. const envNode = builder.context.environment;
  26855. if ( envNode ) {
  26856. switch ( material.combine ) {
  26857. case MultiplyOperation:
  26858. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  26859. break;
  26860. case MixOperation:
  26861. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  26862. break;
  26863. case AddOperation:
  26864. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  26865. break;
  26866. default:
  26867. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  26868. break;
  26869. }
  26870. }
  26871. }
  26872. }
  26873. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  26874. class MeshBasicNodeMaterial extends NodeMaterial {
  26875. static get type() {
  26876. return 'MeshBasicNodeMaterial';
  26877. }
  26878. constructor( parameters ) {
  26879. super();
  26880. this.isMeshBasicNodeMaterial = true;
  26881. this.lights = true;
  26882. this.setDefaultValues( _defaultValues$9 );
  26883. this.setValues( parameters );
  26884. }
  26885. setupNormal() {
  26886. return normalView; // see #28839
  26887. }
  26888. setupEnvironment( builder ) {
  26889. const envNode = super.setupEnvironment( builder );
  26890. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  26891. }
  26892. setupLightMap( builder ) {
  26893. let node = null;
  26894. if ( builder.material.lightMap ) {
  26895. node = new BasicLightMapNode( materialLightMap );
  26896. }
  26897. return node;
  26898. }
  26899. setupOutgoingLight() {
  26900. return diffuseColor.rgb;
  26901. }
  26902. setupLightingModel() {
  26903. return new BasicLightingModel();
  26904. }
  26905. }
  26906. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  26907. // Original approximation by Christophe Schlick '94
  26908. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  26909. // Optimized variant (presented by Epic at SIGGRAPH '13)
  26910. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  26911. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  26912. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  26913. } ); // validated
  26914. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  26915. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  26916. } ); // validated
  26917. const G_BlinnPhong_Implicit = () => float( 0.25 );
  26918. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  26919. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  26920. } );
  26921. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  26922. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  26923. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  26924. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  26925. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  26926. const G = G_BlinnPhong_Implicit();
  26927. const D = D_BlinnPhong( { dotNH } );
  26928. return F.mul( G ).mul( D );
  26929. } );
  26930. class PhongLightingModel extends BasicLightingModel {
  26931. constructor( specular = true ) {
  26932. super();
  26933. this.specular = specular;
  26934. }
  26935. direct( { lightDirection, lightColor, reflectedLight } ) {
  26936. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  26937. const irradiance = dotNL.mul( lightColor );
  26938. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  26939. if ( this.specular === true ) {
  26940. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  26941. }
  26942. }
  26943. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  26944. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  26945. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  26946. }
  26947. }
  26948. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  26949. class MeshLambertNodeMaterial extends NodeMaterial {
  26950. static get type() {
  26951. return 'MeshLambertNodeMaterial';
  26952. }
  26953. constructor( parameters ) {
  26954. super();
  26955. this.isMeshLambertNodeMaterial = true;
  26956. this.lights = true;
  26957. this.setDefaultValues( _defaultValues$8 );
  26958. this.setValues( parameters );
  26959. }
  26960. setupEnvironment( builder ) {
  26961. const envNode = super.setupEnvironment( builder );
  26962. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  26963. }
  26964. setupLightingModel( /*builder*/ ) {
  26965. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  26966. }
  26967. }
  26968. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  26969. class MeshPhongNodeMaterial extends NodeMaterial {
  26970. static get type() {
  26971. return 'MeshPhongNodeMaterial';
  26972. }
  26973. constructor( parameters ) {
  26974. super();
  26975. this.isMeshPhongNodeMaterial = true;
  26976. this.lights = true;
  26977. this.shininessNode = null;
  26978. this.specularNode = null;
  26979. this.setDefaultValues( _defaultValues$7 );
  26980. this.setValues( parameters );
  26981. }
  26982. setupEnvironment( builder ) {
  26983. const envNode = super.setupEnvironment( builder );
  26984. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  26985. }
  26986. setupLightingModel( /*builder*/ ) {
  26987. return new PhongLightingModel();
  26988. }
  26989. setupVariants() {
  26990. // SHININESS
  26991. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  26992. shininess.assign( shininessNode );
  26993. // SPECULAR COLOR
  26994. const specularNode = this.specularNode || materialSpecular;
  26995. specularColor.assign( specularNode );
  26996. }
  26997. copy( source ) {
  26998. this.shininessNode = source.shininessNode;
  26999. this.specularNode = source.specularNode;
  27000. return super.copy( source );
  27001. }
  27002. }
  27003. const getGeometryRoughness = /*@__PURE__*/ Fn( () => {
  27004. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27005. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27006. return geometryRoughness;
  27007. } );
  27008. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27009. const { roughness } = inputs;
  27010. const geometryRoughness = getGeometryRoughness();
  27011. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27012. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27013. roughnessFactor = roughnessFactor.min( 1.0 );
  27014. return roughnessFactor;
  27015. } );
  27016. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27017. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27018. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27019. const a2 = alpha.pow2();
  27020. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27021. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27022. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27023. } ).setLayout( {
  27024. name: 'V_GGX_SmithCorrelated',
  27025. type: 'float',
  27026. inputs: [
  27027. { name: 'alpha', type: 'float' },
  27028. { name: 'dotNL', type: 'float' },
  27029. { name: 'dotNV', type: 'float' }
  27030. ]
  27031. } ); // validated
  27032. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27033. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27034. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27035. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27036. const v = div( 0.5, gv.add( gl ) );
  27037. return v.saturate();
  27038. } ).setLayout( {
  27039. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27040. type: 'float',
  27041. inputs: [
  27042. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27043. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27044. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27045. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27046. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27047. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27048. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27049. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27050. ]
  27051. } );
  27052. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27053. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27054. // alpha is "roughness squared" in Disney’s reparameterization
  27055. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27056. const a2 = alpha.pow2();
  27057. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27058. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27059. } ).setLayout( {
  27060. name: 'D_GGX',
  27061. type: 'float',
  27062. inputs: [
  27063. { name: 'alpha', type: 'float' },
  27064. { name: 'dotNH', type: 'float' }
  27065. ]
  27066. } ); // validated
  27067. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27068. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27069. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27070. const a2 = alphaT.mul( alphaB );
  27071. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27072. const v2 = v.dot( v );
  27073. const w2 = a2.div( v2 );
  27074. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27075. } ).setLayout( {
  27076. name: 'D_GGX_Anisotropic',
  27077. type: 'float',
  27078. inputs: [
  27079. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27080. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27081. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27082. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27083. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27084. ]
  27085. } );
  27086. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27087. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27088. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27089. const normalView = inputs.normalView || transformedNormalView;
  27090. const alpha = roughness.pow2(); // UE4's roughness
  27091. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27092. const dotNL = normalView.dot( lightDirection ).clamp();
  27093. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27094. const dotNH = normalView.dot( halfDir ).clamp();
  27095. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27096. let F = F_Schlick( { f0, f90, dotVH } );
  27097. let V, D;
  27098. if ( defined( USE_IRIDESCENCE ) ) {
  27099. F = iridescence.mix( F, f );
  27100. }
  27101. if ( defined( USE_ANISOTROPY ) ) {
  27102. const dotTL = anisotropyT.dot( lightDirection );
  27103. const dotTV = anisotropyT.dot( positionViewDirection );
  27104. const dotTH = anisotropyT.dot( halfDir );
  27105. const dotBL = anisotropyB.dot( lightDirection );
  27106. const dotBV = anisotropyB.dot( positionViewDirection );
  27107. const dotBH = anisotropyB.dot( halfDir );
  27108. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27109. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27110. } else {
  27111. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27112. D = D_GGX( { alpha, dotNH } );
  27113. }
  27114. return F.mul( V ).mul( D );
  27115. } ); // validated
  27116. // Analytical approximation of the DFG LUT, one half of the
  27117. // split-sum approximation used in indirect specular lighting.
  27118. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27119. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27120. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27121. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27122. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27123. const r = roughness.mul( c0 ).add( c1 );
  27124. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27125. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27126. return fab;
  27127. } ).setLayout( {
  27128. name: 'DFGApprox',
  27129. type: 'vec2',
  27130. inputs: [
  27131. { name: 'roughness', type: 'float' },
  27132. { name: 'dotNV', type: 'vec3' }
  27133. ]
  27134. } );
  27135. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27136. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27137. const fab = DFGApprox( { dotNV, roughness } );
  27138. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27139. } );
  27140. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27141. const x = dotVH.oneMinus().saturate();
  27142. const x2 = x.mul( x );
  27143. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27144. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27145. } ).setLayout( {
  27146. name: 'Schlick_to_F0',
  27147. type: 'vec3',
  27148. inputs: [
  27149. { name: 'f', type: 'vec3' },
  27150. { name: 'f90', type: 'float' },
  27151. { name: 'dotVH', type: 'float' }
  27152. ]
  27153. } );
  27154. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27155. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27156. const alpha = roughness.pow2();
  27157. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27158. const invAlpha = float( 1.0 ).div( alpha );
  27159. const cos2h = dotNH.pow2();
  27160. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27161. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27162. } ).setLayout( {
  27163. name: 'D_Charlie',
  27164. type: 'float',
  27165. inputs: [
  27166. { name: 'roughness', type: 'float' },
  27167. { name: 'dotNH', type: 'float' }
  27168. ]
  27169. } );
  27170. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27171. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27172. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27173. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27174. } ).setLayout( {
  27175. name: 'V_Neubelt',
  27176. type: 'float',
  27177. inputs: [
  27178. { name: 'dotNV', type: 'float' },
  27179. { name: 'dotNL', type: 'float' }
  27180. ]
  27181. } );
  27182. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27183. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27184. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27185. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27186. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27187. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27188. const V = V_Neubelt( { dotNV, dotNL } );
  27189. return sheen.mul( D ).mul( V );
  27190. } );
  27191. // Rect Area Light
  27192. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27193. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27194. // code: https://github.com/selfshadow/ltc_code/
  27195. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27196. const LUT_SIZE = 64.0;
  27197. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27198. const LUT_BIAS = 0.5 / LUT_SIZE;
  27199. const dotNV = N.dot( V ).saturate();
  27200. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27201. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27202. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27203. return uv;
  27204. } ).setLayout( {
  27205. name: 'LTC_Uv',
  27206. type: 'vec2',
  27207. inputs: [
  27208. { name: 'N', type: 'vec3' },
  27209. { name: 'V', type: 'vec3' },
  27210. { name: 'roughness', type: 'float' }
  27211. ]
  27212. } );
  27213. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27214. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27215. // An approximation of the form factor of a horizon-clipped rectangle.
  27216. const l = f.length();
  27217. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27218. } ).setLayout( {
  27219. name: 'LTC_ClippedSphereFormFactor',
  27220. type: 'float',
  27221. inputs: [
  27222. { name: 'f', type: 'vec3' }
  27223. ]
  27224. } );
  27225. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27226. const x = v1.dot( v2 );
  27227. const y = x.abs().toVar();
  27228. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27229. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27230. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27231. const v = a.div( b );
  27232. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27233. return v1.cross( v2 ).mul( theta_sintheta );
  27234. } ).setLayout( {
  27235. name: 'LTC_EdgeVectorFormFactor',
  27236. type: 'vec3',
  27237. inputs: [
  27238. { name: 'v1', type: 'vec3' },
  27239. { name: 'v2', type: 'vec3' }
  27240. ]
  27241. } );
  27242. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27243. // bail if point is on back side of plane of light
  27244. // assumes ccw winding order of light vertices
  27245. const v1 = p1.sub( p0 ).toVar();
  27246. const v2 = p3.sub( p0 ).toVar();
  27247. const lightNormal = v1.cross( v2 );
  27248. const result = vec3().toVar();
  27249. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27250. // construct orthonormal basis around N
  27251. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27252. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27253. // compute transform
  27254. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27255. // transform rect
  27256. // & project rect onto sphere
  27257. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27258. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27259. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27260. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27261. // calculate vector form factor
  27262. const vectorFormFactor = vec3( 0 ).toVar();
  27263. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27264. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27265. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27266. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27267. // adjust for horizon clipping
  27268. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27269. } );
  27270. return result;
  27271. } ).setLayout( {
  27272. name: 'LTC_Evaluate',
  27273. type: 'vec3',
  27274. inputs: [
  27275. { name: 'N', type: 'vec3' },
  27276. { name: 'V', type: 'vec3' },
  27277. { name: 'P', type: 'vec3' },
  27278. { name: 'mInv', type: 'mat3' },
  27279. { name: 'p0', type: 'vec3' },
  27280. { name: 'p1', type: 'vec3' },
  27281. { name: 'p2', type: 'vec3' },
  27282. { name: 'p3', type: 'vec3' }
  27283. ]
  27284. } );
  27285. // Mipped Bicubic Texture Filtering by N8
  27286. // https://www.shadertoy.com/view/Dl2SDW
  27287. const bC = 1.0 / 6.0;
  27288. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27289. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27290. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27291. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27292. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27293. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27294. // h0 and h1 are the two offset functions
  27295. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27296. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27297. const bicubic = ( textureNode, texelSize, lod ) => {
  27298. const uv = textureNode.uvNode;
  27299. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27300. const iuv = floor( uvScaled );
  27301. const fuv = fract( uvScaled );
  27302. const g0x = g0( fuv.x );
  27303. const g1x = g1( fuv.x );
  27304. const h0x = h0( fuv.x );
  27305. const h1x = h1( fuv.x );
  27306. const h0y = h0( fuv.y );
  27307. const h1y = h1( fuv.y );
  27308. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27309. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27310. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27311. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27312. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27313. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27314. return a.add( b );
  27315. };
  27316. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27317. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27318. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27319. const fLodSizeInv = div( 1.0, fLodSize );
  27320. const cLodSizeInv = div( 1.0, cLodSize );
  27321. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27322. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27323. return fract( lodNode ).mix( fSample, cSample );
  27324. } );
  27325. //
  27326. // Transmission
  27327. //
  27328. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  27329. // Direction of refracted light.
  27330. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  27331. // Compute rotation-independant scaling of the model matrix.
  27332. const modelScale = vec3(
  27333. length( modelMatrix[ 0 ].xyz ),
  27334. length( modelMatrix[ 1 ].xyz ),
  27335. length( modelMatrix[ 2 ].xyz )
  27336. );
  27337. // The thickness is specified in local space.
  27338. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  27339. } ).setLayout( {
  27340. name: 'getVolumeTransmissionRay',
  27341. type: 'vec3',
  27342. inputs: [
  27343. { name: 'n', type: 'vec3' },
  27344. { name: 'v', type: 'vec3' },
  27345. { name: 'thickness', type: 'float' },
  27346. { name: 'ior', type: 'float' },
  27347. { name: 'modelMatrix', type: 'mat4' }
  27348. ]
  27349. } );
  27350. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  27351. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  27352. // an IOR of 1.5 results in the default amount of microfacet refraction.
  27353. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  27354. } ).setLayout( {
  27355. name: 'applyIorToRoughness',
  27356. type: 'float',
  27357. inputs: [
  27358. { name: 'roughness', type: 'float' },
  27359. { name: 'ior', type: 'float' }
  27360. ]
  27361. } );
  27362. const singleViewportMipTexture = /*@__PURE__*/ viewportMipTexture();
  27363. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ] ) => {
  27364. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  27365. //const transmissionSample = viewportMipTexture( fragCoord );
  27366. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  27367. return textureBicubic( transmissionSample, lod );
  27368. } );
  27369. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  27370. If( attenuationDistance.notEqual( 0 ), () => {
  27371. // Compute light attenuation using Beer's law.
  27372. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  27373. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  27374. return transmittance;
  27375. } );
  27376. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  27377. return vec3( 1.0 );
  27378. } ).setLayout( {
  27379. name: 'volumeAttenuation',
  27380. type: 'vec3',
  27381. inputs: [
  27382. { name: 'transmissionDistance', type: 'float' },
  27383. { name: 'attenuationColor', type: 'vec3' },
  27384. { name: 'attenuationDistance', type: 'float' }
  27385. ]
  27386. } );
  27387. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  27388. let transmittedLight, transmittance;
  27389. if ( dispersion ) {
  27390. transmittedLight = vec4().toVar();
  27391. transmittance = vec3().toVar();
  27392. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  27393. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  27394. Loop( { start: 0, end: 3 }, ( { i } ) => {
  27395. const ior = iors.element( i );
  27396. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27397. const refractedRayExit = position.add( transmissionRay );
  27398. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27399. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27400. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27401. refractionCoords.addAssign( 1.0 );
  27402. refractionCoords.divAssign( 2.0 );
  27403. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27404. // Sample framebuffer to get pixel the refracted ray hits.
  27405. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  27406. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  27407. transmittedLight.a.addAssign( transmissionSample.a );
  27408. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  27409. } );
  27410. transmittedLight.a.divAssign( 3.0 );
  27411. } else {
  27412. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27413. const refractedRayExit = position.add( transmissionRay );
  27414. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27415. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27416. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27417. refractionCoords.addAssign( 1.0 );
  27418. refractionCoords.divAssign( 2.0 );
  27419. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27420. // Sample framebuffer to get pixel the refracted ray hits.
  27421. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  27422. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  27423. }
  27424. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  27425. const dotNV = n.dot( v ).clamp();
  27426. // Get the specular component.
  27427. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  27428. dotNV,
  27429. specularColor,
  27430. specularF90,
  27431. roughness
  27432. } ) );
  27433. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  27434. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  27435. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  27436. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  27437. } );
  27438. //
  27439. // Iridescence
  27440. //
  27441. // XYZ to linear-sRGB color space
  27442. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  27443. 3.2404542, - 0.9692660, 0.0556434,
  27444. - 1.5371385, 1.8760108, - 0.2040259,
  27445. - 0.4985314, 0.0415560, 1.0572252
  27446. );
  27447. // Assume air interface for top
  27448. // Note: We don't handle the case fresnel0 == 1
  27449. const Fresnel0ToIor = ( fresnel0 ) => {
  27450. const sqrtF0 = fresnel0.sqrt();
  27451. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  27452. };
  27453. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  27454. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  27455. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  27456. };
  27457. // Fresnel equations for dielectric/dielectric interfaces.
  27458. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  27459. // Evaluation XYZ sensitivity curves in Fourier space
  27460. const evalSensitivity = ( OPD, shift ) => {
  27461. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  27462. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  27463. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  27464. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  27465. 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() );
  27466. 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() );
  27467. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  27468. const rgb = XYZ_TO_REC709.mul( xyz );
  27469. return rgb;
  27470. };
  27471. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  27472. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  27473. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  27474. // Evaluate the cosTheta on the base layer (Snell law)
  27475. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  27476. // Handle TIR:
  27477. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  27478. /*if ( cosTheta2Sq < 0.0 ) {
  27479. return vec3( 1.0 );
  27480. }*/
  27481. const cosTheta2 = cosTheta2Sq.sqrt();
  27482. // First interface
  27483. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  27484. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  27485. //const R21 = R12;
  27486. const T121 = R12.oneMinus();
  27487. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  27488. const phi21 = float( Math.PI ).sub( phi12 );
  27489. // Second interface
  27490. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  27491. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  27492. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  27493. const phi23 = vec3(
  27494. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  27495. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  27496. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  27497. );
  27498. // Phase shift
  27499. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  27500. const phi = vec3( phi21 ).add( phi23 );
  27501. // Compound terms
  27502. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  27503. const r123 = R123.sqrt();
  27504. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  27505. // Reflectance term for m = 0 (DC term amplitude)
  27506. const C0 = R12.add( Rs );
  27507. let I = C0;
  27508. // Reflectance term for m > 0 (pairs of diracs)
  27509. let Cm = Rs.sub( T121 );
  27510. for ( let m = 1; m <= 2; ++ m ) {
  27511. Cm = Cm.mul( r123 );
  27512. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  27513. I = I.add( Cm.mul( Sm ) );
  27514. }
  27515. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  27516. return I.max( vec3( 0.0 ) );
  27517. } ).setLayout( {
  27518. name: 'evalIridescence',
  27519. type: 'vec3',
  27520. inputs: [
  27521. { name: 'outsideIOR', type: 'float' },
  27522. { name: 'eta2', type: 'float' },
  27523. { name: 'cosTheta1', type: 'float' },
  27524. { name: 'thinFilmThickness', type: 'float' },
  27525. { name: 'baseF0', type: 'vec3' }
  27526. ]
  27527. } );
  27528. //
  27529. // Sheen
  27530. //
  27531. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  27532. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  27533. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  27534. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  27535. const dotNV = normal.dot( viewDir ).saturate();
  27536. const r2 = roughness.pow2();
  27537. const a = select(
  27538. roughness.lessThan( 0.25 ),
  27539. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  27540. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  27541. );
  27542. const b = select(
  27543. roughness.lessThan( 0.25 ),
  27544. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  27545. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  27546. );
  27547. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  27548. return DG.mul( 1.0 / Math.PI ).saturate();
  27549. } );
  27550. const clearcoatF0 = vec3( 0.04 );
  27551. const clearcoatF90 = float( 1 );
  27552. //
  27553. class PhysicalLightingModel extends LightingModel {
  27554. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  27555. super();
  27556. this.clearcoat = clearcoat;
  27557. this.sheen = sheen;
  27558. this.iridescence = iridescence;
  27559. this.anisotropy = anisotropy;
  27560. this.transmission = transmission;
  27561. this.dispersion = dispersion;
  27562. this.clearcoatRadiance = null;
  27563. this.clearcoatSpecularDirect = null;
  27564. this.clearcoatSpecularIndirect = null;
  27565. this.sheenSpecularDirect = null;
  27566. this.sheenSpecularIndirect = null;
  27567. this.iridescenceFresnel = null;
  27568. this.iridescenceF0 = null;
  27569. }
  27570. start( context ) {
  27571. if ( this.clearcoat === true ) {
  27572. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  27573. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  27574. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  27575. }
  27576. if ( this.sheen === true ) {
  27577. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  27578. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  27579. }
  27580. if ( this.iridescence === true ) {
  27581. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  27582. this.iridescenceFresnel = evalIridescence( {
  27583. outsideIOR: float( 1.0 ),
  27584. eta2: iridescenceIOR,
  27585. cosTheta1: dotNVi,
  27586. thinFilmThickness: iridescenceThickness,
  27587. baseF0: specularColor
  27588. } );
  27589. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  27590. }
  27591. if ( this.transmission === true ) {
  27592. const position = positionWorld;
  27593. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  27594. const n = transformedNormalWorld;
  27595. context.backdrop = getIBLVolumeRefraction(
  27596. n,
  27597. v,
  27598. roughness,
  27599. diffuseColor,
  27600. specularColor,
  27601. specularF90, // specularF90
  27602. position, // positionWorld
  27603. modelWorldMatrix, // modelMatrix
  27604. cameraViewMatrix, // viewMatrix
  27605. cameraProjectionMatrix, // projMatrix
  27606. ior,
  27607. thickness,
  27608. attenuationColor,
  27609. attenuationDistance,
  27610. this.dispersion ? dispersion : null
  27611. );
  27612. context.backdropAlpha = transmission;
  27613. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  27614. }
  27615. }
  27616. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  27617. // Approximates multiscattering in order to preserve energy.
  27618. // http://www.jcgt.org/published/0008/01/03/
  27619. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  27620. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27621. const fab = DFGApprox( { roughness, dotNV } );
  27622. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  27623. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27624. const Ess = fab.x.add( fab.y );
  27625. const Ems = Ess.oneMinus();
  27626. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  27627. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  27628. singleScatter.addAssign( FssEss );
  27629. multiScatter.addAssign( Fms.mul( Ems ) );
  27630. }
  27631. direct( { lightDirection, lightColor, reflectedLight } ) {
  27632. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27633. const irradiance = dotNL.mul( lightColor );
  27634. if ( this.sheen === true ) {
  27635. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  27636. }
  27637. if ( this.clearcoat === true ) {
  27638. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  27639. const ccIrradiance = dotNLcc.mul( lightColor );
  27640. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  27641. }
  27642. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27643. 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 } ) ) );
  27644. }
  27645. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  27646. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  27647. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  27648. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  27649. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  27650. const N = transformedNormalView;
  27651. const V = positionViewDirection;
  27652. const P = positionView.toVar();
  27653. const uv = LTC_Uv( { N, V, roughness } );
  27654. const t1 = ltc_1.uv( uv ).toVar();
  27655. const t2 = ltc_2.uv( uv ).toVar();
  27656. const mInv = mat3(
  27657. vec3( t1.x, 0, t1.y ),
  27658. vec3( 0, 1, 0 ),
  27659. vec3( t1.z, 0, t1.w )
  27660. ).toVar();
  27661. // LTC Fresnel Approximation by Stephen Hill
  27662. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  27663. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  27664. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  27665. 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 } ) ) );
  27666. }
  27667. indirect( context, stack, builder ) {
  27668. this.indirectDiffuse( context, stack, builder );
  27669. this.indirectSpecular( context, stack, builder );
  27670. this.ambientOcclusion( context, stack, builder );
  27671. }
  27672. indirectDiffuse( { irradiance, reflectedLight } ) {
  27673. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27674. }
  27675. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  27676. if ( this.sheen === true ) {
  27677. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  27678. sheen,
  27679. IBLSheenBRDF( {
  27680. normal: transformedNormalView,
  27681. viewDir: positionViewDirection,
  27682. roughness: sheenRoughness
  27683. } )
  27684. ) );
  27685. }
  27686. if ( this.clearcoat === true ) {
  27687. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  27688. const clearcoatEnv = EnvironmentBRDF( {
  27689. dotNV: dotNVcc,
  27690. specularColor: clearcoatF0,
  27691. specularF90: clearcoatF90,
  27692. roughness: clearcoatRoughness
  27693. } );
  27694. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  27695. }
  27696. // Both indirect specular and indirect diffuse light accumulate here
  27697. const singleScattering = vec3().toVar( 'singleScattering' );
  27698. const multiScattering = vec3().toVar( 'multiScattering' );
  27699. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  27700. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  27701. const totalScattering = singleScattering.add( multiScattering );
  27702. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  27703. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  27704. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  27705. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  27706. }
  27707. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  27708. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27709. const aoNV = dotNV.add( ambientOcclusion );
  27710. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  27711. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  27712. if ( this.clearcoat === true ) {
  27713. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  27714. }
  27715. if ( this.sheen === true ) {
  27716. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  27717. }
  27718. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27719. reflectedLight.indirectSpecular.mulAssign( aoNode );
  27720. }
  27721. finish( context ) {
  27722. const { outgoingLight } = context;
  27723. if ( this.clearcoat === true ) {
  27724. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  27725. const Fcc = F_Schlick( {
  27726. dotVH: dotNVcc,
  27727. f0: clearcoatF0,
  27728. f90: clearcoatF90
  27729. } );
  27730. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  27731. outgoingLight.assign( clearcoatLight );
  27732. }
  27733. if ( this.sheen === true ) {
  27734. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  27735. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  27736. outgoingLight.assign( sheenLight );
  27737. }
  27738. }
  27739. }
  27740. // These defines must match with PMREMGenerator
  27741. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  27742. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  27743. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  27744. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  27745. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  27746. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  27747. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  27748. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  27749. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  27750. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  27751. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  27752. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  27753. // These shader functions convert between the UV coordinates of a single face of
  27754. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  27755. // sampling a textureCube (not generally normalized ).
  27756. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  27757. const absDirection = vec3( abs( direction ) ).toVar();
  27758. const face = float( - 1.0 ).toVar();
  27759. If( absDirection.x.greaterThan( absDirection.z ), () => {
  27760. If( absDirection.x.greaterThan( absDirection.y ), () => {
  27761. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  27762. } ).Else( () => {
  27763. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27764. } );
  27765. } ).Else( () => {
  27766. If( absDirection.z.greaterThan( absDirection.y ), () => {
  27767. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  27768. } ).Else( () => {
  27769. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27770. } );
  27771. } );
  27772. return face;
  27773. } ).setLayout( {
  27774. name: 'getFace',
  27775. type: 'float',
  27776. inputs: [
  27777. { name: 'direction', type: 'vec3' }
  27778. ]
  27779. } );
  27780. // RH coordinate system; PMREM face-indexing convention
  27781. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  27782. const uv = vec2().toVar();
  27783. If( face.equal( 0.0 ), () => {
  27784. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  27785. } ).ElseIf( face.equal( 1.0 ), () => {
  27786. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  27787. } ).ElseIf( face.equal( 2.0 ), () => {
  27788. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  27789. } ).ElseIf( face.equal( 3.0 ), () => {
  27790. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  27791. } ).ElseIf( face.equal( 4.0 ), () => {
  27792. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  27793. } ).Else( () => {
  27794. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  27795. } );
  27796. return mul( 0.5, uv.add( 1.0 ) );
  27797. } ).setLayout( {
  27798. name: 'getUV',
  27799. type: 'vec2',
  27800. inputs: [
  27801. { name: 'direction', type: 'vec3' },
  27802. { name: 'face', type: 'float' }
  27803. ]
  27804. } );
  27805. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  27806. const mip = float( 0.0 ).toVar();
  27807. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  27808. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  27809. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  27810. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  27811. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  27812. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  27813. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  27814. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  27815. } ).Else( () => {
  27816. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  27817. } );
  27818. return mip;
  27819. } ).setLayout( {
  27820. name: 'roughnessToMip',
  27821. type: 'float',
  27822. inputs: [
  27823. { name: 'roughness', type: 'float' }
  27824. ]
  27825. } );
  27826. // RH coordinate system; PMREM face-indexing convention
  27827. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  27828. const uv = uv_immutable.toVar();
  27829. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  27830. const direction = vec3( uv, 1.0 ).toVar();
  27831. If( face.equal( 0.0 ), () => {
  27832. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  27833. } ).ElseIf( face.equal( 1.0 ), () => {
  27834. direction.assign( direction.xzy );
  27835. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  27836. } ).ElseIf( face.equal( 2.0 ), () => {
  27837. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  27838. } ).ElseIf( face.equal( 3.0 ), () => {
  27839. direction.assign( direction.zyx );
  27840. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  27841. } ).ElseIf( face.equal( 4.0 ), () => {
  27842. direction.assign( direction.xzy );
  27843. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  27844. } ).ElseIf( face.equal( 5.0 ), () => {
  27845. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  27846. } );
  27847. return direction;
  27848. } ).setLayout( {
  27849. name: 'getDirection',
  27850. type: 'vec3',
  27851. inputs: [
  27852. { name: 'uv', type: 'vec2' },
  27853. { name: 'face', type: 'float' }
  27854. ]
  27855. } );
  27856. //
  27857. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27858. const roughness = float( roughness_immutable );
  27859. const sampleDir = vec3( sampleDir_immutable );
  27860. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  27861. const mipF = fract( mip );
  27862. const mipInt = floor( mip );
  27863. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27864. If( mipF.notEqual( 0.0 ), () => {
  27865. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27866. color0.assign( mix( color0, color1, mipF ) );
  27867. } );
  27868. return color0;
  27869. } );
  27870. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27871. const mipInt = float( mipInt_immutable ).toVar();
  27872. const direction = vec3( direction_immutable );
  27873. const face = float( getFace( direction ) ).toVar();
  27874. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  27875. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  27876. const faceSize = float( exp2( mipInt ) ).toVar();
  27877. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  27878. If( face.greaterThan( 2.0 ), () => {
  27879. uv.y.addAssign( faceSize );
  27880. face.subAssign( 3.0 );
  27881. } );
  27882. uv.x.addAssign( face.mul( faceSize ) );
  27883. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  27884. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  27885. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  27886. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  27887. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  27888. } );
  27889. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27890. const cosTheta = cos( theta );
  27891. // Rodrigues' axis-angle rotation
  27892. const sampleDirection = outputDirection.mul( cosTheta )
  27893. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  27894. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  27895. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  27896. } );
  27897. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27898. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  27899. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  27900. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  27901. } );
  27902. axis.assign( normalize( axis ) );
  27903. const gl_FragColor = vec3().toVar();
  27904. 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 } ) ) );
  27905. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  27906. If( i.greaterThanEqual( samples ), () => {
  27907. Break();
  27908. } );
  27909. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  27910. 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 } ) ) );
  27911. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27912. } );
  27913. return vec4( gl_FragColor, 1 );
  27914. } );
  27915. let _generator = null;
  27916. const _cache = new WeakMap();
  27917. function _generateCubeUVSize( imageHeight ) {
  27918. const maxMip = Math.log2( imageHeight ) - 2;
  27919. const texelHeight = 1.0 / imageHeight;
  27920. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  27921. return { texelWidth, texelHeight, maxMip };
  27922. }
  27923. function _getPMREMFromTexture( texture ) {
  27924. let cacheTexture = _cache.get( texture );
  27925. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  27926. if ( pmremVersion !== texture.pmremVersion ) {
  27927. const image = texture.image;
  27928. if ( texture.isCubeTexture ) {
  27929. if ( isCubeMapReady( image ) ) {
  27930. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  27931. } else {
  27932. return null;
  27933. }
  27934. } else {
  27935. if ( isEquirectangularMapReady( image ) ) {
  27936. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  27937. } else {
  27938. return null;
  27939. }
  27940. }
  27941. cacheTexture.pmremVersion = texture.pmremVersion;
  27942. _cache.set( texture, cacheTexture );
  27943. }
  27944. return cacheTexture.texture;
  27945. }
  27946. class PMREMNode extends TempNode {
  27947. static get type() {
  27948. return 'PMREMNode';
  27949. }
  27950. constructor( value, uvNode = null, levelNode = null ) {
  27951. super( 'vec3' );
  27952. this._value = value;
  27953. this._pmrem = null;
  27954. this.uvNode = uvNode;
  27955. this.levelNode = levelNode;
  27956. this._generator = null;
  27957. const defaultTexture = new Texture();
  27958. defaultTexture.isRenderTargetTexture = true;
  27959. this._texture = texture( defaultTexture );
  27960. this._width = uniform( 0 );
  27961. this._height = uniform( 0 );
  27962. this._maxMip = uniform( 0 );
  27963. this.updateBeforeType = NodeUpdateType.RENDER;
  27964. }
  27965. set value( value ) {
  27966. this._value = value;
  27967. this._pmrem = null;
  27968. }
  27969. get value() {
  27970. return this._value;
  27971. }
  27972. updateFromTexture( texture ) {
  27973. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  27974. this._texture.value = texture;
  27975. this._width.value = cubeUVSize.texelWidth;
  27976. this._height.value = cubeUVSize.texelHeight;
  27977. this._maxMip.value = cubeUVSize.maxMip;
  27978. }
  27979. updateBefore() {
  27980. let pmrem = this._pmrem;
  27981. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  27982. const texture = this._value;
  27983. if ( pmremVersion !== texture.pmremVersion ) {
  27984. if ( texture.isPMREMTexture === true ) {
  27985. pmrem = texture;
  27986. } else {
  27987. pmrem = _getPMREMFromTexture( texture );
  27988. }
  27989. if ( pmrem !== null ) {
  27990. this._pmrem = pmrem;
  27991. this.updateFromTexture( pmrem );
  27992. }
  27993. }
  27994. }
  27995. setup( builder ) {
  27996. if ( _generator === null ) {
  27997. _generator = builder.createPMREMGenerator();
  27998. }
  27999. //
  28000. this.updateBefore( builder );
  28001. //
  28002. let uvNode = this.uvNode;
  28003. if ( uvNode === null && builder.context.getUV ) {
  28004. uvNode = builder.context.getUV( this );
  28005. }
  28006. //
  28007. const texture = this.value;
  28008. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28009. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28010. }
  28011. //
  28012. let levelNode = this.levelNode;
  28013. if ( levelNode === null && builder.context.getTextureLevel ) {
  28014. levelNode = builder.context.getTextureLevel( this );
  28015. }
  28016. //
  28017. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28018. }
  28019. }
  28020. function isCubeMapReady( image ) {
  28021. if ( image === null || image === undefined ) return false;
  28022. let count = 0;
  28023. const length = 6;
  28024. for ( let i = 0; i < length; i ++ ) {
  28025. if ( image[ i ] !== undefined ) count ++;
  28026. }
  28027. return count === length;
  28028. }
  28029. function isEquirectangularMapReady( image ) {
  28030. if ( image === null || image === undefined ) return false;
  28031. return image.height > 0;
  28032. }
  28033. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28034. const _envNodeCache = new WeakMap();
  28035. class EnvironmentNode extends LightingNode {
  28036. static get type() {
  28037. return 'EnvironmentNode';
  28038. }
  28039. constructor( envNode = null ) {
  28040. super();
  28041. this.envNode = envNode;
  28042. }
  28043. setup( builder ) {
  28044. const { material } = builder;
  28045. let envNode = this.envNode;
  28046. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28047. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28048. let cacheEnvNode = _envNodeCache.get( value );
  28049. if ( cacheEnvNode === undefined ) {
  28050. cacheEnvNode = pmremTexture( value );
  28051. _envNodeCache.set( value, cacheEnvNode );
  28052. }
  28053. envNode = cacheEnvNode;
  28054. }
  28055. //
  28056. const envMap = material.envMap;
  28057. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28058. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28059. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28060. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28061. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28062. const isolateRadiance = cache( radiance );
  28063. const isolateIrradiance = cache( irradiance );
  28064. //
  28065. builder.context.radiance.addAssign( isolateRadiance );
  28066. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28067. //
  28068. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28069. if ( clearcoatRadiance ) {
  28070. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28071. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28072. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28073. }
  28074. }
  28075. }
  28076. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28077. let reflectVec = null;
  28078. return {
  28079. getUV: () => {
  28080. if ( reflectVec === null ) {
  28081. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28082. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28083. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28084. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28085. }
  28086. return reflectVec;
  28087. },
  28088. getTextureLevel: () => {
  28089. return roughnessNode;
  28090. }
  28091. };
  28092. };
  28093. const createIrradianceContext = ( normalWorldNode ) => {
  28094. return {
  28095. getUV: () => {
  28096. return normalWorldNode;
  28097. },
  28098. getTextureLevel: () => {
  28099. return float( 1.0 );
  28100. }
  28101. };
  28102. };
  28103. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28104. class MeshStandardNodeMaterial extends NodeMaterial {
  28105. static get type() {
  28106. return 'MeshStandardNodeMaterial';
  28107. }
  28108. constructor( parameters ) {
  28109. super();
  28110. this.isMeshStandardNodeMaterial = true;
  28111. this.lights = true;
  28112. this.emissiveNode = null;
  28113. this.metalnessNode = null;
  28114. this.roughnessNode = null;
  28115. this.setDefaultValues( _defaultValues$6 );
  28116. this.setValues( parameters );
  28117. }
  28118. setupEnvironment( builder ) {
  28119. let envNode = super.setupEnvironment( builder );
  28120. if ( envNode === null && builder.environmentNode ) {
  28121. envNode = builder.environmentNode;
  28122. }
  28123. return envNode ? new EnvironmentNode( envNode ) : null;
  28124. }
  28125. setupLightingModel( /*builder*/ ) {
  28126. return new PhysicalLightingModel();
  28127. }
  28128. setupSpecular() {
  28129. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28130. specularColor.assign( specularColorNode );
  28131. specularF90.assign( 1.0 );
  28132. }
  28133. setupVariants() {
  28134. // METALNESS
  28135. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28136. metalness.assign( metalnessNode );
  28137. // ROUGHNESS
  28138. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28139. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28140. roughness.assign( roughnessNode );
  28141. // SPECULAR COLOR
  28142. this.setupSpecular();
  28143. // DIFFUSE COLOR
  28144. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28145. }
  28146. copy( source ) {
  28147. this.emissiveNode = source.emissiveNode;
  28148. this.metalnessNode = source.metalnessNode;
  28149. this.roughnessNode = source.roughnessNode;
  28150. return super.copy( source );
  28151. }
  28152. }
  28153. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28154. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28155. static get type() {
  28156. return 'MeshPhysicalNodeMaterial';
  28157. }
  28158. constructor( parameters ) {
  28159. super();
  28160. this.isMeshPhysicalNodeMaterial = true;
  28161. this.clearcoatNode = null;
  28162. this.clearcoatRoughnessNode = null;
  28163. this.clearcoatNormalNode = null;
  28164. this.sheenNode = null;
  28165. this.sheenRoughnessNode = null;
  28166. this.iridescenceNode = null;
  28167. this.iridescenceIORNode = null;
  28168. this.iridescenceThicknessNode = null;
  28169. this.specularIntensityNode = null;
  28170. this.specularColorNode = null;
  28171. this.iorNode = null;
  28172. this.transmissionNode = null;
  28173. this.thicknessNode = null;
  28174. this.attenuationDistanceNode = null;
  28175. this.attenuationColorNode = null;
  28176. this.dispersionNode = null;
  28177. this.anisotropyNode = null;
  28178. this.setDefaultValues( _defaultValues$5 );
  28179. this.setValues( parameters );
  28180. }
  28181. get useClearcoat() {
  28182. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28183. }
  28184. get useIridescence() {
  28185. return this.iridescence > 0 || this.iridescenceNode !== null;
  28186. }
  28187. get useSheen() {
  28188. return this.sheen > 0 || this.sheenNode !== null;
  28189. }
  28190. get useAnisotropy() {
  28191. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28192. }
  28193. get useTransmission() {
  28194. return this.transmission > 0 || this.transmissionNode !== null;
  28195. }
  28196. get useDispersion() {
  28197. return this.dispersion > 0 || this.dispersionNode !== null;
  28198. }
  28199. setupSpecular() {
  28200. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28201. ior.assign( iorNode );
  28202. 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 ) );
  28203. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28204. }
  28205. setupLightingModel( /*builder*/ ) {
  28206. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28207. }
  28208. setupVariants( builder ) {
  28209. super.setupVariants( builder );
  28210. // CLEARCOAT
  28211. if ( this.useClearcoat ) {
  28212. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28213. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28214. clearcoat.assign( clearcoatNode );
  28215. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28216. }
  28217. // SHEEN
  28218. if ( this.useSheen ) {
  28219. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28220. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28221. sheen.assign( sheenNode );
  28222. sheenRoughness.assign( sheenRoughnessNode );
  28223. }
  28224. // IRIDESCENCE
  28225. if ( this.useIridescence ) {
  28226. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28227. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28228. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28229. iridescence.assign( iridescenceNode );
  28230. iridescenceIOR.assign( iridescenceIORNode );
  28231. iridescenceThickness.assign( iridescenceThicknessNode );
  28232. }
  28233. // ANISOTROPY
  28234. if ( this.useAnisotropy ) {
  28235. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28236. anisotropy.assign( anisotropyV.length() );
  28237. If( anisotropy.equal( 0.0 ), () => {
  28238. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28239. } ).Else( () => {
  28240. anisotropyV.divAssign( vec2( anisotropy ) );
  28241. anisotropy.assign( anisotropy.saturate() );
  28242. } );
  28243. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28244. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28245. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28246. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28247. }
  28248. // TRANSMISSION
  28249. if ( this.useTransmission ) {
  28250. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28251. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28252. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28253. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28254. transmission.assign( transmissionNode );
  28255. thickness.assign( thicknessNode );
  28256. attenuationDistance.assign( attenuationDistanceNode );
  28257. attenuationColor.assign( attenuationColorNode );
  28258. if ( this.useDispersion ) {
  28259. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28260. dispersion.assign( dispersionNode );
  28261. }
  28262. }
  28263. }
  28264. setupClearcoatNormal() {
  28265. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28266. }
  28267. setup( builder ) {
  28268. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28269. super.setup( builder );
  28270. }
  28271. copy( source ) {
  28272. this.clearcoatNode = source.clearcoatNode;
  28273. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28274. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28275. this.sheenNode = source.sheenNode;
  28276. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28277. this.iridescenceNode = source.iridescenceNode;
  28278. this.iridescenceIORNode = source.iridescenceIORNode;
  28279. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28280. this.specularIntensityNode = source.specularIntensityNode;
  28281. this.specularColorNode = source.specularColorNode;
  28282. this.transmissionNode = source.transmissionNode;
  28283. this.thicknessNode = source.thicknessNode;
  28284. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28285. this.attenuationColorNode = source.attenuationColorNode;
  28286. this.dispersionNode = source.dispersionNode;
  28287. this.anisotropyNode = source.anisotropyNode;
  28288. return super.copy( source );
  28289. }
  28290. }
  28291. class SSSLightingModel extends PhysicalLightingModel {
  28292. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28293. super( useClearcoat, useSheen, useIridescence );
  28294. this.useSSS = useSSS;
  28295. }
  28296. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28297. if ( this.useSSS === true ) {
  28298. const material = builder.material;
  28299. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28300. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28301. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28302. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28303. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28304. }
  28305. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28306. }
  28307. }
  28308. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28309. static get type() {
  28310. return 'MeshSSSNodeMaterial';
  28311. }
  28312. constructor( parameters ) {
  28313. super( parameters );
  28314. this.thicknessColorNode = null;
  28315. this.thicknessDistortionNode = float( 0.1 );
  28316. this.thicknessAmbientNode = float( 0.0 );
  28317. this.thicknessAttenuationNode = float( .1 );
  28318. this.thicknessPowerNode = float( 2.0 );
  28319. this.thicknessScaleNode = float( 10.0 );
  28320. }
  28321. get useSSS() {
  28322. return this.thicknessColorNode !== null;
  28323. }
  28324. setupLightingModel( /*builder*/ ) {
  28325. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28326. }
  28327. copy( source ) {
  28328. this.thicknessColorNode = source.thicknessColorNode;
  28329. this.thicknessDistortionNode = source.thicknessDistortionNode;
  28330. this.thicknessAmbientNode = source.thicknessAmbientNode;
  28331. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  28332. this.thicknessPowerNode = source.thicknessPowerNode;
  28333. this.thicknessScaleNode = source.thicknessScaleNode;
  28334. return super.copy( source );
  28335. }
  28336. }
  28337. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  28338. // dotNL will be from -1.0 to 1.0
  28339. const dotNL = normal.dot( lightDirection );
  28340. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  28341. if ( builder.material.gradientMap ) {
  28342. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  28343. return vec3( gradientMap.r );
  28344. } else {
  28345. const fw = coord.fwidth().mul( 0.5 );
  28346. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  28347. }
  28348. } );
  28349. class ToonLightingModel extends LightingModel {
  28350. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28351. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  28352. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28353. }
  28354. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  28355. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28356. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28357. }
  28358. }
  28359. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  28360. class MeshToonNodeMaterial extends NodeMaterial {
  28361. static get type() {
  28362. return 'MeshToonNodeMaterial';
  28363. }
  28364. constructor( parameters ) {
  28365. super();
  28366. this.isMeshToonNodeMaterial = true;
  28367. this.lights = true;
  28368. this.setDefaultValues( _defaultValues$4 );
  28369. this.setValues( parameters );
  28370. }
  28371. setupLightingModel( /*builder*/ ) {
  28372. return new ToonLightingModel();
  28373. }
  28374. }
  28375. class MatcapUVNode extends TempNode {
  28376. static get type() {
  28377. return 'MatcapUVNode';
  28378. }
  28379. constructor() {
  28380. super( 'vec2' );
  28381. }
  28382. setup() {
  28383. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28384. const y = positionViewDirection.cross( x );
  28385. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28386. }
  28387. }
  28388. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  28389. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  28390. class MeshMatcapNodeMaterial extends NodeMaterial {
  28391. static get type() {
  28392. return 'MeshMatcapNodeMaterial';
  28393. }
  28394. constructor( parameters ) {
  28395. super();
  28396. this.lights = false;
  28397. this.isMeshMatcapNodeMaterial = true;
  28398. this.setDefaultValues( _defaultValues$3 );
  28399. this.setValues( parameters );
  28400. }
  28401. setupVariants( builder ) {
  28402. const uv = matcapUV;
  28403. let matcapColor;
  28404. if ( builder.material.matcap ) {
  28405. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  28406. } else {
  28407. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  28408. }
  28409. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  28410. }
  28411. }
  28412. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  28413. class PointsNodeMaterial extends NodeMaterial {
  28414. static get type() {
  28415. return 'PointsNodeMaterial';
  28416. }
  28417. constructor( parameters ) {
  28418. super();
  28419. this.isPointsNodeMaterial = true;
  28420. this.lights = false;
  28421. this.transparent = true;
  28422. this.sizeNode = null;
  28423. this.setDefaultValues( _defaultValues$2 );
  28424. this.setValues( parameters );
  28425. }
  28426. copy( source ) {
  28427. this.sizeNode = source.sizeNode;
  28428. return super.copy( source );
  28429. }
  28430. }
  28431. class RotateNode extends TempNode {
  28432. static get type() {
  28433. return 'RotateNode';
  28434. }
  28435. constructor( positionNode, rotationNode ) {
  28436. super();
  28437. this.positionNode = positionNode;
  28438. this.rotationNode = rotationNode;
  28439. }
  28440. getNodeType( builder ) {
  28441. return this.positionNode.getNodeType( builder );
  28442. }
  28443. setup( builder ) {
  28444. const { rotationNode, positionNode } = this;
  28445. const nodeType = this.getNodeType( builder );
  28446. if ( nodeType === 'vec2' ) {
  28447. const cosAngle = rotationNode.cos();
  28448. const sinAngle = rotationNode.sin();
  28449. const rotationMatrix = mat2(
  28450. cosAngle, sinAngle,
  28451. sinAngle.negate(), cosAngle
  28452. );
  28453. return rotationMatrix.mul( positionNode );
  28454. } else {
  28455. const rotation = rotationNode;
  28456. 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 ) );
  28457. 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 ) );
  28458. 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 ) );
  28459. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  28460. }
  28461. }
  28462. }
  28463. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  28464. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  28465. class SpriteNodeMaterial extends NodeMaterial {
  28466. static get type() {
  28467. return 'SpriteNodeMaterial';
  28468. }
  28469. constructor( parameters ) {
  28470. super();
  28471. this.isSpriteNodeMaterial = true;
  28472. this.lights = false;
  28473. this.positionNode = null;
  28474. this.rotationNode = null;
  28475. this.scaleNode = null;
  28476. this.setDefaultValues( _defaultValues$1 );
  28477. this.setValues( parameters );
  28478. }
  28479. setupPosition( { object, context } ) {
  28480. // < VERTEX STAGE >
  28481. const { positionNode, rotationNode, scaleNode } = this;
  28482. const vertex = positionLocal;
  28483. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  28484. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  28485. if ( scaleNode !== null ) {
  28486. scale = scale.mul( scaleNode );
  28487. }
  28488. let alignedPosition = vertex.xy;
  28489. if ( object.center && object.center.isVector2 === true ) {
  28490. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  28491. }
  28492. alignedPosition = alignedPosition.mul( scale );
  28493. const rotation = float( rotationNode || materialRotation );
  28494. const rotatedPosition = rotate( alignedPosition, rotation );
  28495. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  28496. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  28497. context.vertex = vertex;
  28498. return modelViewProjection;
  28499. }
  28500. copy( source ) {
  28501. this.positionNode = source.positionNode;
  28502. this.rotationNode = source.rotationNode;
  28503. this.scaleNode = source.scaleNode;
  28504. return super.copy( source );
  28505. }
  28506. }
  28507. class ShadowMaskModel extends LightingModel {
  28508. constructor() {
  28509. super();
  28510. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  28511. }
  28512. direct( { shadowMask } ) {
  28513. this.shadowNode.mulAssign( shadowMask );
  28514. }
  28515. finish( context ) {
  28516. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  28517. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  28518. }
  28519. }
  28520. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  28521. class ShadowNodeMaterial extends NodeMaterial {
  28522. static get type() {
  28523. return 'ShadowNodeMaterial';
  28524. }
  28525. constructor( parameters ) {
  28526. super();
  28527. this.isShadowNodeMaterial = true;
  28528. this.lights = true;
  28529. this.setDefaultValues( _defaultValues );
  28530. this.setValues( parameters );
  28531. }
  28532. setupLightingModel( /*builder*/ ) {
  28533. return new ShadowMaskModel();
  28534. }
  28535. }
  28536. const normal = Fn( ( { texture, uv } ) => {
  28537. const epsilon = 0.0001;
  28538. const ret = vec3().temp();
  28539. If( uv.x.lessThan( epsilon ), () => {
  28540. ret.assign( vec3( 1, 0, 0 ) );
  28541. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  28542. ret.assign( vec3( 0, 1, 0 ) );
  28543. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  28544. ret.assign( vec3( 0, 0, 1 ) );
  28545. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  28546. ret.assign( vec3( - 1, 0, 0 ) );
  28547. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  28548. ret.assign( vec3( 0, - 1, 0 ) );
  28549. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  28550. ret.assign( vec3( 0, 0, - 1 ) );
  28551. } ).Else( () => {
  28552. const step = 0.01;
  28553. 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 );
  28554. 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 );
  28555. 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 );
  28556. ret.assign( vec3( x, y, z ) );
  28557. } );
  28558. return ret.normalize();
  28559. } );
  28560. class Texture3DNode extends TextureNode {
  28561. static get type() {
  28562. return 'Texture3DNode';
  28563. }
  28564. constructor( value, uvNode = null, levelNode = null ) {
  28565. super( value, uvNode, levelNode );
  28566. this.isTexture3DNode = true;
  28567. }
  28568. getInputType( /*builder*/ ) {
  28569. return 'texture3D';
  28570. }
  28571. getDefaultUV() {
  28572. return vec3( 0.5, 0.5, 0.5 );
  28573. }
  28574. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  28575. setupUV( builder, uvNode ) {
  28576. return uvNode;
  28577. }
  28578. generateUV( builder, uvNode ) {
  28579. return uvNode.build( builder, 'vec3' );
  28580. }
  28581. normal( uvNode ) {
  28582. return normal( { texture: this, uv: uvNode } );
  28583. }
  28584. }
  28585. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  28586. class VolumeNodeMaterial extends NodeMaterial {
  28587. static get type() {
  28588. return 'VolumeNodeMaterial';
  28589. }
  28590. constructor( params = {} ) {
  28591. super();
  28592. this.lights = false;
  28593. this.isVolumeNodeMaterial = true;
  28594. this.testNode = null;
  28595. this.setValues( params );
  28596. }
  28597. setup( builder ) {
  28598. const map = texture3D( this.map, null, 0 );
  28599. const hitBox = Fn( ( { orig, dir } ) => {
  28600. const box_min = vec3( - 0.5 );
  28601. const box_max = vec3( 0.5 );
  28602. const inv_dir = dir.reciprocal();
  28603. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  28604. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  28605. const tmin = min$1( tmin_tmp, tmax_tmp );
  28606. const tmax = max$1( tmin_tmp, tmax_tmp );
  28607. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  28608. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  28609. return vec2( t0, t1 );
  28610. } );
  28611. this.fragmentNode = Fn( () => {
  28612. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  28613. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  28614. const rayDir = vDirection.normalize();
  28615. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  28616. bounds.x.greaterThan( bounds.y ).discard();
  28617. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  28618. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  28619. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  28620. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  28621. delta.divAssign( materialReference( 'steps', 'float' ) );
  28622. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  28623. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  28624. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  28625. if ( this.testNode !== null ) {
  28626. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  28627. } else {
  28628. // default to show surface of mesh
  28629. ac.a.assign( 1 );
  28630. Break();
  28631. }
  28632. p.addAssign( rayDir.mul( delta ) );
  28633. } );
  28634. ac.a.equal( 0 ).discard();
  28635. return vec4( ac );
  28636. } )();
  28637. super.setup( builder );
  28638. }
  28639. }
  28640. class Animation {
  28641. constructor( nodes, info ) {
  28642. this.nodes = nodes;
  28643. this.info = info;
  28644. this.animationLoop = null;
  28645. this.requestId = null;
  28646. this._init();
  28647. }
  28648. _init() {
  28649. const update = ( time, frame ) => {
  28650. this.requestId = self.requestAnimationFrame( update );
  28651. if ( this.info.autoReset === true ) this.info.reset();
  28652. this.nodes.nodeFrame.update();
  28653. this.info.frame = this.nodes.nodeFrame.frameId;
  28654. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  28655. };
  28656. update();
  28657. }
  28658. dispose() {
  28659. self.cancelAnimationFrame( this.requestId );
  28660. this.requestId = null;
  28661. }
  28662. setAnimationLoop( callback ) {
  28663. this.animationLoop = callback;
  28664. }
  28665. }
  28666. class ChainMap {
  28667. constructor() {
  28668. this.weakMap = new WeakMap();
  28669. }
  28670. get( keys ) {
  28671. let map = this.weakMap;
  28672. for ( let i = 0; i < keys.length; i ++ ) {
  28673. map = map.get( keys[ i ] );
  28674. if ( map === undefined ) return undefined;
  28675. }
  28676. return map.get( keys[ keys.length - 1 ] );
  28677. }
  28678. set( keys, value ) {
  28679. let map = this.weakMap;
  28680. for ( let i = 0; i < keys.length; i ++ ) {
  28681. const key = keys[ i ];
  28682. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  28683. map = map.get( key );
  28684. }
  28685. return map.set( keys[ keys.length - 1 ], value );
  28686. }
  28687. delete( keys ) {
  28688. let map = this.weakMap;
  28689. for ( let i = 0; i < keys.length; i ++ ) {
  28690. map = map.get( keys[ i ] );
  28691. if ( map === undefined ) return false;
  28692. }
  28693. return map.delete( keys[ keys.length - 1 ] );
  28694. }
  28695. }
  28696. const _plane = /*@__PURE__*/ new Plane();
  28697. class ClippingContext {
  28698. constructor() {
  28699. this.version = 0;
  28700. this.globalClippingCount = 0;
  28701. this.localClippingCount = 0;
  28702. this.localClippingEnabled = false;
  28703. this.localClipIntersection = false;
  28704. this.planes = [];
  28705. this.parentVersion = 0;
  28706. this.viewNormalMatrix = new Matrix3();
  28707. this.cacheKey = '';
  28708. }
  28709. projectPlanes( source, offset ) {
  28710. const l = source.length;
  28711. const planes = this.planes;
  28712. for ( let i = 0; i < l; i ++ ) {
  28713. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  28714. const v = planes[ offset + i ];
  28715. const normal = _plane.normal;
  28716. v.x = - normal.x;
  28717. v.y = - normal.y;
  28718. v.z = - normal.z;
  28719. v.w = _plane.constant;
  28720. }
  28721. }
  28722. updateGlobal( renderer, camera ) {
  28723. const rendererClippingPlanes = renderer.clippingPlanes;
  28724. this.viewMatrix = camera.matrixWorldInverse;
  28725. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  28726. let update = false;
  28727. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  28728. const l = rendererClippingPlanes.length;
  28729. if ( l !== this.globalClippingCount ) {
  28730. const planes = [];
  28731. for ( let i = 0; i < l; i ++ ) {
  28732. planes.push( new Vector4() );
  28733. }
  28734. this.globalClippingCount = l;
  28735. this.planes = planes;
  28736. update = true;
  28737. }
  28738. this.projectPlanes( rendererClippingPlanes, 0 );
  28739. } else if ( this.globalClippingCount !== 0 ) {
  28740. this.globalClippingCount = 0;
  28741. this.planes = [];
  28742. update = true;
  28743. }
  28744. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  28745. this.localClippingEnabled = renderer.localClippingEnabled;
  28746. update = true;
  28747. }
  28748. if ( update ) {
  28749. this.version ++;
  28750. this.cacheKey = `${ this.globalClippingCount }:${ this.localClippingEnabled === undefined ? false : this.localClippingEnabled }:`;
  28751. }
  28752. }
  28753. update( parent, material ) {
  28754. let update = false;
  28755. if ( this !== parent && parent.version !== this.parentVersion ) {
  28756. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  28757. this.localClippingEnabled = parent.localClippingEnabled;
  28758. this.planes = Array.from( parent.planes );
  28759. this.parentVersion = parent.version;
  28760. this.viewMatrix = parent.viewMatrix;
  28761. this.viewNormalMatrix = parent.viewNormalMatrix;
  28762. update = true;
  28763. }
  28764. if ( this.localClippingEnabled ) {
  28765. const localClippingPlanes = material.clippingPlanes;
  28766. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  28767. const l = localClippingPlanes.length;
  28768. const planes = this.planes;
  28769. const offset = this.globalClippingCount;
  28770. if ( update || l !== this.localClippingCount ) {
  28771. planes.length = offset + l;
  28772. for ( let i = 0; i < l; i ++ ) {
  28773. planes[ offset + i ] = new Vector4();
  28774. }
  28775. this.localClippingCount = l;
  28776. update = true;
  28777. }
  28778. this.projectPlanes( localClippingPlanes, offset );
  28779. } else if ( this.localClippingCount !== 0 ) {
  28780. this.localClippingCount = 0;
  28781. update = true;
  28782. }
  28783. if ( this.localClipIntersection !== material.clipIntersection ) {
  28784. this.localClipIntersection = material.clipIntersection;
  28785. update = true;
  28786. }
  28787. }
  28788. if ( update ) {
  28789. this.version += parent.version;
  28790. this.cacheKey = parent.cacheKey + `:${ this.localClippingCount }:${ this.localClipIntersection === undefined ? false : this.localClipIntersection }`;
  28791. }
  28792. }
  28793. }
  28794. let _id$7 = 0;
  28795. function getKeys( obj ) {
  28796. const keys = Object.keys( obj );
  28797. let proto = Object.getPrototypeOf( obj );
  28798. while ( proto ) {
  28799. const descriptors = Object.getOwnPropertyDescriptors( proto );
  28800. for ( const key in descriptors ) {
  28801. if ( descriptors[ key ] !== undefined ) {
  28802. const descriptor = descriptors[ key ];
  28803. if ( descriptor && typeof descriptor.get === 'function' ) {
  28804. keys.push( key );
  28805. }
  28806. }
  28807. }
  28808. proto = Object.getPrototypeOf( proto );
  28809. }
  28810. return keys;
  28811. }
  28812. class RenderObject {
  28813. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  28814. this._nodes = nodes;
  28815. this._geometries = geometries;
  28816. this.id = _id$7 ++;
  28817. this.renderer = renderer;
  28818. this.object = object;
  28819. this.material = material;
  28820. this.scene = scene;
  28821. this.camera = camera;
  28822. this.lightsNode = lightsNode;
  28823. this.context = renderContext;
  28824. this.geometry = object.geometry;
  28825. this.version = material.version;
  28826. this.drawRange = null;
  28827. this.attributes = null;
  28828. this.pipeline = null;
  28829. this.vertexBuffers = null;
  28830. this.updateClipping( renderContext.clippingContext );
  28831. this.clippingContextVersion = this.clippingContext.version;
  28832. this.initialNodesCacheKey = this.getDynamicCacheKey();
  28833. this.initialCacheKey = this.getCacheKey();
  28834. this._nodeBuilderState = null;
  28835. this._bindings = null;
  28836. this.onDispose = null;
  28837. this.isRenderObject = true;
  28838. this.onMaterialDispose = () => {
  28839. this.dispose();
  28840. };
  28841. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  28842. }
  28843. updateClipping( parent ) {
  28844. const material = this.material;
  28845. let clippingContext = this.clippingContext;
  28846. if ( Array.isArray( material.clippingPlanes ) ) {
  28847. if ( clippingContext === parent || ! clippingContext ) {
  28848. clippingContext = new ClippingContext();
  28849. this.clippingContext = clippingContext;
  28850. }
  28851. clippingContext.update( parent, material );
  28852. } else if ( this.clippingContext !== parent ) {
  28853. this.clippingContext = parent;
  28854. }
  28855. }
  28856. get clippingNeedsUpdate() {
  28857. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  28858. this.clippingContextVersion = this.clippingContext.version;
  28859. return true;
  28860. }
  28861. getNodeBuilderState() {
  28862. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  28863. }
  28864. getBindings() {
  28865. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  28866. }
  28867. getIndex() {
  28868. return this._geometries.getIndex( this );
  28869. }
  28870. getChainArray() {
  28871. return [ this.object, this.material, this.context, this.lightsNode ];
  28872. }
  28873. getAttributes() {
  28874. if ( this.attributes !== null ) return this.attributes;
  28875. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  28876. const geometry = this.geometry;
  28877. const attributes = [];
  28878. const vertexBuffers = new Set();
  28879. for ( const nodeAttribute of nodeAttributes ) {
  28880. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  28881. if ( attribute === undefined ) continue;
  28882. attributes.push( attribute );
  28883. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  28884. vertexBuffers.add( bufferAttribute );
  28885. }
  28886. this.attributes = attributes;
  28887. this.vertexBuffers = Array.from( vertexBuffers.values() );
  28888. return attributes;
  28889. }
  28890. getVertexBuffers() {
  28891. if ( this.vertexBuffers === null ) this.getAttributes();
  28892. return this.vertexBuffers;
  28893. }
  28894. getMaterialCacheKey() {
  28895. const { object, material } = this;
  28896. let cacheKey = material.customProgramCacheKey();
  28897. for ( const property of getKeys( material ) ) {
  28898. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  28899. const value = material[ property ];
  28900. let valueKey;
  28901. if ( value !== null ) {
  28902. // some material values require a formatting
  28903. const type = typeof value;
  28904. if ( type === 'number' ) {
  28905. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  28906. } else if ( type === 'object' ) {
  28907. valueKey = '{';
  28908. if ( value.isTexture ) {
  28909. valueKey += value.mapping;
  28910. }
  28911. valueKey += '}';
  28912. } else {
  28913. valueKey = String( value );
  28914. }
  28915. } else {
  28916. valueKey = String( value );
  28917. }
  28918. cacheKey += /*property + ':' +*/ valueKey + ',';
  28919. }
  28920. cacheKey += this.clippingContext.cacheKey + ',';
  28921. if ( object.skeleton ) {
  28922. cacheKey += object.skeleton.bones.length + ',';
  28923. }
  28924. if ( object.morphTargetInfluences ) {
  28925. cacheKey += object.morphTargetInfluences.length + ',';
  28926. }
  28927. if ( object.isBatchedMesh ) {
  28928. cacheKey += object._matricesTexture.uuid + ',';
  28929. if ( object._colorsTexture !== null ) {
  28930. cacheKey += object._colorsTexture.uuid + ',';
  28931. }
  28932. }
  28933. if ( object.count > 1 ) {
  28934. cacheKey += object.count + ',' + object.uuid + ',';
  28935. }
  28936. return cacheKey;
  28937. }
  28938. get needsUpdate() {
  28939. return this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate;
  28940. }
  28941. getDynamicCacheKey() {
  28942. // Environment Nodes Cache Key
  28943. return this.object.receiveShadow + ',' + this._nodes.getCacheKey( this.scene, this.lightsNode );
  28944. }
  28945. getCacheKey() {
  28946. return this.getMaterialCacheKey() + ',' + this.getDynamicCacheKey();
  28947. }
  28948. dispose() {
  28949. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  28950. this.onDispose();
  28951. }
  28952. }
  28953. class RenderObjects {
  28954. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  28955. this.renderer = renderer;
  28956. this.nodes = nodes;
  28957. this.geometries = geometries;
  28958. this.pipelines = pipelines;
  28959. this.bindings = bindings;
  28960. this.info = info;
  28961. this.chainMaps = {};
  28962. }
  28963. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  28964. const chainMap = this.getChainMap( passId );
  28965. const chainArray = [ object, material, renderContext, lightsNode ];
  28966. let renderObject = chainMap.get( chainArray );
  28967. if ( renderObject === undefined ) {
  28968. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  28969. chainMap.set( chainArray, renderObject );
  28970. } else {
  28971. renderObject.updateClipping( renderContext.clippingContext );
  28972. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  28973. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  28974. renderObject.dispose();
  28975. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  28976. } else {
  28977. renderObject.version = material.version;
  28978. }
  28979. }
  28980. }
  28981. return renderObject;
  28982. }
  28983. getChainMap( passId = 'default' ) {
  28984. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  28985. }
  28986. dispose() {
  28987. this.chainMaps = {};
  28988. }
  28989. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  28990. const chainMap = this.getChainMap( passId );
  28991. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  28992. renderObject.onDispose = () => {
  28993. this.pipelines.delete( renderObject );
  28994. this.bindings.delete( renderObject );
  28995. this.nodes.delete( renderObject );
  28996. chainMap.delete( renderObject.getChainArray() );
  28997. };
  28998. return renderObject;
  28999. }
  29000. }
  29001. class DataMap {
  29002. constructor() {
  29003. this.data = new WeakMap();
  29004. }
  29005. get( object ) {
  29006. let map = this.data.get( object );
  29007. if ( map === undefined ) {
  29008. map = {};
  29009. this.data.set( object, map );
  29010. }
  29011. return map;
  29012. }
  29013. delete( object ) {
  29014. let map;
  29015. if ( this.data.has( object ) ) {
  29016. map = this.data.get( object );
  29017. this.data.delete( object );
  29018. }
  29019. return map;
  29020. }
  29021. has( object ) {
  29022. return this.data.has( object );
  29023. }
  29024. dispose() {
  29025. this.data = new WeakMap();
  29026. }
  29027. }
  29028. const AttributeType = {
  29029. VERTEX: 1,
  29030. INDEX: 2,
  29031. STORAGE: 4
  29032. };
  29033. // size of a chunk in bytes (STD140 layout)
  29034. const GPU_CHUNK_BYTES = 16;
  29035. // @TODO: Move to src/constants.js
  29036. const BlendColorFactor = 211;
  29037. const OneMinusBlendColorFactor = 212;
  29038. class Attributes extends DataMap {
  29039. constructor( backend ) {
  29040. super();
  29041. this.backend = backend;
  29042. }
  29043. delete( attribute ) {
  29044. const attributeData = super.delete( attribute );
  29045. if ( attributeData !== undefined ) {
  29046. this.backend.destroyAttribute( attribute );
  29047. }
  29048. return attributeData;
  29049. }
  29050. update( attribute, type ) {
  29051. const data = this.get( attribute );
  29052. if ( data.version === undefined ) {
  29053. if ( type === AttributeType.VERTEX ) {
  29054. this.backend.createAttribute( attribute );
  29055. } else if ( type === AttributeType.INDEX ) {
  29056. this.backend.createIndexAttribute( attribute );
  29057. } else if ( type === AttributeType.STORAGE ) {
  29058. this.backend.createStorageAttribute( attribute );
  29059. }
  29060. data.version = this._getBufferAttribute( attribute ).version;
  29061. } else {
  29062. const bufferAttribute = this._getBufferAttribute( attribute );
  29063. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29064. this.backend.updateAttribute( attribute );
  29065. data.version = bufferAttribute.version;
  29066. }
  29067. }
  29068. }
  29069. _getBufferAttribute( attribute ) {
  29070. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29071. return attribute;
  29072. }
  29073. }
  29074. function arrayNeedsUint32( array ) {
  29075. // assumes larger values usually on last
  29076. for ( let i = array.length - 1; i >= 0; -- i ) {
  29077. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29078. }
  29079. return false;
  29080. }
  29081. function getWireframeVersion( geometry ) {
  29082. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29083. }
  29084. function getWireframeIndex( geometry ) {
  29085. const indices = [];
  29086. const geometryIndex = geometry.index;
  29087. const geometryPosition = geometry.attributes.position;
  29088. if ( geometryIndex !== null ) {
  29089. const array = geometryIndex.array;
  29090. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29091. const a = array[ i + 0 ];
  29092. const b = array[ i + 1 ];
  29093. const c = array[ i + 2 ];
  29094. indices.push( a, b, b, c, c, a );
  29095. }
  29096. } else {
  29097. const array = geometryPosition.array;
  29098. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29099. const a = i + 0;
  29100. const b = i + 1;
  29101. const c = i + 2;
  29102. indices.push( a, b, b, c, c, a );
  29103. }
  29104. }
  29105. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29106. attribute.version = getWireframeVersion( geometry );
  29107. return attribute;
  29108. }
  29109. class Geometries extends DataMap {
  29110. constructor( attributes, info ) {
  29111. super();
  29112. this.attributes = attributes;
  29113. this.info = info;
  29114. this.wireframes = new WeakMap();
  29115. this.attributeCall = new WeakMap();
  29116. }
  29117. has( renderObject ) {
  29118. const geometry = renderObject.geometry;
  29119. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29120. }
  29121. updateForRender( renderObject ) {
  29122. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29123. this.updateAttributes( renderObject );
  29124. }
  29125. initGeometry( renderObject ) {
  29126. const geometry = renderObject.geometry;
  29127. const geometryData = this.get( geometry );
  29128. geometryData.initialized = true;
  29129. this.info.memory.geometries ++;
  29130. const onDispose = () => {
  29131. this.info.memory.geometries --;
  29132. const index = geometry.index;
  29133. const geometryAttributes = renderObject.getAttributes();
  29134. if ( index !== null ) {
  29135. this.attributes.delete( index );
  29136. }
  29137. for ( const geometryAttribute of geometryAttributes ) {
  29138. this.attributes.delete( geometryAttribute );
  29139. }
  29140. const wireframeAttribute = this.wireframes.get( geometry );
  29141. if ( wireframeAttribute !== undefined ) {
  29142. this.attributes.delete( wireframeAttribute );
  29143. }
  29144. geometry.removeEventListener( 'dispose', onDispose );
  29145. };
  29146. geometry.addEventListener( 'dispose', onDispose );
  29147. }
  29148. updateAttributes( renderObject ) {
  29149. const attributes = renderObject.getAttributes();
  29150. for ( const attribute of attributes ) {
  29151. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29152. this.updateAttribute( attribute, AttributeType.STORAGE );
  29153. } else {
  29154. this.updateAttribute( attribute, AttributeType.VERTEX );
  29155. }
  29156. }
  29157. const index = this.getIndex( renderObject );
  29158. if ( index !== null ) {
  29159. this.updateAttribute( index, AttributeType.INDEX );
  29160. }
  29161. }
  29162. updateAttribute( attribute, type ) {
  29163. const callId = this.info.render.calls;
  29164. if ( ! attribute.isInterleavedBufferAttribute ) {
  29165. if ( this.attributeCall.get( attribute ) !== callId ) {
  29166. this.attributes.update( attribute, type );
  29167. this.attributeCall.set( attribute, callId );
  29168. }
  29169. } else {
  29170. if ( this.attributeCall.get( attribute ) === undefined ) {
  29171. this.attributes.update( attribute, type );
  29172. this.attributeCall.set( attribute, callId );
  29173. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29174. this.attributes.update( attribute, type );
  29175. this.attributeCall.set( attribute.data, callId );
  29176. this.attributeCall.set( attribute, callId );
  29177. }
  29178. }
  29179. }
  29180. getIndex( renderObject ) {
  29181. const { geometry, material } = renderObject;
  29182. let index = geometry.index;
  29183. if ( material.wireframe === true ) {
  29184. const wireframes = this.wireframes;
  29185. let wireframeAttribute = wireframes.get( geometry );
  29186. if ( wireframeAttribute === undefined ) {
  29187. wireframeAttribute = getWireframeIndex( geometry );
  29188. wireframes.set( geometry, wireframeAttribute );
  29189. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29190. this.attributes.delete( wireframeAttribute );
  29191. wireframeAttribute = getWireframeIndex( geometry );
  29192. wireframes.set( geometry, wireframeAttribute );
  29193. }
  29194. index = wireframeAttribute;
  29195. }
  29196. return index;
  29197. }
  29198. }
  29199. class Info {
  29200. constructor() {
  29201. this.autoReset = true;
  29202. this.frame = 0;
  29203. this.calls = 0;
  29204. this.render = {
  29205. calls: 0,
  29206. frameCalls: 0,
  29207. drawCalls: 0,
  29208. triangles: 0,
  29209. points: 0,
  29210. lines: 0,
  29211. timestamp: 0,
  29212. previousFrameCalls: 0,
  29213. timestampCalls: 0
  29214. };
  29215. this.compute = {
  29216. calls: 0,
  29217. frameCalls: 0,
  29218. timestamp: 0,
  29219. previousFrameCalls: 0,
  29220. timestampCalls: 0
  29221. };
  29222. this.memory = {
  29223. geometries: 0,
  29224. textures: 0
  29225. };
  29226. }
  29227. update( object, count, instanceCount ) {
  29228. this.render.drawCalls ++;
  29229. if ( object.isMesh || object.isSprite ) {
  29230. this.render.triangles += instanceCount * ( count / 3 );
  29231. } else if ( object.isPoints ) {
  29232. this.render.points += instanceCount * count;
  29233. } else if ( object.isLineSegments ) {
  29234. this.render.lines += instanceCount * ( count / 2 );
  29235. } else if ( object.isLine ) {
  29236. this.render.lines += instanceCount * ( count - 1 );
  29237. } else {
  29238. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  29239. }
  29240. }
  29241. updateTimestamp( type, time ) {
  29242. if ( this[ type ].timestampCalls === 0 ) {
  29243. this[ type ].timestamp = 0;
  29244. }
  29245. this[ type ].timestamp += time;
  29246. this[ type ].timestampCalls ++;
  29247. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  29248. this[ type ].timestampCalls = 0;
  29249. }
  29250. }
  29251. reset() {
  29252. const previousRenderFrameCalls = this.render.frameCalls;
  29253. this.render.previousFrameCalls = previousRenderFrameCalls;
  29254. const previousComputeFrameCalls = this.compute.frameCalls;
  29255. this.compute.previousFrameCalls = previousComputeFrameCalls;
  29256. this.render.drawCalls = 0;
  29257. this.render.frameCalls = 0;
  29258. this.compute.frameCalls = 0;
  29259. this.render.triangles = 0;
  29260. this.render.points = 0;
  29261. this.render.lines = 0;
  29262. }
  29263. dispose() {
  29264. this.reset();
  29265. this.calls = 0;
  29266. this.render.calls = 0;
  29267. this.compute.calls = 0;
  29268. this.render.timestamp = 0;
  29269. this.compute.timestamp = 0;
  29270. this.memory.geometries = 0;
  29271. this.memory.textures = 0;
  29272. }
  29273. }
  29274. class Pipeline {
  29275. constructor( cacheKey ) {
  29276. this.cacheKey = cacheKey;
  29277. this.usedTimes = 0;
  29278. }
  29279. }
  29280. class RenderPipeline extends Pipeline {
  29281. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  29282. super( cacheKey );
  29283. this.vertexProgram = vertexProgram;
  29284. this.fragmentProgram = fragmentProgram;
  29285. }
  29286. }
  29287. class ComputePipeline extends Pipeline {
  29288. constructor( cacheKey, computeProgram ) {
  29289. super( cacheKey );
  29290. this.computeProgram = computeProgram;
  29291. this.isComputePipeline = true;
  29292. }
  29293. }
  29294. let _id$6 = 0;
  29295. class ProgrammableStage {
  29296. constructor( code, type, transforms = null, attributes = null ) {
  29297. this.id = _id$6 ++;
  29298. this.code = code;
  29299. this.stage = type;
  29300. this.transforms = transforms;
  29301. this.attributes = attributes;
  29302. this.usedTimes = 0;
  29303. }
  29304. }
  29305. class Pipelines extends DataMap {
  29306. constructor( backend, nodes ) {
  29307. super();
  29308. this.backend = backend;
  29309. this.nodes = nodes;
  29310. this.bindings = null; // set by the bindings
  29311. this.caches = new Map();
  29312. this.programs = {
  29313. vertex: new Map(),
  29314. fragment: new Map(),
  29315. compute: new Map()
  29316. };
  29317. }
  29318. getForCompute( computeNode, bindings ) {
  29319. const { backend } = this;
  29320. const data = this.get( computeNode );
  29321. if ( this._needsComputeUpdate( computeNode ) ) {
  29322. const previousPipeline = data.pipeline;
  29323. if ( previousPipeline ) {
  29324. previousPipeline.usedTimes --;
  29325. previousPipeline.computeProgram.usedTimes --;
  29326. }
  29327. // get shader
  29328. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  29329. // programmable stage
  29330. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  29331. if ( stageCompute === undefined ) {
  29332. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  29333. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  29334. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  29335. backend.createProgram( stageCompute );
  29336. }
  29337. // determine compute pipeline
  29338. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  29339. let pipeline = this.caches.get( cacheKey );
  29340. if ( pipeline === undefined ) {
  29341. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29342. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  29343. }
  29344. // keep track of all used times
  29345. pipeline.usedTimes ++;
  29346. stageCompute.usedTimes ++;
  29347. //
  29348. data.version = computeNode.version;
  29349. data.pipeline = pipeline;
  29350. }
  29351. return data.pipeline;
  29352. }
  29353. getForRender( renderObject, promises = null ) {
  29354. const { backend } = this;
  29355. const data = this.get( renderObject );
  29356. if ( this._needsRenderUpdate( renderObject ) ) {
  29357. const previousPipeline = data.pipeline;
  29358. if ( previousPipeline ) {
  29359. previousPipeline.usedTimes --;
  29360. previousPipeline.vertexProgram.usedTimes --;
  29361. previousPipeline.fragmentProgram.usedTimes --;
  29362. }
  29363. // get shader
  29364. const nodeBuilderState = renderObject.getNodeBuilderState();
  29365. // programmable stages
  29366. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  29367. if ( stageVertex === undefined ) {
  29368. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  29369. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  29370. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  29371. backend.createProgram( stageVertex );
  29372. }
  29373. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  29374. if ( stageFragment === undefined ) {
  29375. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  29376. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  29377. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  29378. backend.createProgram( stageFragment );
  29379. }
  29380. // determine render pipeline
  29381. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  29382. let pipeline = this.caches.get( cacheKey );
  29383. if ( pipeline === undefined ) {
  29384. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29385. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  29386. } else {
  29387. renderObject.pipeline = pipeline;
  29388. }
  29389. // keep track of all used times
  29390. pipeline.usedTimes ++;
  29391. stageVertex.usedTimes ++;
  29392. stageFragment.usedTimes ++;
  29393. //
  29394. data.pipeline = pipeline;
  29395. }
  29396. return data.pipeline;
  29397. }
  29398. delete( object ) {
  29399. const pipeline = this.get( object ).pipeline;
  29400. if ( pipeline ) {
  29401. // pipeline
  29402. pipeline.usedTimes --;
  29403. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  29404. // programs
  29405. if ( pipeline.isComputePipeline ) {
  29406. pipeline.computeProgram.usedTimes --;
  29407. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  29408. } else {
  29409. pipeline.fragmentProgram.usedTimes --;
  29410. pipeline.vertexProgram.usedTimes --;
  29411. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  29412. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  29413. }
  29414. }
  29415. return super.delete( object );
  29416. }
  29417. dispose() {
  29418. super.dispose();
  29419. this.caches = new Map();
  29420. this.programs = {
  29421. vertex: new Map(),
  29422. fragment: new Map(),
  29423. compute: new Map()
  29424. };
  29425. }
  29426. updateForRender( renderObject ) {
  29427. this.getForRender( renderObject );
  29428. }
  29429. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  29430. // check for existing pipeline
  29431. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  29432. let pipeline = this.caches.get( cacheKey );
  29433. if ( pipeline === undefined ) {
  29434. pipeline = new ComputePipeline( cacheKey, stageCompute );
  29435. this.caches.set( cacheKey, pipeline );
  29436. this.backend.createComputePipeline( pipeline, bindings );
  29437. }
  29438. return pipeline;
  29439. }
  29440. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  29441. // check for existing pipeline
  29442. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  29443. let pipeline = this.caches.get( cacheKey );
  29444. if ( pipeline === undefined ) {
  29445. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  29446. this.caches.set( cacheKey, pipeline );
  29447. renderObject.pipeline = pipeline;
  29448. this.backend.createRenderPipeline( renderObject, promises );
  29449. }
  29450. return pipeline;
  29451. }
  29452. _getComputeCacheKey( computeNode, stageCompute ) {
  29453. return computeNode.id + ',' + stageCompute.id;
  29454. }
  29455. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  29456. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  29457. }
  29458. _releasePipeline( pipeline ) {
  29459. this.caches.delete( pipeline.cacheKey );
  29460. }
  29461. _releaseProgram( program ) {
  29462. const code = program.code;
  29463. const stage = program.stage;
  29464. this.programs[ stage ].delete( code );
  29465. }
  29466. _needsComputeUpdate( computeNode ) {
  29467. const data = this.get( computeNode );
  29468. return data.pipeline === undefined || data.version !== computeNode.version;
  29469. }
  29470. _needsRenderUpdate( renderObject ) {
  29471. const data = this.get( renderObject );
  29472. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  29473. }
  29474. }
  29475. class Bindings extends DataMap {
  29476. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  29477. super();
  29478. this.backend = backend;
  29479. this.textures = textures;
  29480. this.pipelines = pipelines;
  29481. this.attributes = attributes;
  29482. this.nodes = nodes;
  29483. this.info = info;
  29484. this.pipelines.bindings = this; // assign bindings to pipelines
  29485. }
  29486. getForRender( renderObject ) {
  29487. const bindings = renderObject.getBindings();
  29488. for ( const bindGroup of bindings ) {
  29489. const groupData = this.get( bindGroup );
  29490. if ( groupData.bindGroup === undefined ) {
  29491. // each object defines an array of bindings (ubos, textures, samplers etc.)
  29492. this._init( bindGroup );
  29493. this.backend.createBindings( bindGroup, bindings );
  29494. groupData.bindGroup = bindGroup;
  29495. }
  29496. }
  29497. return bindings;
  29498. }
  29499. getForCompute( computeNode ) {
  29500. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  29501. for ( const bindGroup of bindings ) {
  29502. const groupData = this.get( bindGroup );
  29503. if ( groupData.bindGroup === undefined ) {
  29504. this._init( bindGroup );
  29505. this.backend.createBindings( bindGroup, bindings );
  29506. groupData.bindGroup = bindGroup;
  29507. }
  29508. }
  29509. return bindings;
  29510. }
  29511. updateForCompute( computeNode ) {
  29512. this._updateBindings( this.getForCompute( computeNode ) );
  29513. }
  29514. updateForRender( renderObject ) {
  29515. this._updateBindings( this.getForRender( renderObject ) );
  29516. }
  29517. _updateBindings( bindings ) {
  29518. for ( const bindGroup of bindings ) {
  29519. this._update( bindGroup, bindings );
  29520. }
  29521. }
  29522. _init( bindGroup ) {
  29523. for ( const binding of bindGroup.bindings ) {
  29524. if ( binding.isSampledTexture ) {
  29525. this.textures.updateTexture( binding.texture );
  29526. } else if ( binding.isStorageBuffer ) {
  29527. const attribute = binding.attribute;
  29528. this.attributes.update( attribute, AttributeType.STORAGE );
  29529. }
  29530. }
  29531. }
  29532. _update( bindGroup, bindings ) {
  29533. const { backend } = this;
  29534. let needsBindingsUpdate = false;
  29535. // iterate over all bindings and check if buffer updates or a new binding group is required
  29536. for ( const binding of bindGroup.bindings ) {
  29537. if ( binding.isNodeUniformsGroup ) {
  29538. const updated = this.nodes.updateGroup( binding );
  29539. if ( ! updated ) continue;
  29540. }
  29541. if ( binding.isUniformBuffer ) {
  29542. const updated = binding.update();
  29543. if ( updated ) {
  29544. backend.updateBinding( binding );
  29545. }
  29546. } else if ( binding.isSampler ) {
  29547. binding.update();
  29548. } else if ( binding.isSampledTexture ) {
  29549. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  29550. const updated = binding.update();
  29551. const texture = binding.texture;
  29552. if ( updated ) {
  29553. this.textures.updateTexture( texture );
  29554. }
  29555. const textureData = backend.get( texture );
  29556. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  29557. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  29558. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  29559. this.textures.updateTexture( texture );
  29560. needsBindingsUpdate = true;
  29561. }
  29562. if ( texture.isStorageTexture === true ) {
  29563. const textureData = this.get( texture );
  29564. if ( binding.store === true ) {
  29565. textureData.needsMipmap = true;
  29566. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  29567. this.backend.generateMipmaps( texture );
  29568. textureData.needsMipmap = false;
  29569. }
  29570. }
  29571. }
  29572. }
  29573. if ( needsBindingsUpdate === true ) {
  29574. this.backend.updateBindings( bindGroup, bindings );
  29575. }
  29576. }
  29577. }
  29578. class NodeAttribute {
  29579. constructor( name, type, node = null ) {
  29580. this.isNodeAttribute = true;
  29581. this.name = name;
  29582. this.type = type;
  29583. this.node = node;
  29584. }
  29585. }
  29586. class NodeUniform {
  29587. constructor( name, type, node ) {
  29588. this.isNodeUniform = true;
  29589. this.name = name;
  29590. this.type = type;
  29591. this.node = node.getSelf();
  29592. }
  29593. get value() {
  29594. return this.node.value;
  29595. }
  29596. set value( val ) {
  29597. this.node.value = val;
  29598. }
  29599. get id() {
  29600. return this.node.id;
  29601. }
  29602. get groupNode() {
  29603. return this.node.groupNode;
  29604. }
  29605. }
  29606. class NodeVar {
  29607. constructor( name, type ) {
  29608. this.isNodeVar = true;
  29609. this.name = name;
  29610. this.type = type;
  29611. }
  29612. }
  29613. class NodeVarying extends NodeVar {
  29614. constructor( name, type ) {
  29615. super( name, type );
  29616. this.needsInterpolation = false;
  29617. this.isNodeVarying = true;
  29618. }
  29619. }
  29620. class NodeCode {
  29621. constructor( name, type, code = '' ) {
  29622. this.name = name;
  29623. this.type = type;
  29624. this.code = code;
  29625. Object.defineProperty( this, 'isNodeCode', { value: true } );
  29626. }
  29627. }
  29628. let id$1 = 0;
  29629. class NodeCache {
  29630. constructor( parent = null ) {
  29631. this.id = id$1 ++;
  29632. this.nodesData = new WeakMap();
  29633. this.parent = parent;
  29634. }
  29635. getData( node ) {
  29636. let data = this.nodesData.get( node );
  29637. if ( data === undefined && this.parent !== null ) {
  29638. data = this.parent.getData( node );
  29639. }
  29640. return data;
  29641. }
  29642. setData( node, data ) {
  29643. this.nodesData.set( node, data );
  29644. }
  29645. }
  29646. class ParameterNode extends PropertyNode {
  29647. static get type() {
  29648. return 'ParameterNode';
  29649. }
  29650. constructor( nodeType, name = null ) {
  29651. super( nodeType, name );
  29652. this.isParameterNode = true;
  29653. }
  29654. getHash() {
  29655. return this.uuid;
  29656. }
  29657. generate() {
  29658. return this.name;
  29659. }
  29660. }
  29661. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  29662. class CodeNode extends Node {
  29663. static get type() {
  29664. return 'CodeNode';
  29665. }
  29666. constructor( code = '', includes = [], language = '' ) {
  29667. super( 'code' );
  29668. this.isCodeNode = true;
  29669. this.code = code;
  29670. this.language = language;
  29671. this.includes = includes;
  29672. }
  29673. isGlobal() {
  29674. return true;
  29675. }
  29676. setIncludes( includes ) {
  29677. this.includes = includes;
  29678. return this;
  29679. }
  29680. getIncludes( /*builder*/ ) {
  29681. return this.includes;
  29682. }
  29683. generate( builder ) {
  29684. const includes = this.getIncludes( builder );
  29685. for ( const include of includes ) {
  29686. include.build( builder );
  29687. }
  29688. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  29689. nodeCode.code = this.code;
  29690. return nodeCode.code;
  29691. }
  29692. serialize( data ) {
  29693. super.serialize( data );
  29694. data.code = this.code;
  29695. data.language = this.language;
  29696. }
  29697. deserialize( data ) {
  29698. super.deserialize( data );
  29699. this.code = data.code;
  29700. this.language = data.language;
  29701. }
  29702. }
  29703. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  29704. const js = ( src, includes ) => code( src, includes, 'js' );
  29705. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  29706. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  29707. class FunctionNode extends CodeNode {
  29708. static get type() {
  29709. return 'FunctionNode';
  29710. }
  29711. constructor( code = '', includes = [], language = '' ) {
  29712. super( code, includes, language );
  29713. }
  29714. getNodeType( builder ) {
  29715. return this.getNodeFunction( builder ).type;
  29716. }
  29717. getInputs( builder ) {
  29718. return this.getNodeFunction( builder ).inputs;
  29719. }
  29720. getNodeFunction( builder ) {
  29721. const nodeData = builder.getDataFromNode( this );
  29722. let nodeFunction = nodeData.nodeFunction;
  29723. if ( nodeFunction === undefined ) {
  29724. nodeFunction = builder.parser.parseFunction( this.code );
  29725. nodeData.nodeFunction = nodeFunction;
  29726. }
  29727. return nodeFunction;
  29728. }
  29729. generate( builder, output ) {
  29730. super.generate( builder );
  29731. const nodeFunction = this.getNodeFunction( builder );
  29732. const name = nodeFunction.name;
  29733. const type = nodeFunction.type;
  29734. const nodeCode = builder.getCodeFromNode( this, type );
  29735. if ( name !== '' ) {
  29736. // use a custom property name
  29737. nodeCode.name = name;
  29738. }
  29739. const propertyName = builder.getPropertyName( nodeCode );
  29740. const code = this.getNodeFunction( builder ).getCode( propertyName );
  29741. nodeCode.code = code + '\n';
  29742. if ( output === 'property' ) {
  29743. return propertyName;
  29744. } else {
  29745. return builder.format( `${ propertyName }()`, type, output );
  29746. }
  29747. }
  29748. }
  29749. const nativeFn = ( code, includes = [], language = '' ) => {
  29750. for ( let i = 0; i < includes.length; i ++ ) {
  29751. const include = includes[ i ];
  29752. // TSL Function: glslFn, wgslFn
  29753. if ( typeof include === 'function' ) {
  29754. includes[ i ] = include.functionNode;
  29755. }
  29756. }
  29757. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  29758. const fn = ( ...params ) => functionNode.call( ...params );
  29759. fn.functionNode = functionNode;
  29760. return fn;
  29761. };
  29762. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  29763. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  29764. class Uniform {
  29765. constructor( name, value ) {
  29766. this.name = name;
  29767. this.value = value;
  29768. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  29769. this.itemSize = 0;
  29770. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  29771. }
  29772. setValue( value ) {
  29773. this.value = value;
  29774. }
  29775. getValue() {
  29776. return this.value;
  29777. }
  29778. }
  29779. class NumberUniform extends Uniform {
  29780. constructor( name, value = 0 ) {
  29781. super( name, value );
  29782. this.isNumberUniform = true;
  29783. this.boundary = 4;
  29784. this.itemSize = 1;
  29785. }
  29786. }
  29787. class Vector2Uniform extends Uniform {
  29788. constructor( name, value = new Vector2() ) {
  29789. super( name, value );
  29790. this.isVector2Uniform = true;
  29791. this.boundary = 8;
  29792. this.itemSize = 2;
  29793. }
  29794. }
  29795. class Vector3Uniform extends Uniform {
  29796. constructor( name, value = new Vector3() ) {
  29797. super( name, value );
  29798. this.isVector3Uniform = true;
  29799. this.boundary = 16;
  29800. this.itemSize = 3;
  29801. }
  29802. }
  29803. class Vector4Uniform extends Uniform {
  29804. constructor( name, value = new Vector4() ) {
  29805. super( name, value );
  29806. this.isVector4Uniform = true;
  29807. this.boundary = 16;
  29808. this.itemSize = 4;
  29809. }
  29810. }
  29811. class ColorUniform extends Uniform {
  29812. constructor( name, value = new Color() ) {
  29813. super( name, value );
  29814. this.isColorUniform = true;
  29815. this.boundary = 16;
  29816. this.itemSize = 3;
  29817. }
  29818. }
  29819. class Matrix3Uniform extends Uniform {
  29820. constructor( name, value = new Matrix3() ) {
  29821. super( name, value );
  29822. this.isMatrix3Uniform = true;
  29823. this.boundary = 48;
  29824. this.itemSize = 12;
  29825. }
  29826. }
  29827. class Matrix4Uniform extends Uniform {
  29828. constructor( name, value = new Matrix4() ) {
  29829. super( name, value );
  29830. this.isMatrix4Uniform = true;
  29831. this.boundary = 64;
  29832. this.itemSize = 16;
  29833. }
  29834. }
  29835. class NumberNodeUniform extends NumberUniform {
  29836. constructor( nodeUniform ) {
  29837. super( nodeUniform.name, nodeUniform.value );
  29838. this.nodeUniform = nodeUniform;
  29839. }
  29840. getValue() {
  29841. return this.nodeUniform.value;
  29842. }
  29843. }
  29844. class Vector2NodeUniform extends Vector2Uniform {
  29845. constructor( nodeUniform ) {
  29846. super( nodeUniform.name, nodeUniform.value );
  29847. this.nodeUniform = nodeUniform;
  29848. }
  29849. getValue() {
  29850. return this.nodeUniform.value;
  29851. }
  29852. }
  29853. class Vector3NodeUniform extends Vector3Uniform {
  29854. constructor( nodeUniform ) {
  29855. super( nodeUniform.name, nodeUniform.value );
  29856. this.nodeUniform = nodeUniform;
  29857. }
  29858. getValue() {
  29859. return this.nodeUniform.value;
  29860. }
  29861. }
  29862. class Vector4NodeUniform extends Vector4Uniform {
  29863. constructor( nodeUniform ) {
  29864. super( nodeUniform.name, nodeUniform.value );
  29865. this.nodeUniform = nodeUniform;
  29866. }
  29867. getValue() {
  29868. return this.nodeUniform.value;
  29869. }
  29870. }
  29871. class ColorNodeUniform extends ColorUniform {
  29872. constructor( nodeUniform ) {
  29873. super( nodeUniform.name, nodeUniform.value );
  29874. this.nodeUniform = nodeUniform;
  29875. }
  29876. getValue() {
  29877. return this.nodeUniform.value;
  29878. }
  29879. }
  29880. class Matrix3NodeUniform extends Matrix3Uniform {
  29881. constructor( nodeUniform ) {
  29882. super( nodeUniform.name, nodeUniform.value );
  29883. this.nodeUniform = nodeUniform;
  29884. }
  29885. getValue() {
  29886. return this.nodeUniform.value;
  29887. }
  29888. }
  29889. class Matrix4NodeUniform extends Matrix4Uniform {
  29890. constructor( nodeUniform ) {
  29891. super( nodeUniform.name, nodeUniform.value );
  29892. this.nodeUniform = nodeUniform;
  29893. }
  29894. getValue() {
  29895. return this.nodeUniform.value;
  29896. }
  29897. }
  29898. class StackNode extends Node {
  29899. static get type() {
  29900. return 'StackNode';
  29901. }
  29902. constructor( parent = null ) {
  29903. super();
  29904. this.nodes = [];
  29905. this.outputNode = null;
  29906. this.parent = parent;
  29907. this._currentCond = null;
  29908. this.isStackNode = true;
  29909. }
  29910. getNodeType( builder ) {
  29911. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  29912. }
  29913. add( node ) {
  29914. this.nodes.push( node );
  29915. return this;
  29916. }
  29917. If( boolNode, method ) {
  29918. const methodNode = new ShaderNode( method );
  29919. this._currentCond = select( boolNode, methodNode );
  29920. return this.add( this._currentCond );
  29921. }
  29922. ElseIf( boolNode, method ) {
  29923. const methodNode = new ShaderNode( method );
  29924. const ifNode = select( boolNode, methodNode );
  29925. this._currentCond.elseNode = ifNode;
  29926. this._currentCond = ifNode;
  29927. return this;
  29928. }
  29929. Else( method ) {
  29930. this._currentCond.elseNode = new ShaderNode( method );
  29931. return this;
  29932. }
  29933. build( builder, ...params ) {
  29934. const previousStack = getCurrentStack();
  29935. setCurrentStack( this );
  29936. for ( const node of this.nodes ) {
  29937. node.build( builder, 'void' );
  29938. }
  29939. setCurrentStack( previousStack );
  29940. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  29941. }
  29942. //
  29943. else( ...params ) { // @deprecated, r168
  29944. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  29945. return this.Else( ...params );
  29946. }
  29947. elseif( ...params ) { // @deprecated, r168
  29948. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  29949. return this.ElseIf( ...params );
  29950. }
  29951. }
  29952. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  29953. const LOD_MIN = 4;
  29954. // The standard deviations (radians) associated with the extra mips. These are
  29955. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29956. // geometric shadowing function. These sigma values squared must match the
  29957. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29958. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29959. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29960. // samples and exit early, but not recompile the shader.
  29961. const MAX_SAMPLES = 20;
  29962. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29963. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  29964. const _clearColor$2 = /*@__PURE__*/ new Color();
  29965. let _oldTarget = null;
  29966. let _oldActiveCubeFace = 0;
  29967. let _oldActiveMipmapLevel = 0;
  29968. // Golden Ratio
  29969. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29970. const INV_PHI = 1 / PHI;
  29971. // Vertices of a dodecahedron (except the opposites, which represent the
  29972. // same axis), used as axis directions evenly spread on a sphere.
  29973. const _axisDirections = [
  29974. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  29975. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29976. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29977. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29978. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29979. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29980. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  29981. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  29982. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  29983. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  29984. ];
  29985. //
  29986. // WebGPU Face indices
  29987. const _faceLib = [
  29988. 3, 1, 5,
  29989. 0, 4, 2
  29990. ];
  29991. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  29992. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  29993. /**
  29994. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29995. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29996. * blur to be quickly accessed based on material roughness. It is packed into a
  29997. * special CubeUV format that allows us to perform custom interpolation so that
  29998. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29999. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  30000. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  30001. * higher roughness levels. In this way we maintain resolution to smoothly
  30002. * interpolate diffuse lighting while limiting sampling computation.
  30003. *
  30004. * Paper: Fast, Accurate Image-Based Lighting
  30005. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  30006. */
  30007. class PMREMGenerator {
  30008. constructor( renderer ) {
  30009. this._renderer = renderer;
  30010. this._pingPongRenderTarget = null;
  30011. this._lodMax = 0;
  30012. this._cubeSize = 0;
  30013. this._lodPlanes = [];
  30014. this._sizeLods = [];
  30015. this._sigmas = [];
  30016. this._lodMeshes = [];
  30017. this._blurMaterial = null;
  30018. this._cubemapMaterial = null;
  30019. this._equirectMaterial = null;
  30020. this._backgroundBox = null;
  30021. }
  30022. /**
  30023. * Generates a PMREM from a supplied Scene, which can be faster than using an
  30024. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  30025. * in radians to be applied to the scene before PMREM generation. Optional near
  30026. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  30027. * is placed at the origin).
  30028. */
  30029. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  30030. _oldTarget = this._renderer.getRenderTarget();
  30031. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30032. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30033. this._setSize( 256 );
  30034. const cubeUVRenderTarget = this._allocateTargets();
  30035. cubeUVRenderTarget.depthBuffer = true;
  30036. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  30037. if ( sigma > 0 ) {
  30038. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  30039. }
  30040. this._applyPMREM( cubeUVRenderTarget );
  30041. this._cleanup( cubeUVRenderTarget );
  30042. return cubeUVRenderTarget;
  30043. }
  30044. /**
  30045. * Generates a PMREM from an equirectangular texture, which can be either LDR
  30046. * or HDR. The ideal input image size is 1k (1024 x 512),
  30047. * as this matches best with the 256 x 256 cubemap output.
  30048. */
  30049. fromEquirectangular( equirectangular, renderTarget = null ) {
  30050. return this._fromTexture( equirectangular, renderTarget );
  30051. }
  30052. /**
  30053. * Generates a PMREM from an cubemap texture, which can be either LDR
  30054. * or HDR. The ideal input cube size is 256 x 256,
  30055. * as this matches best with the 256 x 256 cubemap output.
  30056. */
  30057. fromCubemap( cubemap, renderTarget = null ) {
  30058. return this._fromTexture( cubemap, renderTarget );
  30059. }
  30060. /**
  30061. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  30062. * your texture's network fetch for increased concurrency.
  30063. */
  30064. async compileCubemapShader() {
  30065. if ( this._cubemapMaterial === null ) {
  30066. this._cubemapMaterial = _getCubemapMaterial();
  30067. await this._compileMaterial( this._cubemapMaterial );
  30068. }
  30069. }
  30070. /**
  30071. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  30072. * your texture's network fetch for increased concurrency.
  30073. */
  30074. async compileEquirectangularShader() {
  30075. if ( this._equirectMaterial === null ) {
  30076. this._equirectMaterial = _getEquirectMaterial();
  30077. await this._compileMaterial( this._equirectMaterial );
  30078. }
  30079. }
  30080. /**
  30081. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  30082. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  30083. * one of them will cause any others to also become unusable.
  30084. */
  30085. dispose() {
  30086. this._dispose();
  30087. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  30088. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  30089. if ( this._backgroundBox !== null ) {
  30090. this._backgroundBox.geometry.dispose();
  30091. this._backgroundBox.material.dispose();
  30092. }
  30093. }
  30094. // private interface
  30095. _setSize( cubeSize ) {
  30096. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  30097. this._cubeSize = Math.pow( 2, this._lodMax );
  30098. }
  30099. _dispose() {
  30100. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  30101. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  30102. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  30103. this._lodPlanes[ i ].dispose();
  30104. }
  30105. }
  30106. _cleanup( outputTarget ) {
  30107. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  30108. outputTarget.scissorTest = false;
  30109. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  30110. }
  30111. _fromTexture( texture, renderTarget ) {
  30112. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  30113. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  30114. } else { // Equirectangular
  30115. this._setSize( texture.image.width / 4 );
  30116. }
  30117. _oldTarget = this._renderer.getRenderTarget();
  30118. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30119. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30120. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  30121. this._textureToCubeUV( texture, cubeUVRenderTarget );
  30122. this._applyPMREM( cubeUVRenderTarget );
  30123. this._cleanup( cubeUVRenderTarget );
  30124. return cubeUVRenderTarget;
  30125. }
  30126. _allocateTargets() {
  30127. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  30128. const height = 4 * this._cubeSize;
  30129. const params = {
  30130. magFilter: LinearFilter,
  30131. minFilter: LinearFilter,
  30132. generateMipmaps: false,
  30133. type: HalfFloatType,
  30134. format: RGBAFormat,
  30135. colorSpace: LinearSRGBColorSpace,
  30136. //depthBuffer: false
  30137. };
  30138. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  30139. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  30140. if ( this._pingPongRenderTarget !== null ) {
  30141. this._dispose();
  30142. }
  30143. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  30144. const { _lodMax } = this;
  30145. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  30146. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  30147. }
  30148. return cubeUVRenderTarget;
  30149. }
  30150. async _compileMaterial( material ) {
  30151. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  30152. await this._renderer.compile( tmpMesh, _flatCamera );
  30153. }
  30154. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  30155. const cubeCamera = _cubeCamera;
  30156. cubeCamera.near = near;
  30157. cubeCamera.far = far;
  30158. // px, py, pz, nx, ny, nz
  30159. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  30160. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  30161. const renderer = this._renderer;
  30162. const originalAutoClear = renderer.autoClear;
  30163. renderer.getClearColor( _clearColor$2 );
  30164. renderer.autoClear = false;
  30165. let backgroundBox = this._backgroundBox;
  30166. if ( backgroundBox === null ) {
  30167. const backgroundMaterial = new MeshBasicMaterial( {
  30168. name: 'PMREM.Background',
  30169. side: BackSide,
  30170. depthWrite: false,
  30171. depthTest: false
  30172. } );
  30173. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  30174. }
  30175. let useSolidColor = false;
  30176. const background = scene.background;
  30177. if ( background ) {
  30178. if ( background.isColor ) {
  30179. backgroundBox.material.color.copy( background );
  30180. scene.background = null;
  30181. useSolidColor = true;
  30182. }
  30183. } else {
  30184. backgroundBox.material.color.copy( _clearColor$2 );
  30185. useSolidColor = true;
  30186. }
  30187. renderer.setRenderTarget( cubeUVRenderTarget );
  30188. renderer.clear();
  30189. if ( useSolidColor ) {
  30190. renderer.render( backgroundBox, cubeCamera );
  30191. }
  30192. for ( let i = 0; i < 6; i ++ ) {
  30193. const col = i % 3;
  30194. if ( col === 0 ) {
  30195. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30196. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  30197. } else if ( col === 1 ) {
  30198. cubeCamera.up.set( 0, 0, upSign[ i ] );
  30199. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  30200. } else {
  30201. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30202. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  30203. }
  30204. const size = this._cubeSize;
  30205. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  30206. renderer.render( scene, cubeCamera );
  30207. }
  30208. renderer.autoClear = originalAutoClear;
  30209. scene.background = background;
  30210. }
  30211. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  30212. const renderer = this._renderer;
  30213. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  30214. if ( isCubeTexture ) {
  30215. if ( this._cubemapMaterial === null ) {
  30216. this._cubemapMaterial = _getCubemapMaterial( texture );
  30217. }
  30218. } else {
  30219. if ( this._equirectMaterial === null ) {
  30220. this._equirectMaterial = _getEquirectMaterial( texture );
  30221. }
  30222. }
  30223. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  30224. material.fragmentNode.value = texture;
  30225. const mesh = this._lodMeshes[ 0 ];
  30226. mesh.material = material;
  30227. const size = this._cubeSize;
  30228. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  30229. renderer.setRenderTarget( cubeUVRenderTarget );
  30230. renderer.render( mesh, _flatCamera );
  30231. }
  30232. _applyPMREM( cubeUVRenderTarget ) {
  30233. const renderer = this._renderer;
  30234. const autoClear = renderer.autoClear;
  30235. renderer.autoClear = false;
  30236. const n = this._lodPlanes.length;
  30237. for ( let i = 1; i < n; i ++ ) {
  30238. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  30239. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  30240. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  30241. }
  30242. renderer.autoClear = autoClear;
  30243. }
  30244. /**
  30245. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  30246. * vertically and horizontally, but this breaks down on a cube. Here we apply
  30247. * the blur latitudinally (around the poles), and then longitudinally (towards
  30248. * the poles) to approximate the orthogonally-separable blur. It is least
  30249. * accurate at the poles, but still does a decent job.
  30250. */
  30251. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  30252. const pingPongRenderTarget = this._pingPongRenderTarget;
  30253. this._halfBlur(
  30254. cubeUVRenderTarget,
  30255. pingPongRenderTarget,
  30256. lodIn,
  30257. lodOut,
  30258. sigma,
  30259. 'latitudinal',
  30260. poleAxis );
  30261. this._halfBlur(
  30262. pingPongRenderTarget,
  30263. cubeUVRenderTarget,
  30264. lodOut,
  30265. lodOut,
  30266. sigma,
  30267. 'longitudinal',
  30268. poleAxis );
  30269. }
  30270. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  30271. const renderer = this._renderer;
  30272. const blurMaterial = this._blurMaterial;
  30273. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  30274. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  30275. }
  30276. // Number of standard deviations at which to cut off the discrete approximation.
  30277. const STANDARD_DEVIATIONS = 3;
  30278. const blurMesh = this._lodMeshes[ lodOut ];
  30279. blurMesh.material = blurMaterial;
  30280. const blurUniforms = blurMaterial.uniforms;
  30281. const pixels = this._sizeLods[ lodIn ] - 1;
  30282. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  30283. const sigmaPixels = sigmaRadians / radiansPerPixel;
  30284. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  30285. if ( samples > MAX_SAMPLES ) {
  30286. console.warn( `sigmaRadians, ${
  30287. sigmaRadians}, is too large and will clip, as it requested ${
  30288. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  30289. }
  30290. const weights = [];
  30291. let sum = 0;
  30292. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  30293. const x = i / sigmaPixels;
  30294. const weight = Math.exp( - x * x / 2 );
  30295. weights.push( weight );
  30296. if ( i === 0 ) {
  30297. sum += weight;
  30298. } else if ( i < samples ) {
  30299. sum += 2 * weight;
  30300. }
  30301. }
  30302. for ( let i = 0; i < weights.length; i ++ ) {
  30303. weights[ i ] = weights[ i ] / sum;
  30304. }
  30305. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  30306. blurUniforms.envMap.value = targetIn.texture;
  30307. blurUniforms.samples.value = samples;
  30308. blurUniforms.weights.array = weights;
  30309. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  30310. if ( poleAxis ) {
  30311. blurUniforms.poleAxis.value = poleAxis;
  30312. }
  30313. const { _lodMax } = this;
  30314. blurUniforms.dTheta.value = radiansPerPixel;
  30315. blurUniforms.mipInt.value = _lodMax - lodIn;
  30316. const outputSize = this._sizeLods[ lodOut ];
  30317. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  30318. const y = 4 * ( this._cubeSize - outputSize );
  30319. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  30320. renderer.setRenderTarget( targetOut );
  30321. renderer.render( blurMesh, _flatCamera );
  30322. }
  30323. }
  30324. function _createPlanes( lodMax ) {
  30325. const lodPlanes = [];
  30326. const sizeLods = [];
  30327. const sigmas = [];
  30328. const lodMeshes = [];
  30329. let lod = lodMax;
  30330. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  30331. for ( let i = 0; i < totalLods; i ++ ) {
  30332. const sizeLod = Math.pow( 2, lod );
  30333. sizeLods.push( sizeLod );
  30334. let sigma = 1.0 / sizeLod;
  30335. if ( i > lodMax - LOD_MIN ) {
  30336. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  30337. } else if ( i === 0 ) {
  30338. sigma = 0;
  30339. }
  30340. sigmas.push( sigma );
  30341. const texelSize = 1.0 / ( sizeLod - 2 );
  30342. const min = - texelSize;
  30343. const max = 1 + texelSize;
  30344. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  30345. const cubeFaces = 6;
  30346. const vertices = 6;
  30347. const positionSize = 3;
  30348. const uvSize = 2;
  30349. const faceIndexSize = 1;
  30350. const position = new Float32Array( positionSize * vertices * cubeFaces );
  30351. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  30352. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  30353. for ( let face = 0; face < cubeFaces; face ++ ) {
  30354. const x = ( face % 3 ) * 2 / 3 - 1;
  30355. const y = face > 2 ? 0 : - 1;
  30356. const coordinates = [
  30357. x, y, 0,
  30358. x + 2 / 3, y, 0,
  30359. x + 2 / 3, y + 1, 0,
  30360. x, y, 0,
  30361. x + 2 / 3, y + 1, 0,
  30362. x, y + 1, 0
  30363. ];
  30364. const faceIdx = _faceLib[ face ];
  30365. position.set( coordinates, positionSize * vertices * faceIdx );
  30366. uv.set( uv1, uvSize * vertices * faceIdx );
  30367. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  30368. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  30369. }
  30370. const planes = new BufferGeometry();
  30371. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  30372. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  30373. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  30374. lodPlanes.push( planes );
  30375. lodMeshes.push( new Mesh( planes, null ) );
  30376. if ( lod > LOD_MIN ) {
  30377. lod --;
  30378. }
  30379. }
  30380. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  30381. }
  30382. function _createRenderTarget( width, height, params ) {
  30383. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  30384. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  30385. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  30386. cubeUVRenderTarget.texture.isPMREMTexture = true;
  30387. cubeUVRenderTarget.scissorTest = true;
  30388. return cubeUVRenderTarget;
  30389. }
  30390. function _setViewport( target, x, y, width, height ) {
  30391. target.viewport.set( x, y, width, height );
  30392. target.scissor.set( x, y, width, height );
  30393. }
  30394. function _getMaterial( type ) {
  30395. const material = new NodeMaterial();
  30396. material.depthTest = false;
  30397. material.depthWrite = false;
  30398. material.blending = NoBlending;
  30399. material.name = `PMREM_${ type }`;
  30400. return material;
  30401. }
  30402. function _getBlurShader( lodMax, width, height ) {
  30403. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  30404. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  30405. const dTheta = uniform( 0 );
  30406. const n = float( MAX_SAMPLES );
  30407. const latitudinal = uniform( 0 ); // false, bool
  30408. const samples = uniform( 1 ); // int
  30409. const envMap = texture( null );
  30410. const mipInt = uniform( 0 ); // int
  30411. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  30412. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  30413. const CUBEUV_MAX_MIP = float( lodMax );
  30414. const materialUniforms = {
  30415. n,
  30416. latitudinal,
  30417. weights,
  30418. poleAxis,
  30419. outputDirection,
  30420. dTheta,
  30421. samples,
  30422. envMap,
  30423. mipInt,
  30424. CUBEUV_TEXEL_WIDTH,
  30425. CUBEUV_TEXEL_HEIGHT,
  30426. CUBEUV_MAX_MIP
  30427. };
  30428. const material = _getMaterial( 'blur' );
  30429. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  30430. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  30431. return material;
  30432. }
  30433. function _getCubemapMaterial( envTexture ) {
  30434. const material = _getMaterial( 'cubemap' );
  30435. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  30436. return material;
  30437. }
  30438. function _getEquirectMaterial( envTexture ) {
  30439. const material = _getMaterial( 'equirect' );
  30440. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  30441. return material;
  30442. }
  30443. let _id$5 = 0;
  30444. class BindGroup {
  30445. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30446. this.name = name;
  30447. this.bindings = bindings;
  30448. this.index = index;
  30449. this.bindingsReference = bindingsReference;
  30450. this.id = _id$5 ++;
  30451. }
  30452. }
  30453. const rendererCache = new WeakMap();
  30454. const typeFromLength = new Map( [
  30455. [ 2, 'vec2' ],
  30456. [ 3, 'vec3' ],
  30457. [ 4, 'vec4' ],
  30458. [ 9, 'mat3' ],
  30459. [ 16, 'mat4' ]
  30460. ] );
  30461. const typeFromArray = new Map( [
  30462. [ Int8Array, 'int' ],
  30463. [ Int16Array, 'int' ],
  30464. [ Int32Array, 'int' ],
  30465. [ Uint8Array, 'uint' ],
  30466. [ Uint16Array, 'uint' ],
  30467. [ Uint32Array, 'uint' ],
  30468. [ Float32Array, 'float' ]
  30469. ] );
  30470. const toFloat = ( value ) => {
  30471. value = Number( value );
  30472. return value + ( value % 1 ? '' : '.0' );
  30473. };
  30474. class NodeBuilder {
  30475. constructor( object, renderer, parser ) {
  30476. this.object = object;
  30477. this.material = ( object && object.material ) || null;
  30478. this.geometry = ( object && object.geometry ) || null;
  30479. this.renderer = renderer;
  30480. this.parser = parser;
  30481. this.scene = null;
  30482. this.camera = null;
  30483. this.nodes = [];
  30484. this.updateNodes = [];
  30485. this.updateBeforeNodes = [];
  30486. this.updateAfterNodes = [];
  30487. this.hashNodes = {};
  30488. this.lightsNode = null;
  30489. this.environmentNode = null;
  30490. this.fogNode = null;
  30491. this.clippingContext = null;
  30492. this.vertexShader = null;
  30493. this.fragmentShader = null;
  30494. this.computeShader = null;
  30495. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30496. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30497. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30498. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30499. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30500. this.bindingsIndexes = {};
  30501. this.bindGroups = null;
  30502. this.attributes = [];
  30503. this.bufferAttributes = [];
  30504. this.varyings = [];
  30505. this.codes = {};
  30506. this.vars = {};
  30507. this.flow = { code: '' };
  30508. this.chaining = [];
  30509. this.stack = stack();
  30510. this.stacks = [];
  30511. this.tab = '\t';
  30512. this.instanceBindGroups = true;
  30513. this.currentFunctionNode = null;
  30514. this.context = {
  30515. material: this.material
  30516. };
  30517. this.cache = new NodeCache();
  30518. this.globalCache = this.cache;
  30519. this.flowsData = new WeakMap();
  30520. this.shaderStage = null;
  30521. this.buildStage = null;
  30522. this.useComparisonMethod = false;
  30523. }
  30524. getBindGroupsCache() {
  30525. let bindGroupsCache = rendererCache.get( this.renderer );
  30526. if ( bindGroupsCache === undefined ) {
  30527. bindGroupsCache = new ChainMap();
  30528. rendererCache.set( this.renderer, bindGroupsCache );
  30529. }
  30530. return bindGroupsCache;
  30531. }
  30532. createRenderTarget( width, height, options ) {
  30533. return new RenderTarget( width, height, options );
  30534. }
  30535. createCubeRenderTarget( size, options ) {
  30536. return new CubeRenderTarget( size, options );
  30537. }
  30538. createPMREMGenerator() {
  30539. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30540. return new PMREMGenerator( this.renderer );
  30541. }
  30542. includes( node ) {
  30543. return this.nodes.includes( node );
  30544. }
  30545. _getBindGroup( groupName, bindings ) {
  30546. const bindGroupsCache = this.getBindGroupsCache();
  30547. //
  30548. const bindingsArray = [];
  30549. let sharedGroup = true;
  30550. for ( const binding of bindings ) {
  30551. bindingsArray.push( binding );
  30552. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30553. }
  30554. //
  30555. let bindGroup;
  30556. if ( sharedGroup ) {
  30557. bindGroup = bindGroupsCache.get( bindingsArray );
  30558. if ( bindGroup === undefined ) {
  30559. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30560. bindGroupsCache.set( bindingsArray, bindGroup );
  30561. }
  30562. } else {
  30563. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30564. }
  30565. return bindGroup;
  30566. }
  30567. getBindGroupArray( groupName, shaderStage ) {
  30568. const bindings = this.bindings[ shaderStage ];
  30569. let bindGroup = bindings[ groupName ];
  30570. if ( bindGroup === undefined ) {
  30571. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  30572. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  30573. }
  30574. bindings[ groupName ] = bindGroup = [];
  30575. }
  30576. return bindGroup;
  30577. }
  30578. getBindings() {
  30579. let bindingsGroups = this.bindGroups;
  30580. if ( bindingsGroups === null ) {
  30581. const groups = {};
  30582. const bindings = this.bindings;
  30583. for ( const shaderStage of shaderStages ) {
  30584. for ( const groupName in bindings[ shaderStage ] ) {
  30585. const uniforms = bindings[ shaderStage ][ groupName ];
  30586. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  30587. groupUniforms.push( ...uniforms );
  30588. }
  30589. }
  30590. bindingsGroups = [];
  30591. for ( const groupName in groups ) {
  30592. const group = groups[ groupName ];
  30593. const bindingsGroup = this._getBindGroup( groupName, group );
  30594. bindingsGroups.push( bindingsGroup );
  30595. }
  30596. this.bindGroups = bindingsGroups;
  30597. }
  30598. return bindingsGroups;
  30599. }
  30600. sortBindingGroups() {
  30601. const bindingsGroups = this.getBindings();
  30602. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30603. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30604. const bindingGroup = bindingsGroups[ i ];
  30605. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30606. bindingGroup.index = i;
  30607. }
  30608. }
  30609. setHashNode( node, hash ) {
  30610. this.hashNodes[ hash ] = node;
  30611. }
  30612. addNode( node ) {
  30613. if ( this.nodes.includes( node ) === false ) {
  30614. this.nodes.push( node );
  30615. this.setHashNode( node, node.getHash( this ) );
  30616. }
  30617. }
  30618. buildUpdateNodes() {
  30619. for ( const node of this.nodes ) {
  30620. const updateType = node.getUpdateType();
  30621. const updateBeforeType = node.getUpdateBeforeType();
  30622. const updateAfterType = node.getUpdateAfterType();
  30623. if ( updateType !== NodeUpdateType.NONE ) {
  30624. this.updateNodes.push( node.getSelf() );
  30625. }
  30626. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30627. this.updateBeforeNodes.push( node );
  30628. }
  30629. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30630. this.updateAfterNodes.push( node );
  30631. }
  30632. }
  30633. }
  30634. get currentNode() {
  30635. return this.chaining[ this.chaining.length - 1 ];
  30636. }
  30637. isFilteredTexture( texture ) {
  30638. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30639. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30640. }
  30641. addChain( node ) {
  30642. /*
  30643. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30644. console.warn( 'Recursive node: ', node );
  30645. }
  30646. */
  30647. this.chaining.push( node );
  30648. }
  30649. removeChain( node ) {
  30650. const lastChain = this.chaining.pop();
  30651. if ( lastChain !== node ) {
  30652. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30653. }
  30654. }
  30655. getMethod( method ) {
  30656. return method;
  30657. }
  30658. getNodeFromHash( hash ) {
  30659. return this.hashNodes[ hash ];
  30660. }
  30661. addFlow( shaderStage, node ) {
  30662. this.flowNodes[ shaderStage ].push( node );
  30663. return node;
  30664. }
  30665. setContext( context ) {
  30666. this.context = context;
  30667. }
  30668. getContext() {
  30669. return this.context;
  30670. }
  30671. getSharedContext() {
  30672. ({ ...this.context });
  30673. return this.context;
  30674. }
  30675. setCache( cache ) {
  30676. this.cache = cache;
  30677. }
  30678. getCache() {
  30679. return this.cache;
  30680. }
  30681. getCacheFromNode( node, parent = true ) {
  30682. const data = this.getDataFromNode( node );
  30683. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30684. return data.cache;
  30685. }
  30686. isAvailable( /*name*/ ) {
  30687. return false;
  30688. }
  30689. getVertexIndex() {
  30690. console.warn( 'Abstract function.' );
  30691. }
  30692. getInstanceIndex() {
  30693. console.warn( 'Abstract function.' );
  30694. }
  30695. getDrawIndex() {
  30696. console.warn( 'Abstract function.' );
  30697. }
  30698. getFrontFacing() {
  30699. console.warn( 'Abstract function.' );
  30700. }
  30701. getFragCoord() {
  30702. console.warn( 'Abstract function.' );
  30703. }
  30704. isFlipY() {
  30705. return false;
  30706. }
  30707. increaseUsage( node ) {
  30708. const nodeData = this.getDataFromNode( node );
  30709. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30710. return nodeData.usageCount;
  30711. }
  30712. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30713. console.warn( 'Abstract function.' );
  30714. }
  30715. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  30716. console.warn( 'Abstract function.' );
  30717. }
  30718. generateConst( type, value = null ) {
  30719. if ( value === null ) {
  30720. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30721. else if ( type === 'bool' ) value = false;
  30722. else if ( type === 'color' ) value = new Color();
  30723. else if ( type === 'vec2' ) value = new Vector2();
  30724. else if ( type === 'vec3' ) value = new Vector3();
  30725. else if ( type === 'vec4' ) value = new Vector4();
  30726. }
  30727. if ( type === 'float' ) return toFloat( value );
  30728. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30729. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30730. if ( type === 'bool' ) return value ? 'true' : 'false';
  30731. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30732. const typeLength = this.getTypeLength( type );
  30733. const componentType = this.getComponentType( type );
  30734. const generateConst = value => this.generateConst( componentType, value );
  30735. if ( typeLength === 2 ) {
  30736. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30737. } else if ( typeLength === 3 ) {
  30738. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30739. } else if ( typeLength === 4 ) {
  30740. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30741. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30742. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30743. } else if ( typeLength > 4 ) {
  30744. return `${ this.getType( type ) }()`;
  30745. }
  30746. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30747. }
  30748. getType( type ) {
  30749. if ( type === 'color' ) return 'vec3';
  30750. return type;
  30751. }
  30752. hasGeometryAttribute( name ) {
  30753. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30754. }
  30755. getAttribute( name, type ) {
  30756. const attributes = this.attributes;
  30757. // find attribute
  30758. for ( const attribute of attributes ) {
  30759. if ( attribute.name === name ) {
  30760. return attribute;
  30761. }
  30762. }
  30763. // create a new if no exist
  30764. const attribute = new NodeAttribute( name, type );
  30765. attributes.push( attribute );
  30766. return attribute;
  30767. }
  30768. getPropertyName( node/*, shaderStage*/ ) {
  30769. return node.name;
  30770. }
  30771. isVector( type ) {
  30772. return /vec\d/.test( type );
  30773. }
  30774. isMatrix( type ) {
  30775. return /mat\d/.test( type );
  30776. }
  30777. isReference( type ) {
  30778. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30779. }
  30780. needsToWorkingColorSpace( /*texture*/ ) {
  30781. return false;
  30782. }
  30783. getComponentTypeFromTexture( texture ) {
  30784. const type = texture.type;
  30785. if ( texture.isDataTexture ) {
  30786. if ( type === IntType ) return 'int';
  30787. if ( type === UnsignedIntType ) return 'uint';
  30788. }
  30789. return 'float';
  30790. }
  30791. getElementType( type ) {
  30792. if ( type === 'mat2' ) return 'vec2';
  30793. if ( type === 'mat3' ) return 'vec3';
  30794. if ( type === 'mat4' ) return 'vec4';
  30795. return this.getComponentType( type );
  30796. }
  30797. getComponentType( type ) {
  30798. type = this.getVectorType( type );
  30799. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30800. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30801. if ( componentType === null ) return null;
  30802. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30803. if ( componentType[ 1 ] === 'i' ) return 'int';
  30804. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30805. return 'float';
  30806. }
  30807. getVectorType( type ) {
  30808. if ( type === 'color' ) return 'vec3';
  30809. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30810. return type;
  30811. }
  30812. getTypeFromLength( length, componentType = 'float' ) {
  30813. if ( length === 1 ) return componentType;
  30814. const baseType = typeFromLength.get( length );
  30815. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30816. return prefix + baseType;
  30817. }
  30818. getTypeFromArray( array ) {
  30819. return typeFromArray.get( array.constructor );
  30820. }
  30821. getTypeFromAttribute( attribute ) {
  30822. let dataAttribute = attribute;
  30823. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30824. const array = dataAttribute.array;
  30825. const itemSize = attribute.itemSize;
  30826. const normalized = attribute.normalized;
  30827. let arrayType;
  30828. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30829. arrayType = this.getTypeFromArray( array );
  30830. }
  30831. return this.getTypeFromLength( itemSize, arrayType );
  30832. }
  30833. getTypeLength( type ) {
  30834. const vecType = this.getVectorType( type );
  30835. const vecNum = /vec([2-4])/.exec( vecType );
  30836. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30837. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30838. if ( /mat2/.test( type ) === true ) return 4;
  30839. if ( /mat3/.test( type ) === true ) return 9;
  30840. if ( /mat4/.test( type ) === true ) return 16;
  30841. return 0;
  30842. }
  30843. getVectorFromMatrix( type ) {
  30844. return type.replace( 'mat', 'vec' );
  30845. }
  30846. changeComponentType( type, newComponentType ) {
  30847. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30848. }
  30849. getIntegerType( type ) {
  30850. const componentType = this.getComponentType( type );
  30851. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30852. return this.changeComponentType( type, 'int' );
  30853. }
  30854. addStack() {
  30855. this.stack = stack( this.stack );
  30856. this.stacks.push( getCurrentStack() || this.stack );
  30857. setCurrentStack( this.stack );
  30858. return this.stack;
  30859. }
  30860. removeStack() {
  30861. const lastStack = this.stack;
  30862. this.stack = lastStack.parent;
  30863. setCurrentStack( this.stacks.pop() );
  30864. return lastStack;
  30865. }
  30866. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30867. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30868. let nodeData = cache.getData( node );
  30869. if ( nodeData === undefined ) {
  30870. nodeData = {};
  30871. cache.setData( node, nodeData );
  30872. }
  30873. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30874. return nodeData[ shaderStage ];
  30875. }
  30876. getNodeProperties( node, shaderStage = 'any' ) {
  30877. const nodeData = this.getDataFromNode( node, shaderStage );
  30878. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30879. }
  30880. getBufferAttributeFromNode( node, type ) {
  30881. const nodeData = this.getDataFromNode( node );
  30882. let bufferAttribute = nodeData.bufferAttribute;
  30883. if ( bufferAttribute === undefined ) {
  30884. const index = this.uniforms.index ++;
  30885. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30886. this.bufferAttributes.push( bufferAttribute );
  30887. nodeData.bufferAttribute = bufferAttribute;
  30888. }
  30889. return bufferAttribute;
  30890. }
  30891. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  30892. const nodeData = this.getDataFromNode( node, shaderStage );
  30893. if ( nodeData.structType === undefined ) {
  30894. const index = this.structs.index ++;
  30895. node.name = `StructType${ index }`;
  30896. this.structs[ shaderStage ].push( node );
  30897. nodeData.structType = node;
  30898. }
  30899. return node;
  30900. }
  30901. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30902. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30903. let nodeUniform = nodeData.uniform;
  30904. if ( nodeUniform === undefined ) {
  30905. const index = this.uniforms.index ++;
  30906. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30907. this.uniforms[ shaderStage ].push( nodeUniform );
  30908. nodeData.uniform = nodeUniform;
  30909. }
  30910. return nodeUniform;
  30911. }
  30912. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  30913. const nodeData = this.getDataFromNode( node, shaderStage );
  30914. let nodeVar = nodeData.variable;
  30915. if ( nodeVar === undefined ) {
  30916. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30917. if ( name === null ) name = 'nodeVar' + vars.length;
  30918. nodeVar = new NodeVar( name, type );
  30919. vars.push( nodeVar );
  30920. nodeData.variable = nodeVar;
  30921. }
  30922. return nodeVar;
  30923. }
  30924. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30925. const nodeData = this.getDataFromNode( node, 'any' );
  30926. let nodeVarying = nodeData.varying;
  30927. if ( nodeVarying === undefined ) {
  30928. const varyings = this.varyings;
  30929. const index = varyings.length;
  30930. if ( name === null ) name = 'nodeVarying' + index;
  30931. nodeVarying = new NodeVarying( name, type );
  30932. varyings.push( nodeVarying );
  30933. nodeData.varying = nodeVarying;
  30934. }
  30935. return nodeVarying;
  30936. }
  30937. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30938. const nodeData = this.getDataFromNode( node );
  30939. let nodeCode = nodeData.code;
  30940. if ( nodeCode === undefined ) {
  30941. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30942. const index = codes.length;
  30943. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30944. codes.push( nodeCode );
  30945. nodeData.code = nodeCode;
  30946. }
  30947. return nodeCode;
  30948. }
  30949. addLineFlowCode( code ) {
  30950. if ( code === '' ) return this;
  30951. code = this.tab + code;
  30952. if ( ! /;\s*$/.test( code ) ) {
  30953. code = code + ';\n';
  30954. }
  30955. this.flow.code += code;
  30956. return this;
  30957. }
  30958. addFlowCode( code ) {
  30959. this.flow.code += code;
  30960. return this;
  30961. }
  30962. addFlowTab() {
  30963. this.tab += '\t';
  30964. return this;
  30965. }
  30966. removeFlowTab() {
  30967. this.tab = this.tab.slice( 0, - 1 );
  30968. return this;
  30969. }
  30970. getFlowData( node/*, shaderStage*/ ) {
  30971. return this.flowsData.get( node );
  30972. }
  30973. flowNode( node ) {
  30974. const output = node.getNodeType( this );
  30975. const flowData = this.flowChildNode( node, output );
  30976. this.flowsData.set( node, flowData );
  30977. return flowData;
  30978. }
  30979. buildFunctionNode( shaderNode ) {
  30980. const fn = new FunctionNode();
  30981. const previous = this.currentFunctionNode;
  30982. this.currentFunctionNode = fn;
  30983. fn.code = this.buildFunctionCode( shaderNode );
  30984. this.currentFunctionNode = previous;
  30985. return fn;
  30986. }
  30987. flowShaderNode( shaderNode ) {
  30988. const layout = shaderNode.layout;
  30989. const inputs = {
  30990. [ Symbol.iterator ]() {
  30991. let index = 0;
  30992. const values = Object.values( this );
  30993. return {
  30994. next: () => ( {
  30995. value: values[ index ],
  30996. done: index ++ >= values.length
  30997. } )
  30998. };
  30999. }
  31000. };
  31001. for ( const input of layout.inputs ) {
  31002. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31003. }
  31004. //
  31005. shaderNode.layout = null;
  31006. const callNode = shaderNode.call( inputs );
  31007. const flowData = this.flowStagesNode( callNode, layout.type );
  31008. shaderNode.layout = layout;
  31009. return flowData;
  31010. }
  31011. flowStagesNode( node, output = null ) {
  31012. const previousFlow = this.flow;
  31013. const previousVars = this.vars;
  31014. const previousCache = this.cache;
  31015. const previousBuildStage = this.buildStage;
  31016. const previousStack = this.stack;
  31017. const flow = {
  31018. code: ''
  31019. };
  31020. this.flow = flow;
  31021. this.vars = {};
  31022. this.cache = new NodeCache();
  31023. this.stack = stack();
  31024. for ( const buildStage of defaultBuildStages ) {
  31025. this.setBuildStage( buildStage );
  31026. flow.result = node.build( this, output );
  31027. }
  31028. flow.vars = this.getVars( this.shaderStage );
  31029. this.flow = previousFlow;
  31030. this.vars = previousVars;
  31031. this.cache = previousCache;
  31032. this.stack = previousStack;
  31033. this.setBuildStage( previousBuildStage );
  31034. return flow;
  31035. }
  31036. getFunctionOperator() {
  31037. return null;
  31038. }
  31039. flowChildNode( node, output = null ) {
  31040. const previousFlow = this.flow;
  31041. const flow = {
  31042. code: ''
  31043. };
  31044. this.flow = flow;
  31045. flow.result = node.build( this, output );
  31046. this.flow = previousFlow;
  31047. return flow;
  31048. }
  31049. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31050. const previousShaderStage = this.shaderStage;
  31051. this.setShaderStage( shaderStage );
  31052. const flowData = this.flowChildNode( node, output );
  31053. if ( propertyName !== null ) {
  31054. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31055. }
  31056. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31057. this.setShaderStage( previousShaderStage );
  31058. return flowData;
  31059. }
  31060. getAttributesArray() {
  31061. return this.attributes.concat( this.bufferAttributes );
  31062. }
  31063. getAttributes( /*shaderStage*/ ) {
  31064. console.warn( 'Abstract function.' );
  31065. }
  31066. getVaryings( /*shaderStage*/ ) {
  31067. console.warn( 'Abstract function.' );
  31068. }
  31069. getVar( type, name ) {
  31070. return `${ this.getType( type ) } ${ name }`;
  31071. }
  31072. getVars( shaderStage ) {
  31073. let snippet = '';
  31074. const vars = this.vars[ shaderStage ];
  31075. if ( vars !== undefined ) {
  31076. for ( const variable of vars ) {
  31077. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31078. }
  31079. }
  31080. return snippet;
  31081. }
  31082. getUniforms( /*shaderStage*/ ) {
  31083. console.warn( 'Abstract function.' );
  31084. }
  31085. getCodes( shaderStage ) {
  31086. const codes = this.codes[ shaderStage ];
  31087. let code = '';
  31088. if ( codes !== undefined ) {
  31089. for ( const nodeCode of codes ) {
  31090. code += nodeCode.code + '\n';
  31091. }
  31092. }
  31093. return code;
  31094. }
  31095. getHash() {
  31096. return this.vertexShader + this.fragmentShader + this.computeShader;
  31097. }
  31098. setShaderStage( shaderStage ) {
  31099. this.shaderStage = shaderStage;
  31100. }
  31101. getShaderStage() {
  31102. return this.shaderStage;
  31103. }
  31104. setBuildStage( buildStage ) {
  31105. this.buildStage = buildStage;
  31106. }
  31107. getBuildStage() {
  31108. return this.buildStage;
  31109. }
  31110. buildCode() {
  31111. console.warn( 'Abstract function.' );
  31112. }
  31113. build() {
  31114. const { object, material, renderer } = this;
  31115. if ( material !== null ) {
  31116. let nodeMaterial = renderer.nodes.library.fromMaterial( material );
  31117. if ( nodeMaterial === null ) {
  31118. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31119. nodeMaterial = new NodeMaterial();
  31120. }
  31121. nodeMaterial.build( this );
  31122. } else {
  31123. this.addFlow( 'compute', object );
  31124. }
  31125. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31126. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31127. // generate() -> stage 3: generate shader
  31128. for ( const buildStage of defaultBuildStages ) {
  31129. this.setBuildStage( buildStage );
  31130. if ( this.context.vertex && this.context.vertex.isNode ) {
  31131. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31132. }
  31133. for ( const shaderStage of shaderStages ) {
  31134. this.setShaderStage( shaderStage );
  31135. const flowNodes = this.flowNodes[ shaderStage ];
  31136. for ( const node of flowNodes ) {
  31137. if ( buildStage === 'generate' ) {
  31138. this.flowNode( node );
  31139. } else {
  31140. node.build( this );
  31141. }
  31142. }
  31143. }
  31144. }
  31145. this.setBuildStage( null );
  31146. this.setShaderStage( null );
  31147. // stage 4: build code for a specific output
  31148. this.buildCode();
  31149. this.buildUpdateNodes();
  31150. return this;
  31151. }
  31152. getNodeUniform( uniformNode, type ) {
  31153. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31154. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31155. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31156. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31157. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31158. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31159. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31160. throw new Error( `Uniform "${type}" not declared.` );
  31161. }
  31162. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31163. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31164. }
  31165. format( snippet, fromType, toType ) {
  31166. fromType = this.getVectorType( fromType );
  31167. toType = this.getVectorType( toType );
  31168. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31169. return snippet;
  31170. }
  31171. const fromTypeLength = this.getTypeLength( fromType );
  31172. const toTypeLength = this.getTypeLength( toType );
  31173. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31174. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31175. }
  31176. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31177. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31178. }
  31179. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31180. // @TODO: ignore for now
  31181. return snippet;
  31182. }
  31183. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31184. // @TODO: ignore for now
  31185. return snippet;
  31186. }
  31187. if ( fromTypeLength === toTypeLength ) {
  31188. return `${ this.getType( toType ) }( ${ snippet } )`;
  31189. }
  31190. if ( fromTypeLength > toTypeLength ) {
  31191. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31192. }
  31193. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31194. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31195. }
  31196. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31197. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31198. }
  31199. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31200. // convert a number value to vector type, e.g:
  31201. // vec3( 1u ) -> vec3( float( 1u ) )
  31202. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31203. }
  31204. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31205. }
  31206. getSignature() {
  31207. return `// Three.js r${ REVISION } - Node System\n`;
  31208. }
  31209. }
  31210. class NodeFrame {
  31211. constructor() {
  31212. this.time = 0;
  31213. this.deltaTime = 0;
  31214. this.frameId = 0;
  31215. this.renderId = 0;
  31216. this.startTime = null;
  31217. this.updateMap = new WeakMap();
  31218. this.updateBeforeMap = new WeakMap();
  31219. this.updateAfterMap = new WeakMap();
  31220. this.renderer = null;
  31221. this.material = null;
  31222. this.camera = null;
  31223. this.object = null;
  31224. this.scene = null;
  31225. }
  31226. _getMaps( referenceMap, nodeRef ) {
  31227. let maps = referenceMap.get( nodeRef );
  31228. if ( maps === undefined ) {
  31229. maps = {
  31230. renderMap: new WeakMap(),
  31231. frameMap: new WeakMap()
  31232. };
  31233. referenceMap.set( nodeRef, maps );
  31234. }
  31235. return maps;
  31236. }
  31237. updateBeforeNode( node ) {
  31238. const updateType = node.getUpdateBeforeType();
  31239. const reference = node.updateReference( this );
  31240. if ( updateType === NodeUpdateType.FRAME ) {
  31241. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31242. if ( frameMap.get( reference ) !== this.frameId ) {
  31243. if ( node.updateBefore( this ) !== false ) {
  31244. frameMap.set( reference, this.frameId );
  31245. }
  31246. }
  31247. } else if ( updateType === NodeUpdateType.RENDER ) {
  31248. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31249. if ( renderMap.get( reference ) !== this.renderId ) {
  31250. if ( node.updateBefore( this ) !== false ) {
  31251. renderMap.set( reference, this.renderId );
  31252. }
  31253. }
  31254. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31255. node.updateBefore( this );
  31256. }
  31257. }
  31258. updateAfterNode( node ) {
  31259. const updateType = node.getUpdateAfterType();
  31260. const reference = node.updateReference( this );
  31261. if ( updateType === NodeUpdateType.FRAME ) {
  31262. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31263. if ( frameMap.get( reference ) !== this.frameId ) {
  31264. if ( node.updateAfter( this ) !== false ) {
  31265. frameMap.set( reference, this.frameId );
  31266. }
  31267. }
  31268. } else if ( updateType === NodeUpdateType.RENDER ) {
  31269. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31270. if ( renderMap.get( reference ) !== this.renderId ) {
  31271. if ( node.updateAfter( this ) !== false ) {
  31272. renderMap.set( reference, this.renderId );
  31273. }
  31274. }
  31275. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31276. node.updateAfter( this );
  31277. }
  31278. }
  31279. updateNode( node ) {
  31280. const updateType = node.getUpdateType();
  31281. const reference = node.updateReference( this );
  31282. if ( updateType === NodeUpdateType.FRAME ) {
  31283. const { frameMap } = this._getMaps( this.updateMap, reference );
  31284. if ( frameMap.get( reference ) !== this.frameId ) {
  31285. if ( node.update( this ) !== false ) {
  31286. frameMap.set( reference, this.frameId );
  31287. }
  31288. }
  31289. } else if ( updateType === NodeUpdateType.RENDER ) {
  31290. const { renderMap } = this._getMaps( this.updateMap, reference );
  31291. if ( renderMap.get( reference ) !== this.renderId ) {
  31292. if ( node.update( this ) !== false ) {
  31293. renderMap.set( reference, this.renderId );
  31294. }
  31295. }
  31296. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31297. node.update( this );
  31298. }
  31299. }
  31300. update() {
  31301. this.frameId ++;
  31302. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31303. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31304. this.lastTime = performance.now();
  31305. this.time += this.deltaTime;
  31306. }
  31307. }
  31308. class NodeFunctionInput {
  31309. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31310. this.type = type;
  31311. this.name = name;
  31312. this.count = count;
  31313. this.qualifier = qualifier;
  31314. this.isConst = isConst;
  31315. }
  31316. }
  31317. NodeFunctionInput.isNodeFunctionInput = true;
  31318. class StructTypeNode extends Node {
  31319. static get type() {
  31320. return 'StructTypeNode';
  31321. }
  31322. constructor( types ) {
  31323. super();
  31324. this.types = types;
  31325. this.isStructTypeNode = true;
  31326. }
  31327. getMemberTypes() {
  31328. return this.types;
  31329. }
  31330. }
  31331. class OutputStructNode extends Node {
  31332. static get type() {
  31333. return 'OutputStructNode';
  31334. }
  31335. constructor( ...members ) {
  31336. super();
  31337. this.members = members;
  31338. this.isOutputStructNode = true;
  31339. }
  31340. setup( builder ) {
  31341. super.setup( builder );
  31342. const members = this.members;
  31343. const types = [];
  31344. for ( let i = 0; i < members.length; i ++ ) {
  31345. types.push( members[ i ].getNodeType( builder ) );
  31346. }
  31347. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  31348. }
  31349. generate( builder, output ) {
  31350. const propertyName = builder.getOutputStructName();
  31351. const members = this.members;
  31352. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  31353. for ( let i = 0; i < members.length; i ++ ) {
  31354. const snippet = members[ i ].build( builder, output );
  31355. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  31356. }
  31357. return propertyName;
  31358. }
  31359. }
  31360. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  31361. function getTextureIndex( textures, name ) {
  31362. for ( let i = 0; i < textures.length; i ++ ) {
  31363. if ( textures[ i ].name === name ) {
  31364. return i;
  31365. }
  31366. }
  31367. return - 1;
  31368. }
  31369. class MRTNode extends OutputStructNode {
  31370. static get type() {
  31371. return 'MRTNode';
  31372. }
  31373. constructor( outputNodes ) {
  31374. super();
  31375. this.outputNodes = outputNodes;
  31376. this.isMRTNode = true;
  31377. }
  31378. has( name ) {
  31379. return this.outputNodes[ name ] !== undefined;
  31380. }
  31381. get( name ) {
  31382. return this.outputNodes[ name ];
  31383. }
  31384. merge( mrtNode ) {
  31385. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  31386. return mrt( outputs );
  31387. }
  31388. setup( builder ) {
  31389. const outputNodes = this.outputNodes;
  31390. const mrt = builder.renderer.getRenderTarget();
  31391. const members = [];
  31392. const textures = mrt.textures;
  31393. for ( const name in outputNodes ) {
  31394. const index = getTextureIndex( textures, name );
  31395. members[ index ] = vec4( outputNodes[ name ] );
  31396. }
  31397. this.members = members;
  31398. return super.setup( builder );
  31399. }
  31400. }
  31401. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  31402. class FunctionOverloadingNode extends Node {
  31403. static get type() {
  31404. return 'FunctionOverloadingNode';
  31405. }
  31406. constructor( functionNodes = [], ...parametersNodes ) {
  31407. super();
  31408. this.functionNodes = functionNodes;
  31409. this.parametersNodes = parametersNodes;
  31410. this._candidateFnCall = null;
  31411. this.global = true;
  31412. }
  31413. getNodeType() {
  31414. return this.functionNodes[ 0 ].shaderNode.layout.type;
  31415. }
  31416. setup( builder ) {
  31417. const params = this.parametersNodes;
  31418. let candidateFnCall = this._candidateFnCall;
  31419. if ( candidateFnCall === null ) {
  31420. let candidateFn = null;
  31421. let candidateScore = - 1;
  31422. for ( const functionNode of this.functionNodes ) {
  31423. const shaderNode = functionNode.shaderNode;
  31424. const layout = shaderNode.layout;
  31425. if ( layout === null ) {
  31426. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  31427. }
  31428. const inputs = layout.inputs;
  31429. if ( params.length === inputs.length ) {
  31430. let score = 0;
  31431. for ( let i = 0; i < params.length; i ++ ) {
  31432. const param = params[ i ];
  31433. const input = inputs[ i ];
  31434. if ( param.getNodeType( builder ) === input.type ) {
  31435. score ++;
  31436. } else {
  31437. score = 0;
  31438. }
  31439. }
  31440. if ( score > candidateScore ) {
  31441. candidateFn = functionNode;
  31442. candidateScore = score;
  31443. }
  31444. }
  31445. }
  31446. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  31447. }
  31448. return candidateFnCall;
  31449. }
  31450. }
  31451. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  31452. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  31453. class TimerNode extends UniformNode {
  31454. static get type() {
  31455. return 'TimerNode';
  31456. }
  31457. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  31458. super( value );
  31459. this.scope = scope;
  31460. this.scale = scale;
  31461. this.updateType = NodeUpdateType.FRAME;
  31462. }
  31463. /*
  31464. @TODO:
  31465. getNodeType( builder ) {
  31466. const scope = this.scope;
  31467. if ( scope === TimerNode.FRAME ) {
  31468. return 'uint';
  31469. }
  31470. return 'float';
  31471. }
  31472. */
  31473. update( frame ) {
  31474. const scope = this.scope;
  31475. const scale = this.scale;
  31476. if ( scope === TimerNode.LOCAL ) {
  31477. this.value += frame.deltaTime * scale;
  31478. } else if ( scope === TimerNode.DELTA ) {
  31479. this.value = frame.deltaTime * scale;
  31480. } else if ( scope === TimerNode.FRAME ) {
  31481. this.value = frame.frameId;
  31482. } else {
  31483. // global
  31484. this.value = frame.time * scale;
  31485. }
  31486. }
  31487. serialize( data ) {
  31488. super.serialize( data );
  31489. data.scope = this.scope;
  31490. data.scale = this.scale;
  31491. }
  31492. deserialize( data ) {
  31493. super.deserialize( data );
  31494. this.scope = data.scope;
  31495. this.scale = data.scale;
  31496. }
  31497. }
  31498. TimerNode.LOCAL = 'local';
  31499. TimerNode.GLOBAL = 'global';
  31500. TimerNode.DELTA = 'delta';
  31501. TimerNode.FRAME = 'frame';
  31502. // @TODO: add support to use node in timeScale
  31503. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  31504. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  31505. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  31506. const frameId = /*@__PURE__*/ nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  31507. class OscNode extends Node {
  31508. static get type() {
  31509. return 'OscNode';
  31510. }
  31511. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  31512. super();
  31513. this.method = method;
  31514. this.timeNode = timeNode;
  31515. }
  31516. getNodeType( builder ) {
  31517. return this.timeNode.getNodeType( builder );
  31518. }
  31519. setup() {
  31520. const method = this.method;
  31521. const timeNode = nodeObject( this.timeNode );
  31522. let outputNode = null;
  31523. if ( method === OscNode.SINE ) {
  31524. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  31525. } else if ( method === OscNode.SQUARE ) {
  31526. outputNode = timeNode.fract().round();
  31527. } else if ( method === OscNode.TRIANGLE ) {
  31528. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  31529. } else if ( method === OscNode.SAWTOOTH ) {
  31530. outputNode = timeNode.fract();
  31531. }
  31532. return outputNode;
  31533. }
  31534. serialize( data ) {
  31535. super.serialize( data );
  31536. data.method = this.method;
  31537. }
  31538. deserialize( data ) {
  31539. super.deserialize( data );
  31540. this.method = data.method;
  31541. }
  31542. }
  31543. OscNode.SINE = 'sine';
  31544. OscNode.SQUARE = 'square';
  31545. OscNode.TRIANGLE = 'triangle';
  31546. OscNode.SAWTOOTH = 'sawtooth';
  31547. const oscSine = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SINE );
  31548. const oscSquare = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SQUARE );
  31549. const oscTriangle = /*@__PURE__*/ nodeProxy( OscNode, OscNode.TRIANGLE );
  31550. const oscSawtooth = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SAWTOOTH );
  31551. class SpriteSheetUVNode extends Node {
  31552. static get type() {
  31553. return 'SpriteSheetUVNode';
  31554. }
  31555. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  31556. super( 'vec2' );
  31557. this.countNode = countNode;
  31558. this.uvNode = uvNode;
  31559. this.frameNode = frameNode;
  31560. }
  31561. setup() {
  31562. const { frameNode, uvNode, countNode } = this;
  31563. const { width, height } = countNode;
  31564. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  31565. const column = frameNum.mod( width );
  31566. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  31567. const scale = countNode.reciprocal();
  31568. const uvFrameOffset = vec2( column, row );
  31569. return uvNode.add( uvFrameOffset ).mul( scale );
  31570. }
  31571. }
  31572. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  31573. class StorageArrayElementNode extends ArrayElementNode {
  31574. static get type() {
  31575. return 'StorageArrayElementNode';
  31576. }
  31577. constructor( storageBufferNode, indexNode ) {
  31578. super( storageBufferNode, indexNode );
  31579. this.isStorageArrayElementNode = true;
  31580. }
  31581. set storageBufferNode( value ) {
  31582. this.node = value;
  31583. }
  31584. get storageBufferNode() {
  31585. return this.node;
  31586. }
  31587. setup( builder ) {
  31588. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31589. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  31590. builder.setupPBO( this.node );
  31591. }
  31592. }
  31593. return super.setup( builder );
  31594. }
  31595. generate( builder, output ) {
  31596. let snippet;
  31597. const isAssignContext = builder.context.assign;
  31598. //
  31599. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31600. const { node } = this;
  31601. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  31602. snippet = builder.generatePBO( this );
  31603. } else {
  31604. snippet = node.build( builder );
  31605. }
  31606. } else {
  31607. snippet = super.generate( builder );
  31608. }
  31609. if ( isAssignContext !== true ) {
  31610. const type = this.getNodeType( builder );
  31611. snippet = builder.format( snippet, type, output );
  31612. }
  31613. return snippet;
  31614. }
  31615. }
  31616. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  31617. class TriplanarTexturesNode extends Node {
  31618. static get type() {
  31619. return 'TriplanarTexturesNode';
  31620. }
  31621. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  31622. super( 'vec4' );
  31623. this.textureXNode = textureXNode;
  31624. this.textureYNode = textureYNode;
  31625. this.textureZNode = textureZNode;
  31626. this.scaleNode = scaleNode;
  31627. this.positionNode = positionNode;
  31628. this.normalNode = normalNode;
  31629. }
  31630. setup() {
  31631. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  31632. // Ref: https://github.com/keijiro/StandardTriplanar
  31633. // Blending factor of triplanar mapping
  31634. let bf = normalNode.abs().normalize();
  31635. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  31636. // Triplanar mapping
  31637. const tx = positionNode.yz.mul( scaleNode );
  31638. const ty = positionNode.zx.mul( scaleNode );
  31639. const tz = positionNode.xy.mul( scaleNode );
  31640. // Base color
  31641. const textureX = textureXNode.value;
  31642. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  31643. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  31644. const cx = texture( textureX, tx ).mul( bf.x );
  31645. const cy = texture( textureY, ty ).mul( bf.y );
  31646. const cz = texture( textureZ, tz ).mul( bf.z );
  31647. return add( cx, cy, cz );
  31648. }
  31649. }
  31650. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  31651. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  31652. const _reflectorPlane = new Plane();
  31653. const _normal = new Vector3();
  31654. const _reflectorWorldPosition = new Vector3();
  31655. const _cameraWorldPosition = new Vector3();
  31656. const _rotationMatrix = new Matrix4();
  31657. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  31658. const clipPlane = new Vector4();
  31659. const _view = new Vector3();
  31660. const _target = new Vector3();
  31661. const _q = new Vector4();
  31662. const _size$9 = new Vector2();
  31663. const _defaultRT = new RenderTarget();
  31664. const _defaultUV = viewportUV.flipX();
  31665. let _inReflector = false;
  31666. class ReflectorNode extends TextureNode {
  31667. static get type() {
  31668. return 'ReflectorNode';
  31669. }
  31670. constructor( parameters = {} ) {
  31671. super( _defaultRT.texture, _defaultUV );
  31672. const {
  31673. target = new Object3D(),
  31674. resolution = 1,
  31675. generateMipmaps = false,
  31676. bounces = true
  31677. } = parameters;
  31678. //
  31679. this.target = target;
  31680. this.resolution = resolution;
  31681. this.generateMipmaps = generateMipmaps;
  31682. this.bounces = bounces;
  31683. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  31684. this.virtualCameras = new WeakMap();
  31685. this.renderTargets = new WeakMap();
  31686. }
  31687. _updateResolution( renderTarget, renderer ) {
  31688. const resolution = this.resolution;
  31689. renderer.getDrawingBufferSize( _size$9 );
  31690. renderTarget.setSize( Math.round( _size$9.width * resolution ), Math.round( _size$9.height * resolution ) );
  31691. }
  31692. setup( builder ) {
  31693. this._updateResolution( _defaultRT, builder.renderer );
  31694. return super.setup( builder );
  31695. }
  31696. getTextureNode() {
  31697. return this.textureNode;
  31698. }
  31699. getVirtualCamera( camera ) {
  31700. let virtualCamera = this.virtualCameras.get( camera );
  31701. if ( virtualCamera === undefined ) {
  31702. virtualCamera = camera.clone();
  31703. this.virtualCameras.set( camera, virtualCamera );
  31704. }
  31705. return virtualCamera;
  31706. }
  31707. getRenderTarget( camera ) {
  31708. let renderTarget = this.renderTargets.get( camera );
  31709. if ( renderTarget === undefined ) {
  31710. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  31711. if ( this.generateMipmaps === true ) {
  31712. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  31713. renderTarget.texture.generateMipmaps = true;
  31714. }
  31715. this.renderTargets.set( camera, renderTarget );
  31716. }
  31717. return renderTarget;
  31718. }
  31719. updateBefore( frame ) {
  31720. if ( this.bounces === false && _inReflector ) return false;
  31721. _inReflector = true;
  31722. const { scene, camera, renderer, material } = frame;
  31723. const { target } = this;
  31724. const virtualCamera = this.getVirtualCamera( camera );
  31725. const renderTarget = this.getRenderTarget( virtualCamera );
  31726. renderer.getDrawingBufferSize( _size$9 );
  31727. this._updateResolution( renderTarget, renderer );
  31728. //
  31729. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  31730. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  31731. _rotationMatrix.extractRotation( target.matrixWorld );
  31732. _normal.set( 0, 0, 1 );
  31733. _normal.applyMatrix4( _rotationMatrix );
  31734. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  31735. // Avoid rendering when reflector is facing away
  31736. if ( _view.dot( _normal ) > 0 ) return;
  31737. _view.reflect( _normal ).negate();
  31738. _view.add( _reflectorWorldPosition );
  31739. _rotationMatrix.extractRotation( camera.matrixWorld );
  31740. _lookAtPosition.set( 0, 0, - 1 );
  31741. _lookAtPosition.applyMatrix4( _rotationMatrix );
  31742. _lookAtPosition.add( _cameraWorldPosition );
  31743. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  31744. _target.reflect( _normal ).negate();
  31745. _target.add( _reflectorWorldPosition );
  31746. //
  31747. virtualCamera.coordinateSystem = camera.coordinateSystem;
  31748. virtualCamera.position.copy( _view );
  31749. virtualCamera.up.set( 0, 1, 0 );
  31750. virtualCamera.up.applyMatrix4( _rotationMatrix );
  31751. virtualCamera.up.reflect( _normal );
  31752. virtualCamera.lookAt( _target );
  31753. virtualCamera.near = camera.near;
  31754. virtualCamera.far = camera.far;
  31755. virtualCamera.updateMatrixWorld();
  31756. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  31757. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  31758. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  31759. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  31760. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  31761. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  31762. const projectionMatrix = virtualCamera.projectionMatrix;
  31763. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  31764. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  31765. _q.z = - 1.0;
  31766. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  31767. // Calculate the scaled plane vector
  31768. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  31769. const clipBias = 0;
  31770. // Replacing the third row of the projection matrix
  31771. projectionMatrix.elements[ 2 ] = clipPlane.x;
  31772. projectionMatrix.elements[ 6 ] = clipPlane.y;
  31773. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  31774. projectionMatrix.elements[ 14 ] = clipPlane.w;
  31775. //
  31776. this.value = renderTarget.texture;
  31777. material.visible = false;
  31778. const currentRenderTarget = renderer.getRenderTarget();
  31779. const currentMRT = renderer.getMRT();
  31780. renderer.setMRT( null );
  31781. renderer.setRenderTarget( renderTarget );
  31782. renderer.render( scene, virtualCamera );
  31783. renderer.setMRT( currentMRT );
  31784. renderer.setRenderTarget( currentRenderTarget );
  31785. material.visible = true;
  31786. _inReflector = false;
  31787. }
  31788. }
  31789. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  31790. // Helper for passes that need to fill the viewport with a single quad.
  31791. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  31792. // https://github.com/mrdoob/three.js/pull/21358
  31793. class QuadGeometry extends BufferGeometry {
  31794. constructor( flipY = false ) {
  31795. super();
  31796. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  31797. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  31798. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  31799. }
  31800. }
  31801. const _geometry = /*@__PURE__*/ new QuadGeometry();
  31802. class QuadMesh extends Mesh {
  31803. constructor( material = null ) {
  31804. super( _geometry, material );
  31805. this.camera = _camera;
  31806. this.isQuadMesh = true;
  31807. }
  31808. renderAsync( renderer ) {
  31809. return renderer.renderAsync( this, _camera );
  31810. }
  31811. render( renderer ) {
  31812. renderer.render( this, _camera );
  31813. }
  31814. }
  31815. const _size$8 = /*@__PURE__*/ new Vector2();
  31816. class RTTNode extends TextureNode {
  31817. static get type() {
  31818. return 'RTTNode';
  31819. }
  31820. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  31821. const renderTarget = new RenderTarget( width, height, options );
  31822. super( renderTarget.texture, uv() );
  31823. this.node = node;
  31824. this.width = width;
  31825. this.height = height;
  31826. this.renderTarget = renderTarget;
  31827. this.textureNeedsUpdate = true;
  31828. this.autoUpdate = true;
  31829. this.updateMap = new WeakMap();
  31830. this._rttNode = null;
  31831. this._quadMesh = new QuadMesh( new NodeMaterial() );
  31832. this.updateBeforeType = NodeUpdateType.RENDER;
  31833. }
  31834. get autoSize() {
  31835. return this.width === null;
  31836. }
  31837. setup( builder ) {
  31838. this._rttNode = this.node.context( builder.getSharedContext() );
  31839. this._quadMesh.material.name = 'RTT';
  31840. this._quadMesh.material.needsUpdate = true;
  31841. return super.setup( builder );
  31842. }
  31843. setSize( width, height ) {
  31844. this.width = width;
  31845. this.height = height;
  31846. const effectiveWidth = width * this.pixelRatio;
  31847. const effectiveHeight = height * this.pixelRatio;
  31848. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  31849. this.textureNeedsUpdate = true;
  31850. }
  31851. setPixelRatio( pixelRatio ) {
  31852. this.pixelRatio = pixelRatio;
  31853. this.setSize( this.width, this.height );
  31854. }
  31855. updateBefore( { renderer } ) {
  31856. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  31857. this.textureNeedsUpdate = false;
  31858. //
  31859. if ( this.autoSize === true ) {
  31860. this.pixelRatio = renderer.getPixelRatio();
  31861. const size = renderer.getSize( _size$8 );
  31862. this.setSize( size.width, size.height );
  31863. }
  31864. //
  31865. this._quadMesh.material.fragmentNode = this._rttNode;
  31866. //
  31867. const currentRenderTarget = renderer.getRenderTarget();
  31868. renderer.setRenderTarget( this.renderTarget );
  31869. this._quadMesh.render( renderer );
  31870. renderer.setRenderTarget( currentRenderTarget );
  31871. }
  31872. clone() {
  31873. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  31874. newNode.sampler = this.sampler;
  31875. newNode.referenceNode = this;
  31876. return newNode;
  31877. }
  31878. }
  31879. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  31880. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  31881. class VertexColorNode extends AttributeNode {
  31882. static get type() {
  31883. return 'VertexColorNode';
  31884. }
  31885. constructor( index = 0 ) {
  31886. super( null, 'vec4' );
  31887. this.isVertexColorNode = true;
  31888. this.index = index;
  31889. }
  31890. getAttributeName( /*builder*/ ) {
  31891. const index = this.index;
  31892. return 'color' + ( index > 0 ? index : '' );
  31893. }
  31894. generate( builder ) {
  31895. const attributeName = this.getAttributeName( builder );
  31896. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  31897. let result;
  31898. if ( geometryAttribute === true ) {
  31899. result = super.generate( builder );
  31900. } else {
  31901. // Vertex color fallback should be white
  31902. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  31903. }
  31904. return result;
  31905. }
  31906. serialize( data ) {
  31907. super.serialize( data );
  31908. data.index = this.index;
  31909. }
  31910. deserialize( data ) {
  31911. super.deserialize( data );
  31912. this.index = data.index;
  31913. }
  31914. }
  31915. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  31916. class PointUVNode extends Node {
  31917. static get type() {
  31918. return 'PointUVNode';
  31919. }
  31920. constructor() {
  31921. super( 'vec2' );
  31922. this.isPointUVNode = true;
  31923. }
  31924. generate( /*builder*/ ) {
  31925. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  31926. }
  31927. }
  31928. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  31929. class SceneNode extends Node {
  31930. static get type() {
  31931. return 'SceneNode';
  31932. }
  31933. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  31934. super();
  31935. this.scope = scope;
  31936. this.scene = scene;
  31937. }
  31938. setup( builder ) {
  31939. const scope = this.scope;
  31940. const scene = this.scene !== null ? this.scene : builder.scene;
  31941. let output;
  31942. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  31943. output = reference( 'backgroundBlurriness', 'float', scene );
  31944. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  31945. output = reference( 'backgroundIntensity', 'float', scene );
  31946. } else {
  31947. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  31948. }
  31949. return output;
  31950. }
  31951. }
  31952. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  31953. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  31954. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  31955. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  31956. const GPUPrimitiveTopology = {
  31957. PointList: 'point-list',
  31958. LineList: 'line-list',
  31959. LineStrip: 'line-strip',
  31960. TriangleList: 'triangle-list',
  31961. TriangleStrip: 'triangle-strip',
  31962. };
  31963. const GPUCompareFunction = {
  31964. Never: 'never',
  31965. Less: 'less',
  31966. Equal: 'equal',
  31967. LessEqual: 'less-equal',
  31968. Greater: 'greater',
  31969. NotEqual: 'not-equal',
  31970. GreaterEqual: 'greater-equal',
  31971. Always: 'always'
  31972. };
  31973. const GPUStoreOp = {
  31974. Store: 'store',
  31975. Discard: 'discard'
  31976. };
  31977. const GPULoadOp = {
  31978. Load: 'load',
  31979. Clear: 'clear'
  31980. };
  31981. const GPUFrontFace = {
  31982. CCW: 'ccw',
  31983. CW: 'cw'
  31984. };
  31985. const GPUCullMode = {
  31986. None: 'none',
  31987. Front: 'front',
  31988. Back: 'back'
  31989. };
  31990. const GPUIndexFormat = {
  31991. Uint16: 'uint16',
  31992. Uint32: 'uint32'
  31993. };
  31994. const GPUTextureFormat = {
  31995. // 8-bit formats
  31996. R8Unorm: 'r8unorm',
  31997. R8Snorm: 'r8snorm',
  31998. R8Uint: 'r8uint',
  31999. R8Sint: 'r8sint',
  32000. // 16-bit formats
  32001. R16Uint: 'r16uint',
  32002. R16Sint: 'r16sint',
  32003. R16Float: 'r16float',
  32004. RG8Unorm: 'rg8unorm',
  32005. RG8Snorm: 'rg8snorm',
  32006. RG8Uint: 'rg8uint',
  32007. RG8Sint: 'rg8sint',
  32008. // 32-bit formats
  32009. R32Uint: 'r32uint',
  32010. R32Sint: 'r32sint',
  32011. R32Float: 'r32float',
  32012. RG16Uint: 'rg16uint',
  32013. RG16Sint: 'rg16sint',
  32014. RG16Float: 'rg16float',
  32015. RGBA8Unorm: 'rgba8unorm',
  32016. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  32017. RGBA8Snorm: 'rgba8snorm',
  32018. RGBA8Uint: 'rgba8uint',
  32019. RGBA8Sint: 'rgba8sint',
  32020. BGRA8Unorm: 'bgra8unorm',
  32021. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  32022. // Packed 32-bit formats
  32023. RGB9E5UFloat: 'rgb9e5ufloat',
  32024. RGB10A2Unorm: 'rgb10a2unorm',
  32025. RG11B10uFloat: 'rgb10a2unorm',
  32026. // 64-bit formats
  32027. RG32Uint: 'rg32uint',
  32028. RG32Sint: 'rg32sint',
  32029. RG32Float: 'rg32float',
  32030. RGBA16Uint: 'rgba16uint',
  32031. RGBA16Sint: 'rgba16sint',
  32032. RGBA16Float: 'rgba16float',
  32033. // 128-bit formats
  32034. RGBA32Uint: 'rgba32uint',
  32035. RGBA32Sint: 'rgba32sint',
  32036. RGBA32Float: 'rgba32float',
  32037. // Depth and stencil formats
  32038. Stencil8: 'stencil8',
  32039. Depth16Unorm: 'depth16unorm',
  32040. Depth24Plus: 'depth24plus',
  32041. Depth24PlusStencil8: 'depth24plus-stencil8',
  32042. Depth32Float: 'depth32float',
  32043. // 'depth32float-stencil8' extension
  32044. Depth32FloatStencil8: 'depth32float-stencil8',
  32045. // BC compressed formats usable if 'texture-compression-bc' is both
  32046. // supported by the device/user agent and enabled in requestDevice.
  32047. BC1RGBAUnorm: 'bc1-rgba-unorm',
  32048. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  32049. BC2RGBAUnorm: 'bc2-rgba-unorm',
  32050. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  32051. BC3RGBAUnorm: 'bc3-rgba-unorm',
  32052. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  32053. BC4RUnorm: 'bc4-r-unorm',
  32054. BC4RSnorm: 'bc4-r-snorm',
  32055. BC5RGUnorm: 'bc5-rg-unorm',
  32056. BC5RGSnorm: 'bc5-rg-snorm',
  32057. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  32058. BC6HRGBFloat: 'bc6h-rgb-float',
  32059. BC7RGBAUnorm: 'bc7-rgba-unorm',
  32060. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  32061. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  32062. // supported by the device/user agent and enabled in requestDevice.
  32063. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  32064. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  32065. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  32066. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  32067. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  32068. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  32069. EACR11Unorm: 'eac-r11unorm',
  32070. EACR11Snorm: 'eac-r11snorm',
  32071. EACRG11Unorm: 'eac-rg11unorm',
  32072. EACRG11Snorm: 'eac-rg11snorm',
  32073. // ASTC compressed formats usable if 'texture-compression-astc' is both
  32074. // supported by the device/user agent and enabled in requestDevice.
  32075. ASTC4x4Unorm: 'astc-4x4-unorm',
  32076. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  32077. ASTC5x4Unorm: 'astc-5x4-unorm',
  32078. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  32079. ASTC5x5Unorm: 'astc-5x5-unorm',
  32080. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  32081. ASTC6x5Unorm: 'astc-6x5-unorm',
  32082. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  32083. ASTC6x6Unorm: 'astc-6x6-unorm',
  32084. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  32085. ASTC8x5Unorm: 'astc-8x5-unorm',
  32086. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  32087. ASTC8x6Unorm: 'astc-8x6-unorm',
  32088. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  32089. ASTC8x8Unorm: 'astc-8x8-unorm',
  32090. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  32091. ASTC10x5Unorm: 'astc-10x5-unorm',
  32092. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  32093. ASTC10x6Unorm: 'astc-10x6-unorm',
  32094. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  32095. ASTC10x8Unorm: 'astc-10x8-unorm',
  32096. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  32097. ASTC10x10Unorm: 'astc-10x10-unorm',
  32098. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  32099. ASTC12x10Unorm: 'astc-12x10-unorm',
  32100. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  32101. ASTC12x12Unorm: 'astc-12x12-unorm',
  32102. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  32103. };
  32104. const GPUAddressMode = {
  32105. ClampToEdge: 'clamp-to-edge',
  32106. Repeat: 'repeat',
  32107. MirrorRepeat: 'mirror-repeat'
  32108. };
  32109. const GPUFilterMode = {
  32110. Linear: 'linear',
  32111. Nearest: 'nearest'
  32112. };
  32113. const GPUBlendFactor = {
  32114. Zero: 'zero',
  32115. One: 'one',
  32116. Src: 'src',
  32117. OneMinusSrc: 'one-minus-src',
  32118. SrcAlpha: 'src-alpha',
  32119. OneMinusSrcAlpha: 'one-minus-src-alpha',
  32120. Dst: 'dst',
  32121. OneMinusDstColor: 'one-minus-dst',
  32122. DstAlpha: 'dst-alpha',
  32123. OneMinusDstAlpha: 'one-minus-dst-alpha',
  32124. SrcAlphaSaturated: 'src-alpha-saturated',
  32125. Constant: 'constant',
  32126. OneMinusConstant: 'one-minus-constant'
  32127. };
  32128. const GPUBlendOperation = {
  32129. Add: 'add',
  32130. Subtract: 'subtract',
  32131. ReverseSubtract: 'reverse-subtract',
  32132. Min: 'min',
  32133. Max: 'max'
  32134. };
  32135. const GPUColorWriteFlags = {
  32136. None: 0,
  32137. Red: 0x1,
  32138. Green: 0x2,
  32139. Blue: 0x4,
  32140. Alpha: 0x8,
  32141. All: 0xF
  32142. };
  32143. const GPUStencilOperation = {
  32144. Keep: 'keep',
  32145. Zero: 'zero',
  32146. Replace: 'replace',
  32147. Invert: 'invert',
  32148. IncrementClamp: 'increment-clamp',
  32149. DecrementClamp: 'decrement-clamp',
  32150. IncrementWrap: 'increment-wrap',
  32151. DecrementWrap: 'decrement-wrap'
  32152. };
  32153. const GPUBufferBindingType = {
  32154. Uniform: 'uniform',
  32155. Storage: 'storage',
  32156. ReadOnlyStorage: 'read-only-storage'
  32157. };
  32158. const GPUStorageTextureAccess = {
  32159. WriteOnly: 'write-only',
  32160. ReadOnly: 'read-only',
  32161. ReadWrite: 'read-write',
  32162. };
  32163. const GPUTextureSampleType = {
  32164. Float: 'float',
  32165. UnfilterableFloat: 'unfilterable-float',
  32166. Depth: 'depth',
  32167. SInt: 'sint',
  32168. UInt: 'uint'
  32169. };
  32170. const GPUTextureDimension = {
  32171. OneD: '1d',
  32172. TwoD: '2d',
  32173. ThreeD: '3d'
  32174. };
  32175. const GPUTextureViewDimension = {
  32176. OneD: '1d',
  32177. TwoD: '2d',
  32178. TwoDArray: '2d-array',
  32179. Cube: 'cube',
  32180. CubeArray: 'cube-array',
  32181. ThreeD: '3d'
  32182. };
  32183. const GPUTextureAspect = {
  32184. All: 'all',
  32185. StencilOnly: 'stencil-only',
  32186. DepthOnly: 'depth-only'
  32187. };
  32188. const GPUInputStepMode = {
  32189. Vertex: 'vertex',
  32190. Instance: 'instance'
  32191. };
  32192. const GPUFeatureName = {
  32193. DepthClipControl: 'depth-clip-control',
  32194. Depth32FloatStencil8: 'depth32float-stencil8',
  32195. TextureCompressionBC: 'texture-compression-bc',
  32196. TextureCompressionETC2: 'texture-compression-etc2',
  32197. TextureCompressionASTC: 'texture-compression-astc',
  32198. TimestampQuery: 'timestamp-query',
  32199. IndirectFirstInstance: 'indirect-first-instance',
  32200. ShaderF16: 'shader-f16',
  32201. RG11B10UFloat: 'rg11b10ufloat-renderable',
  32202. BGRA8UNormStorage: 'bgra8unorm-storage',
  32203. Float32Filterable: 'float32-filterable',
  32204. ClipDistances: 'clip-distances',
  32205. DualSourceBlending: 'dual-source-blending',
  32206. Subgroups: 'subgroups'
  32207. };
  32208. class StorageBufferNode extends BufferNode {
  32209. static get type() {
  32210. return 'StorageBufferNode';
  32211. }
  32212. constructor( value, bufferType, bufferCount = 0 ) {
  32213. super( value, bufferType, bufferCount );
  32214. this.isStorageBufferNode = true;
  32215. this.access = GPUBufferBindingType.Storage;
  32216. this.bufferObject = false;
  32217. this.bufferCount = bufferCount;
  32218. this._attribute = null;
  32219. this._varying = null;
  32220. this.global = true;
  32221. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  32222. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  32223. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  32224. else value.isStorageBufferAttribute = true;
  32225. }
  32226. }
  32227. getHash( builder ) {
  32228. if ( this.bufferCount === 0 ) {
  32229. let bufferData = builder.globalCache.getData( this.value );
  32230. if ( bufferData === undefined ) {
  32231. bufferData = {
  32232. node: this
  32233. };
  32234. builder.globalCache.setData( this.value, bufferData );
  32235. }
  32236. return bufferData.node.uuid;
  32237. }
  32238. return this.uuid;
  32239. }
  32240. getInputType( /*builder*/ ) {
  32241. return 'storageBuffer';
  32242. }
  32243. element( indexNode ) {
  32244. return storageElement( this, indexNode );
  32245. }
  32246. setBufferObject( value ) {
  32247. this.bufferObject = value;
  32248. return this;
  32249. }
  32250. setAccess( value ) {
  32251. this.access = value;
  32252. return this;
  32253. }
  32254. toReadOnly() {
  32255. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  32256. }
  32257. generate( builder ) {
  32258. if ( builder.isAvailable( 'storageBuffer' ) ) {
  32259. return super.generate( builder );
  32260. }
  32261. const nodeType = this.getNodeType( builder );
  32262. if ( this._attribute === null ) {
  32263. this._attribute = bufferAttribute( this.value );
  32264. this._varying = varying( this._attribute );
  32265. }
  32266. const output = this._varying.build( builder, nodeType );
  32267. builder.registerTransform( output, this._attribute );
  32268. return output;
  32269. }
  32270. }
  32271. // Read-Write Storage
  32272. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  32273. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  32274. class StorageTextureNode extends TextureNode {
  32275. static get type() {
  32276. return 'StorageTextureNode';
  32277. }
  32278. constructor( value, uvNode, storeNode = null ) {
  32279. super( value, uvNode );
  32280. this.storeNode = storeNode;
  32281. this.isStorageTextureNode = true;
  32282. this.access = GPUStorageTextureAccess.WriteOnly;
  32283. }
  32284. getInputType( /*builder*/ ) {
  32285. return 'storageTexture';
  32286. }
  32287. setup( builder ) {
  32288. super.setup( builder );
  32289. const properties = builder.getNodeProperties( this );
  32290. properties.storeNode = this.storeNode;
  32291. }
  32292. setAccess( value ) {
  32293. this.access = value;
  32294. return this;
  32295. }
  32296. generate( builder, output ) {
  32297. let snippet;
  32298. if ( this.storeNode !== null ) {
  32299. snippet = this.generateStore( builder );
  32300. } else {
  32301. snippet = super.generate( builder, output );
  32302. }
  32303. return snippet;
  32304. }
  32305. toReadOnly() {
  32306. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  32307. }
  32308. toWriteOnly() {
  32309. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  32310. }
  32311. generateStore( builder ) {
  32312. const properties = builder.getNodeProperties( this );
  32313. const { uvNode, storeNode } = properties;
  32314. const textureProperty = super.generate( builder, 'property' );
  32315. const uvSnippet = uvNode.build( builder, 'uvec2' );
  32316. const storeSnippet = storeNode.build( builder, 'vec4' );
  32317. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  32318. builder.addLineFlowCode( snippet );
  32319. }
  32320. }
  32321. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  32322. const textureStore = ( value, uvNode, storeNode ) => {
  32323. const node = storageTexture( value, uvNode, storeNode );
  32324. if ( storeNode !== null ) node.append();
  32325. return node;
  32326. };
  32327. class UserDataNode extends ReferenceNode {
  32328. static get type() {
  32329. return 'UserDataNode';
  32330. }
  32331. constructor( property, inputType, userData = null ) {
  32332. super( property, inputType, userData );
  32333. this.userData = userData;
  32334. }
  32335. update( frame ) {
  32336. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  32337. super.update( frame );
  32338. }
  32339. }
  32340. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  32341. class PosterizeNode extends TempNode {
  32342. static get type() {
  32343. return 'PosterizeNode';
  32344. }
  32345. constructor( sourceNode, stepsNode ) {
  32346. super();
  32347. this.sourceNode = sourceNode;
  32348. this.stepsNode = stepsNode;
  32349. }
  32350. setup() {
  32351. const { sourceNode, stepsNode } = this;
  32352. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  32353. }
  32354. }
  32355. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  32356. let _sharedFramebuffer = null;
  32357. class ViewportSharedTextureNode extends ViewportTextureNode {
  32358. static get type() {
  32359. return 'ViewportSharedTextureNode';
  32360. }
  32361. constructor( uvNode = viewportUV, levelNode = null ) {
  32362. if ( _sharedFramebuffer === null ) {
  32363. _sharedFramebuffer = new FramebufferTexture();
  32364. }
  32365. super( uvNode, levelNode, _sharedFramebuffer );
  32366. }
  32367. updateReference() {
  32368. return this;
  32369. }
  32370. }
  32371. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  32372. const _size$7 = /*@__PURE__*/ new Vector2();
  32373. class PassTextureNode extends TextureNode {
  32374. static get type() {
  32375. return 'PassTextureNode';
  32376. }
  32377. constructor( passNode, texture ) {
  32378. super( texture );
  32379. this.passNode = passNode;
  32380. this.setUpdateMatrix( false );
  32381. }
  32382. setup( builder ) {
  32383. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  32384. return super.setup( builder );
  32385. }
  32386. clone() {
  32387. return new this.constructor( this.passNode, this.value );
  32388. }
  32389. }
  32390. class PassMultipleTextureNode extends PassTextureNode {
  32391. static get type() {
  32392. return 'PassMultipleTextureNode';
  32393. }
  32394. constructor( passNode, textureName, previousTexture = false ) {
  32395. super( passNode, null );
  32396. this.textureName = textureName;
  32397. this.previousTexture = previousTexture;
  32398. }
  32399. updateTexture() {
  32400. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  32401. }
  32402. setup( builder ) {
  32403. this.updateTexture();
  32404. return super.setup( builder );
  32405. }
  32406. clone() {
  32407. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  32408. }
  32409. }
  32410. class PassNode extends TempNode {
  32411. static get type() {
  32412. return 'PassNode';
  32413. }
  32414. constructor( scope, scene, camera, options = {} ) {
  32415. super( 'vec4' );
  32416. this.scope = scope;
  32417. this.scene = scene;
  32418. this.camera = camera;
  32419. this.options = options;
  32420. this._pixelRatio = 1;
  32421. this._width = 1;
  32422. this._height = 1;
  32423. const depthTexture = new DepthTexture();
  32424. depthTexture.isRenderTargetTexture = true;
  32425. //depthTexture.type = FloatType;
  32426. depthTexture.name = 'depth';
  32427. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  32428. renderTarget.texture.name = 'output';
  32429. renderTarget.depthTexture = depthTexture;
  32430. this.renderTarget = renderTarget;
  32431. this.updateBeforeType = NodeUpdateType.FRAME;
  32432. this._textures = {
  32433. output: renderTarget.texture,
  32434. depth: depthTexture
  32435. };
  32436. this._textureNodes = {};
  32437. this._linearDepthNodes = {};
  32438. this._viewZNodes = {};
  32439. this._previousTextures = {};
  32440. this._previousTextureNodes = {};
  32441. this._cameraNear = uniform( 0 );
  32442. this._cameraFar = uniform( 0 );
  32443. this._mrt = null;
  32444. this.isPassNode = true;
  32445. }
  32446. setMRT( mrt ) {
  32447. this._mrt = mrt;
  32448. return this;
  32449. }
  32450. getMRT() {
  32451. return this._mrt;
  32452. }
  32453. isGlobal() {
  32454. return true;
  32455. }
  32456. getTexture( name ) {
  32457. let texture = this._textures[ name ];
  32458. if ( texture === undefined ) {
  32459. const refTexture = this.renderTarget.texture;
  32460. texture = refTexture.clone();
  32461. texture.isRenderTargetTexture = true;
  32462. texture.name = name;
  32463. this._textures[ name ] = texture;
  32464. this.renderTarget.textures.push( texture );
  32465. }
  32466. return texture;
  32467. }
  32468. getPreviousTexture( name ) {
  32469. let texture = this._previousTextures[ name ];
  32470. if ( texture === undefined ) {
  32471. texture = this.getTexture( name ).clone();
  32472. texture.isRenderTargetTexture = true;
  32473. this._previousTextures[ name ] = texture;
  32474. }
  32475. return texture;
  32476. }
  32477. toggleTexture( name ) {
  32478. const prevTexture = this._previousTextures[ name ];
  32479. if ( prevTexture !== undefined ) {
  32480. const texture = this._textures[ name ];
  32481. const index = this.renderTarget.textures.indexOf( texture );
  32482. this.renderTarget.textures[ index ] = prevTexture;
  32483. this._textures[ name ] = prevTexture;
  32484. this._previousTextures[ name ] = texture;
  32485. this._textureNodes[ name ].updateTexture();
  32486. this._previousTextureNodes[ name ].updateTexture();
  32487. }
  32488. }
  32489. getTextureNode( name = 'output' ) {
  32490. let textureNode = this._textureNodes[ name ];
  32491. if ( textureNode === undefined ) {
  32492. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  32493. this._textureNodes[ name ].updateTexture();
  32494. }
  32495. return textureNode;
  32496. }
  32497. getPreviousTextureNode( name = 'output' ) {
  32498. let textureNode = this._previousTextureNodes[ name ];
  32499. if ( textureNode === undefined ) {
  32500. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  32501. this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  32502. this._previousTextureNodes[ name ].updateTexture();
  32503. }
  32504. return textureNode;
  32505. }
  32506. getViewZNode( name = 'depth' ) {
  32507. let viewZNode = this._viewZNodes[ name ];
  32508. if ( viewZNode === undefined ) {
  32509. const cameraNear = this._cameraNear;
  32510. const cameraFar = this._cameraFar;
  32511. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  32512. }
  32513. return viewZNode;
  32514. }
  32515. getLinearDepthNode( name = 'depth' ) {
  32516. let linearDepthNode = this._linearDepthNodes[ name ];
  32517. if ( linearDepthNode === undefined ) {
  32518. const cameraNear = this._cameraNear;
  32519. const cameraFar = this._cameraFar;
  32520. const viewZNode = this.getViewZNode( name );
  32521. // TODO: just if ( builder.camera.isPerspectiveCamera )
  32522. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  32523. }
  32524. return linearDepthNode;
  32525. }
  32526. setup( { renderer } ) {
  32527. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  32528. // Disable MSAA for WebGL backend for now
  32529. if ( renderer.backend.isWebGLBackend === true ) {
  32530. this.renderTarget.samples = 0;
  32531. }
  32532. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  32533. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  32534. }
  32535. updateBefore( frame ) {
  32536. const { renderer } = frame;
  32537. const { scene, camera } = this;
  32538. this._pixelRatio = renderer.getPixelRatio();
  32539. const size = renderer.getSize( _size$7 );
  32540. this.setSize( size.width, size.height );
  32541. const currentRenderTarget = renderer.getRenderTarget();
  32542. const currentMRT = renderer.getMRT();
  32543. this._cameraNear.value = camera.near;
  32544. this._cameraFar.value = camera.far;
  32545. for ( const name in this._previousTextures ) {
  32546. this.toggleTexture( name );
  32547. }
  32548. renderer.setRenderTarget( this.renderTarget );
  32549. renderer.setMRT( this._mrt );
  32550. renderer.render( scene, camera );
  32551. renderer.setRenderTarget( currentRenderTarget );
  32552. renderer.setMRT( currentMRT );
  32553. }
  32554. setSize( width, height ) {
  32555. this._width = width;
  32556. this._height = height;
  32557. const effectiveWidth = this._width * this._pixelRatio;
  32558. const effectiveHeight = this._height * this._pixelRatio;
  32559. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32560. }
  32561. setPixelRatio( pixelRatio ) {
  32562. this._pixelRatio = pixelRatio;
  32563. this.setSize( this._width, this._height );
  32564. }
  32565. dispose() {
  32566. this.renderTarget.dispose();
  32567. }
  32568. }
  32569. PassNode.COLOR = 'color';
  32570. PassNode.DEPTH = 'depth';
  32571. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  32572. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  32573. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  32574. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  32575. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  32576. const _quadMesh1 = /*@__PURE__*/ new QuadMesh();
  32577. const _quadMesh2 = /*@__PURE__*/ new QuadMesh();
  32578. class GaussianBlurNode extends TempNode {
  32579. static get type() {
  32580. return 'GaussianBlurNode';
  32581. }
  32582. constructor( textureNode, directionNode = null, sigma = 2 ) {
  32583. super( 'vec4' );
  32584. this.textureNode = textureNode;
  32585. this.directionNode = directionNode;
  32586. this.sigma = sigma;
  32587. this._invSize = uniform( new Vector2() );
  32588. this._passDirection = uniform( new Vector2() );
  32589. this._horizontalRT = new RenderTarget();
  32590. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  32591. this._verticalRT = new RenderTarget();
  32592. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  32593. this._textureNode = passTexture( this, this._verticalRT.texture );
  32594. this.updateBeforeType = NodeUpdateType.RENDER;
  32595. this.resolution = new Vector2( 1, 1 );
  32596. }
  32597. setSize( width, height ) {
  32598. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  32599. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  32600. this._invSize.value.set( 1 / width, 1 / height );
  32601. this._horizontalRT.setSize( width, height );
  32602. this._verticalRT.setSize( width, height );
  32603. }
  32604. updateBefore( frame ) {
  32605. const { renderer } = frame;
  32606. const textureNode = this.textureNode;
  32607. const map = textureNode.value;
  32608. const currentRenderTarget = renderer.getRenderTarget();
  32609. const currentMRT = renderer.getMRT();
  32610. const currentTexture = textureNode.value;
  32611. _quadMesh1.material = this._material;
  32612. _quadMesh2.material = this._material;
  32613. this.setSize( map.image.width, map.image.height );
  32614. const textureType = map.type;
  32615. this._horizontalRT.texture.type = textureType;
  32616. this._verticalRT.texture.type = textureType;
  32617. // clear
  32618. renderer.setMRT( null );
  32619. // horizontal
  32620. renderer.setRenderTarget( this._horizontalRT );
  32621. this._passDirection.value.set( 1, 0 );
  32622. _quadMesh1.render( renderer );
  32623. // vertical
  32624. textureNode.value = this._horizontalRT.texture;
  32625. renderer.setRenderTarget( this._verticalRT );
  32626. this._passDirection.value.set( 0, 1 );
  32627. _quadMesh2.render( renderer );
  32628. // restore
  32629. renderer.setRenderTarget( currentRenderTarget );
  32630. renderer.setMRT( currentMRT );
  32631. textureNode.value = currentTexture;
  32632. }
  32633. getTextureNode() {
  32634. return this._textureNode;
  32635. }
  32636. setup( builder ) {
  32637. const textureNode = this.textureNode;
  32638. if ( textureNode.isTextureNode !== true ) {
  32639. console.error( 'GaussianBlurNode requires a TextureNode.' );
  32640. return vec4();
  32641. }
  32642. //
  32643. const uvNode = textureNode.uvNode || uv();
  32644. const directionNode = vec2( this.directionNode || 1 );
  32645. const sampleTexture = ( uv ) => textureNode.uv( uv );
  32646. const blur = Fn( () => {
  32647. const kernelSize = 3 + ( 2 * this.sigma );
  32648. const gaussianCoefficients = this._getCoefficients( kernelSize );
  32649. const invSize = this._invSize;
  32650. const direction = directionNode.mul( this._passDirection );
  32651. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  32652. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  32653. for ( let i = 1; i < kernelSize; i ++ ) {
  32654. const x = float( i );
  32655. const w = float( gaussianCoefficients[ i ] );
  32656. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  32657. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  32658. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  32659. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  32660. weightSum.addAssign( mul( 2.0, w ) );
  32661. }
  32662. return diffuseSum.div( weightSum );
  32663. } );
  32664. //
  32665. const material = this._material || ( this._material = new NodeMaterial() );
  32666. material.fragmentNode = blur().context( builder.getSharedContext() );
  32667. material.name = 'Gaussian_blur';
  32668. material.needsUpdate = true;
  32669. //
  32670. const properties = builder.getNodeProperties( this );
  32671. properties.textureNode = textureNode;
  32672. //
  32673. return this._textureNode;
  32674. }
  32675. dispose() {
  32676. this._horizontalRT.dispose();
  32677. this._verticalRT.dispose();
  32678. }
  32679. _getCoefficients( kernelRadius ) {
  32680. const coefficients = [];
  32681. for ( let i = 0; i < kernelRadius; i ++ ) {
  32682. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  32683. }
  32684. return coefficients;
  32685. }
  32686. }
  32687. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma ) );
  32688. const _size$6 = /*@__PURE__*/ new Vector2();
  32689. const _quadMeshComp = /*@__PURE__*/ new QuadMesh();
  32690. class AfterImageNode extends TempNode {
  32691. static get type() {
  32692. return 'AfterImageNode';
  32693. }
  32694. constructor( textureNode, damp = 0.96 ) {
  32695. super( textureNode );
  32696. this.textureNode = textureNode;
  32697. this.textureNodeOld = texture();
  32698. this.damp = uniform( damp );
  32699. this._compRT = new RenderTarget();
  32700. this._compRT.texture.name = 'AfterImageNode.comp';
  32701. this._oldRT = new RenderTarget();
  32702. this._oldRT.texture.name = 'AfterImageNode.old';
  32703. this._textureNode = passTexture( this, this._compRT.texture );
  32704. this.updateBeforeType = NodeUpdateType.RENDER;
  32705. }
  32706. getTextureNode() {
  32707. return this._textureNode;
  32708. }
  32709. setSize( width, height ) {
  32710. this._compRT.setSize( width, height );
  32711. this._oldRT.setSize( width, height );
  32712. }
  32713. updateBefore( frame ) {
  32714. const { renderer } = frame;
  32715. const textureNode = this.textureNode;
  32716. const map = textureNode.value;
  32717. const textureType = map.type;
  32718. this._compRT.texture.type = textureType;
  32719. this._oldRT.texture.type = textureType;
  32720. renderer.getDrawingBufferSize( _size$6 );
  32721. this.setSize( _size$6.x, _size$6.y );
  32722. const currentRenderTarget = renderer.getRenderTarget();
  32723. const currentTexture = textureNode.value;
  32724. this.textureNodeOld.value = this._oldRT.texture;
  32725. // comp
  32726. renderer.setRenderTarget( this._compRT );
  32727. _quadMeshComp.render( renderer );
  32728. // Swap the textures
  32729. const temp = this._oldRT;
  32730. this._oldRT = this._compRT;
  32731. this._compRT = temp;
  32732. renderer.setRenderTarget( currentRenderTarget );
  32733. textureNode.value = currentTexture;
  32734. }
  32735. setup( builder ) {
  32736. const textureNode = this.textureNode;
  32737. const textureNodeOld = this.textureNodeOld;
  32738. //
  32739. const uvNode = textureNode.uvNode || uv();
  32740. textureNodeOld.uvNode = uvNode;
  32741. const sampleTexture = ( uv ) => textureNode.uv( uv );
  32742. const when_gt = Fn( ( [ x_immutable, y_immutable ] ) => {
  32743. const y = float( y_immutable ).toVar();
  32744. const x = vec4( x_immutable ).toVar();
  32745. return max$1( sign( x.sub( y ) ), 0.0 );
  32746. } );
  32747. const afterImg = Fn( () => {
  32748. const texelOld = vec4( textureNodeOld );
  32749. const texelNew = vec4( sampleTexture( uvNode ) );
  32750. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  32751. return max$1( texelNew, texelOld );
  32752. } );
  32753. //
  32754. const materialComposed = this._materialComposed || ( this._materialComposed = new NodeMaterial() );
  32755. materialComposed.name = 'AfterImage';
  32756. materialComposed.fragmentNode = afterImg();
  32757. _quadMeshComp.material = materialComposed;
  32758. //
  32759. const properties = builder.getNodeProperties( this );
  32760. properties.textureNode = textureNode;
  32761. //
  32762. return this._textureNode;
  32763. }
  32764. dispose() {
  32765. this._compRT.dispose();
  32766. this._oldRT.dispose();
  32767. }
  32768. }
  32769. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( convertToTexture( node ), damp ) );
  32770. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32771. return luminance( color.rgb );
  32772. } );
  32773. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32774. return adjustment.mix( luminance( color.rgb ), color.rgb );
  32775. } );
  32776. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32777. const average = add( color.r, color.g, color.b ).div( 3.0 );
  32778. const mx = color.r.max( color.g.max( color.b ) );
  32779. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  32780. return mix( color.rgb, mx, amt );
  32781. } );
  32782. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32783. const k = vec3( 0.57735, 0.57735, 0.57735 );
  32784. const cosAngle = adjustment.cos();
  32785. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  32786. } );
  32787. const _luminanceCoefficients = /*@__PURE__*/ new Vector3();
  32788. const luminance = (
  32789. color,
  32790. luminanceCoefficients = vec3( ... ColorManagement.getLuminanceCoefficients( _luminanceCoefficients ) )
  32791. ) => dot( color, luminanceCoefficients );
  32792. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  32793. const _quadMesh$4 = /*@__PURE__*/ new QuadMesh();
  32794. class AnamorphicNode extends TempNode {
  32795. static get type() {
  32796. return 'AnamorphicNode';
  32797. }
  32798. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  32799. super( 'vec4' );
  32800. this.textureNode = textureNode;
  32801. this.tresholdNode = tresholdNode;
  32802. this.scaleNode = scaleNode;
  32803. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  32804. this.samples = samples;
  32805. this.resolution = new Vector2( 1, 1 );
  32806. this._renderTarget = new RenderTarget();
  32807. this._renderTarget.texture.name = 'anamorphic';
  32808. this._invSize = uniform( new Vector2() );
  32809. this._textureNode = passTexture( this, this._renderTarget.texture );
  32810. this.updateBeforeType = NodeUpdateType.RENDER;
  32811. }
  32812. getTextureNode() {
  32813. return this._textureNode;
  32814. }
  32815. setSize( width, height ) {
  32816. this._invSize.value.set( 1 / width, 1 / height );
  32817. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  32818. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  32819. this._renderTarget.setSize( width, height );
  32820. }
  32821. updateBefore( frame ) {
  32822. const { renderer } = frame;
  32823. const textureNode = this.textureNode;
  32824. const map = textureNode.value;
  32825. this._renderTarget.texture.type = map.type;
  32826. const currentRenderTarget = renderer.getRenderTarget();
  32827. const currentTexture = textureNode.value;
  32828. _quadMesh$4.material = this._material;
  32829. this.setSize( map.image.width, map.image.height );
  32830. // render
  32831. renderer.setRenderTarget( this._renderTarget );
  32832. _quadMesh$4.render( renderer );
  32833. // restore
  32834. renderer.setRenderTarget( currentRenderTarget );
  32835. textureNode.value = currentTexture;
  32836. }
  32837. setup( builder ) {
  32838. const textureNode = this.textureNode;
  32839. const uvNode = textureNode.uvNode || uv();
  32840. const sampleTexture = ( uv ) => textureNode.uv( uv );
  32841. const anamorph = Fn( () => {
  32842. const samples = this.samples;
  32843. const halfSamples = Math.floor( samples / 2 );
  32844. const total = vec3( 0 ).toVar();
  32845. Loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  32846. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  32847. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  32848. const color = sampleTexture( uv );
  32849. const pass = threshold( color, this.tresholdNode ).mul( softness );
  32850. total.addAssign( pass );
  32851. } );
  32852. return total.mul( this.colorNode );
  32853. } );
  32854. //
  32855. const material = this._material || ( this._material = new NodeMaterial() );
  32856. material.name = 'Anamorphic';
  32857. material.fragmentNode = anamorph();
  32858. //
  32859. const properties = builder.getNodeProperties( this );
  32860. properties.textureNode = textureNode;
  32861. //
  32862. return this._textureNode;
  32863. }
  32864. dispose() {
  32865. this._renderTarget.dispose();
  32866. }
  32867. }
  32868. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( convertToTexture( node ), nodeObject( threshold ), nodeObject( scale ), samples ) );
  32869. class SobelOperatorNode extends TempNode {
  32870. static get type() {
  32871. return 'SobelOperatorNode';
  32872. }
  32873. constructor( textureNode ) {
  32874. super();
  32875. this.textureNode = textureNode;
  32876. this.updateBeforeType = NodeUpdateType.RENDER;
  32877. this._invSize = uniform( new Vector2() );
  32878. }
  32879. updateBefore() {
  32880. const map = this.textureNode.value;
  32881. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  32882. }
  32883. setup() {
  32884. const { textureNode } = this;
  32885. const uvNode = textureNode.uvNode || uv();
  32886. const sampleTexture = ( uv ) => textureNode.uv( uv );
  32887. const sobel = Fn( () => {
  32888. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  32889. const texel = this._invSize;
  32890. // kernel definition (in glsl matrices are filled in column-major order)
  32891. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  32892. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  32893. // fetch the 3x3 neighbourhood of a fragment
  32894. // first column
  32895. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  32896. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  32897. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  32898. // second column
  32899. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  32900. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  32901. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  32902. // third column
  32903. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  32904. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  32905. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  32906. // gradient value in x direction
  32907. const valueGx = add(
  32908. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  32909. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  32910. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  32911. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  32912. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  32913. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  32914. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  32915. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  32916. Gx[ 2 ][ 2 ].mul( tx2y2 )
  32917. );
  32918. // gradient value in y direction
  32919. const valueGy = add(
  32920. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  32921. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  32922. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  32923. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  32924. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  32925. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  32926. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  32927. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  32928. Gy[ 2 ][ 2 ].mul( tx2y2 )
  32929. );
  32930. // magnitute of the total gradient
  32931. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  32932. return vec4( vec3( G ), 1 );
  32933. } );
  32934. const outputNode = sobel();
  32935. return outputNode;
  32936. }
  32937. }
  32938. const sobel = ( node ) => nodeObject( new SobelOperatorNode( convertToTexture( node ) ) );
  32939. class DepthOfFieldNode extends TempNode {
  32940. static get type() {
  32941. return 'DepthOfFieldNode';
  32942. }
  32943. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  32944. super();
  32945. this.textureNode = textureNode;
  32946. this.viewZNode = viewZNode;
  32947. this.focusNode = focusNode;
  32948. this.apertureNode = apertureNode;
  32949. this.maxblurNode = maxblurNode;
  32950. this._aspect = uniform( 0 );
  32951. this.updateBeforeType = NodeUpdateType.RENDER;
  32952. }
  32953. updateBefore() {
  32954. const map = this.textureNode.value;
  32955. this._aspect.value = map.image.width / map.image.height;
  32956. }
  32957. setup() {
  32958. const textureNode = this.textureNode;
  32959. const uvNode = textureNode.uvNode || uv();
  32960. const sampleTexture = ( uv ) => textureNode.uv( uv );
  32961. const dof = Fn( () => {
  32962. const aspectcorrect = vec2( 1.0, this._aspect );
  32963. const factor = this.focusNode.add( this.viewZNode );
  32964. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  32965. const dofblur9 = dofblur.mul( 0.9 );
  32966. const dofblur7 = dofblur.mul( 0.7 );
  32967. const dofblur4 = dofblur.mul( 0.4 );
  32968. let col = vec4( 0.0 );
  32969. col = col.add( sampleTexture( uvNode ) );
  32970. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32971. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32972. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32973. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32974. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32975. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32976. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32977. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32978. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32979. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32980. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32981. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32982. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32983. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32984. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32985. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  32986. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32987. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32988. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32989. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32990. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32991. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32992. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32993. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  32994. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  32995. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  32996. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  32997. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  32998. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  32999. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33000. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33001. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33002. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33003. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33004. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33005. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33006. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33007. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33008. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33009. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33010. col = col.div( 41 );
  33011. col.a = 1;
  33012. return vec4( col );
  33013. } );
  33014. const outputNode = dof();
  33015. return outputNode;
  33016. }
  33017. }
  33018. const dof = ( node, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) => nodeObject( new DepthOfFieldNode( convertToTexture( node ), nodeObject( viewZNode ), nodeObject( focus ), nodeObject( aperture ), nodeObject( maxblur ) ) );
  33019. class DotScreenNode extends TempNode {
  33020. static get type() {
  33021. return 'DotScreenNode';
  33022. }
  33023. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  33024. super( 'vec4' );
  33025. this.inputNode = inputNode;
  33026. this.center = uniform( center );
  33027. this.angle = uniform( angle );
  33028. this.scale = uniform( scale );
  33029. }
  33030. setup() {
  33031. const inputNode = this.inputNode;
  33032. const pattern = Fn( () => {
  33033. const s = sin( this.angle );
  33034. const c = cos( this.angle );
  33035. const tex = uv().mul( viewportResolution ).sub( this.center );
  33036. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  33037. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  33038. } );
  33039. const dotScreen = Fn( () => {
  33040. const color = inputNode;
  33041. const average = add( color.r, color.g, color.b ).div( 3 );
  33042. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  33043. } );
  33044. const outputNode = dotScreen();
  33045. return outputNode;
  33046. }
  33047. }
  33048. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  33049. class RGBShiftNode extends TempNode {
  33050. static get type() {
  33051. return 'RGBShiftNode';
  33052. }
  33053. constructor( textureNode, amount = 0.005, angle = 0 ) {
  33054. super( 'vec4' );
  33055. this.textureNode = textureNode;
  33056. this.amount = uniform( amount );
  33057. this.angle = uniform( angle );
  33058. }
  33059. setup() {
  33060. const { textureNode } = this;
  33061. const uvNode = textureNode.uvNode || uv();
  33062. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33063. const rgbShift = Fn( () => {
  33064. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  33065. const cr = sampleTexture( uvNode.add( offset ) );
  33066. const cga = sampleTexture( uvNode );
  33067. const cb = sampleTexture( uvNode.sub( offset ) );
  33068. return vec4( cr.r, cga.g, cb.b, cga.a );
  33069. } );
  33070. return rgbShift();
  33071. }
  33072. }
  33073. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( convertToTexture( node ), amount, angle ) );
  33074. class FilmNode extends TempNode {
  33075. static get type() {
  33076. return 'FilmNode';
  33077. }
  33078. constructor( inputNode, intensityNode = null, uvNode = null ) {
  33079. super();
  33080. this.inputNode = inputNode;
  33081. this.intensityNode = intensityNode;
  33082. this.uvNode = uvNode;
  33083. }
  33084. setup() {
  33085. const uvNode = this.uvNode || uv();
  33086. const film = Fn( () => {
  33087. const base = this.inputNode.rgb;
  33088. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  33089. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  33090. if ( this.intensityNode !== null ) {
  33091. color = mix( base, color, this.intensityNode );
  33092. }
  33093. return vec4( color, this.inputNode.a );
  33094. } );
  33095. const outputNode = film();
  33096. return outputNode;
  33097. }
  33098. }
  33099. const film = /*@__PURE__*/ nodeProxy( FilmNode );
  33100. class Lut3DNode extends TempNode {
  33101. static get type() {
  33102. return 'Lut3DNode';
  33103. }
  33104. constructor( inputNode, lutNode, size, intensityNode ) {
  33105. super();
  33106. this.inputNode = inputNode;
  33107. this.lutNode = lutNode;
  33108. this.size = uniform( size );
  33109. this.intensityNode = intensityNode;
  33110. }
  33111. setup() {
  33112. const { inputNode, lutNode } = this;
  33113. const sampleLut = ( uv ) => lutNode.uv( uv );
  33114. const lut3D = Fn( () => {
  33115. const base = inputNode;
  33116. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  33117. const pixelWidth = float( 1.0 ).div( this.size );
  33118. const halfPixelWidth = float( 0.5 ).div( this.size );
  33119. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  33120. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  33121. return vec4( mix( base, lutValue, this.intensityNode ) );
  33122. } );
  33123. const outputNode = lut3D();
  33124. return outputNode;
  33125. }
  33126. }
  33127. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  33128. const _quadMesh$3 = /*@__PURE__*/ new QuadMesh();
  33129. const _currentClearColor$1 = /*@__PURE__*/ new Color();
  33130. const _size$5 = /*@__PURE__*/ new Vector2();
  33131. class GTAONode extends TempNode {
  33132. static get type() {
  33133. return 'GTAONode';
  33134. }
  33135. constructor( depthNode, normalNode, camera ) {
  33136. super();
  33137. this.depthNode = depthNode;
  33138. this.normalNode = normalNode;
  33139. this.radius = uniform( 0.25 );
  33140. this.resolution = uniform( new Vector2() );
  33141. this.thickness = uniform( 1 );
  33142. this.distanceExponent = uniform( 1 );
  33143. this.distanceFallOff = uniform( 1 );
  33144. this.scale = uniform( 1 );
  33145. this.noiseNode = texture( generateMagicSquareNoise() );
  33146. this.cameraProjectionMatrix = uniform( camera.projectionMatrix );
  33147. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  33148. this.SAMPLES = uniform( 16 );
  33149. this._aoRenderTarget = new RenderTarget();
  33150. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  33151. this._material = null;
  33152. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  33153. this.updateBeforeType = NodeUpdateType.FRAME;
  33154. }
  33155. getTextureNode() {
  33156. return this._textureNode;
  33157. }
  33158. setSize( width, height ) {
  33159. this.resolution.value.set( width, height );
  33160. this._aoRenderTarget.setSize( width, height );
  33161. }
  33162. updateBefore( frame ) {
  33163. const { renderer } = frame;
  33164. const size = renderer.getDrawingBufferSize( _size$5 );
  33165. const currentRenderTarget = renderer.getRenderTarget();
  33166. const currentMRT = renderer.getMRT();
  33167. renderer.getClearColor( _currentClearColor$1 );
  33168. const currentClearAlpha = renderer.getClearAlpha();
  33169. _quadMesh$3.material = this._material;
  33170. this.setSize( size.width, size.height );
  33171. // clear
  33172. renderer.setMRT( null );
  33173. renderer.setClearColor( 0xffffff, 1 );
  33174. // ao
  33175. renderer.setRenderTarget( this._aoRenderTarget );
  33176. _quadMesh$3.render( renderer );
  33177. // restore
  33178. renderer.setRenderTarget( currentRenderTarget );
  33179. renderer.setMRT( currentMRT );
  33180. renderer.setClearColor( _currentClearColor$1, currentClearAlpha );
  33181. }
  33182. setup( builder ) {
  33183. const uvNode = uv();
  33184. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  33185. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  33186. const getSceneUvAndDepth = Fn( ( [ sampleViewPos ] )=> {
  33187. const sampleClipPos = this.cameraProjectionMatrix.mul( vec4( sampleViewPos, 1.0 ) );
  33188. let sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  33189. sampleUv = vec2( sampleUv.x, sampleUv.y.oneMinus() );
  33190. const sampleSceneDepth = sampleDepth( sampleUv );
  33191. return vec3( sampleUv, sampleSceneDepth );
  33192. } );
  33193. const getViewPosition = Fn( ( [ screenPosition, depth ] ) => {
  33194. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  33195. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  33196. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  33197. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  33198. } );
  33199. const ao = Fn( () => {
  33200. const depth = sampleDepth( uvNode );
  33201. depth.greaterThanEqual( 1.0 ).discard();
  33202. const viewPosition = getViewPosition( uvNode, depth );
  33203. const viewNormal = this.normalNode.rgb.normalize();
  33204. const radiusToUse = this.radius;
  33205. const noiseResolution = textureSize( this.noiseNode, 0 );
  33206. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  33207. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  33208. const noiseTexel = sampleNoise( noiseUv );
  33209. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  33210. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  33211. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  33212. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  33213. const DIRECTIONS = this.SAMPLES.lessThan( 30 ).select( 3, 5 );
  33214. const STEPS = add( this.SAMPLES, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS );
  33215. const ao = float( 0 ).toVar();
  33216. Loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  33217. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI );
  33218. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  33219. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  33220. const viewDir = normalize( viewPosition.xyz.negate() );
  33221. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) );
  33222. const sliceTangent = cross( sliceBitangent, viewDir );
  33223. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  33224. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent );
  33225. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  33226. Loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  33227. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  33228. // x
  33229. const sampleSceneUvDepthX = getSceneUvAndDepth( viewPosition.add( sampleViewOffset ) );
  33230. const sampleSceneViewPositionX = getViewPosition( sampleSceneUvDepthX.xy, sampleSceneUvDepthX.z );
  33231. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition );
  33232. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  33233. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  33234. cosHorizons.x.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  33235. } );
  33236. // y
  33237. const sampleSceneUvDepthY = getSceneUvAndDepth( viewPosition.sub( sampleViewOffset ) );
  33238. const sampleSceneViewPositionY = getViewPosition( sampleSceneUvDepthY.xy, sampleSceneUvDepthY.z );
  33239. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition );
  33240. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  33241. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  33242. cosHorizons.y.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  33243. } );
  33244. } );
  33245. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) );
  33246. const nx = dot( normalInSlice, sliceTangent );
  33247. const ny = dot( normalInSlice, viewDir );
  33248. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  33249. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  33250. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  33251. ao.addAssign( occlusion );
  33252. } );
  33253. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  33254. ao.assign( pow( ao, this.scale ) );
  33255. return vec4( vec3( ao ), 1.0 );
  33256. } );
  33257. const material = this._material || ( this._material = new NodeMaterial() );
  33258. material.fragmentNode = ao().context( builder.getSharedContext() );
  33259. material.name = 'GTAO';
  33260. material.needsUpdate = true;
  33261. //
  33262. return this._textureNode;
  33263. }
  33264. dispose() {
  33265. this._aoRenderTarget.dispose();
  33266. }
  33267. }
  33268. function generateMagicSquareNoise( size = 5 ) {
  33269. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  33270. const magicSquare = generateMagicSquare( noiseSize );
  33271. const noiseSquareSize = magicSquare.length;
  33272. const data = new Uint8Array( noiseSquareSize * 4 );
  33273. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  33274. const iAng = magicSquare[ inx ];
  33275. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  33276. const randomVec = new Vector3(
  33277. Math.cos( angle ),
  33278. Math.sin( angle ),
  33279. 0
  33280. ).normalize();
  33281. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  33282. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  33283. data[ inx * 4 + 2 ] = 127;
  33284. data[ inx * 4 + 3 ] = 255;
  33285. }
  33286. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  33287. noiseTexture.wrapS = RepeatWrapping;
  33288. noiseTexture.wrapT = RepeatWrapping;
  33289. noiseTexture.needsUpdate = true;
  33290. return noiseTexture;
  33291. }
  33292. function generateMagicSquare( size ) {
  33293. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  33294. const noiseSquareSize = noiseSize * noiseSize;
  33295. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  33296. let i = Math.floor( noiseSize / 2 );
  33297. let j = noiseSize - 1;
  33298. for ( let num = 1; num <= noiseSquareSize; ) {
  33299. if ( i === - 1 && j === noiseSize ) {
  33300. j = noiseSize - 2;
  33301. i = 0;
  33302. } else {
  33303. if ( j === noiseSize ) {
  33304. j = 0;
  33305. }
  33306. if ( i < 0 ) {
  33307. i = noiseSize - 1;
  33308. }
  33309. }
  33310. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  33311. j -= 2;
  33312. i ++;
  33313. continue;
  33314. } else {
  33315. magicSquare[ i * noiseSize + j ] = num ++;
  33316. }
  33317. j ++;
  33318. i --;
  33319. }
  33320. return magicSquare;
  33321. }
  33322. const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
  33323. class DenoiseNode extends TempNode {
  33324. static get type() {
  33325. return 'DenoiseNode';
  33326. }
  33327. constructor( textureNode, depthNode, normalNode, noiseNode, camera ) {
  33328. super();
  33329. this.textureNode = textureNode;
  33330. this.depthNode = depthNode;
  33331. this.normalNode = normalNode;
  33332. this.noiseNode = noiseNode;
  33333. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  33334. this.lumaPhi = uniform( 5 );
  33335. this.depthPhi = uniform( 5 );
  33336. this.normalPhi = uniform( 5 );
  33337. this.radius = uniform( 5 );
  33338. this.index = uniform( 0 );
  33339. this._resolution = uniform( new Vector2() );
  33340. this._sampleVectors = uniformArray( generatePdSamplePointInitializer( 16, 2, 1 ) );
  33341. this.updateBeforeType = NodeUpdateType.RENDER;
  33342. }
  33343. updateBefore() {
  33344. const map = this.textureNode.value;
  33345. this._resolution.value.set( map.image.width, map.image.height );
  33346. }
  33347. setup() {
  33348. const uvNode = uv();
  33349. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  33350. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  33351. const sampleNormal = ( uv ) => this.normalNode.uv( uv );
  33352. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  33353. const getViewPosition = Fn( ( [ screenPosition, depth ] ) => {
  33354. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  33355. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  33356. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  33357. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  33358. } );
  33359. const denoiseSample = Fn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  33360. const texel = sampleTexture( sampleUv );
  33361. const depth = sampleDepth( sampleUv );
  33362. const normal = sampleNormal( sampleUv ).rgb.normalize();
  33363. const neighborColor = texel.rgb;
  33364. const viewPos = getViewPosition( sampleUv, depth );
  33365. const normalDiff = dot( viewNormal, normal ).toVar();
  33366. const normalSimilarity = pow( max$1( normalDiff, 0 ), this.normalPhi ).toVar();
  33367. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  33368. const lumaSimilarity = max$1( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  33369. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  33370. const depthSimilarity = max$1( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  33371. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  33372. return vec4( neighborColor.mul( w ), w );
  33373. } );
  33374. const denoise = Fn( ( [ uvNode ] ) => {
  33375. const depth = sampleDepth( uvNode );
  33376. const viewNormal = sampleNormal( uvNode ).rgb.normalize();
  33377. const texel = sampleTexture( uvNode );
  33378. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  33379. return texel;
  33380. } );
  33381. const center = vec3( texel.rgb );
  33382. const viewPosition = getViewPosition( uvNode, depth );
  33383. const noiseResolution = textureSize( this.noiseNode, 0 );
  33384. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  33385. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  33386. const noiseTexel = sampleNoise( noiseUv );
  33387. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  33388. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  33389. const noiseVec = vec2( x, y );
  33390. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y );
  33391. const totalWeight = float( 1.0 ).toVar();
  33392. const denoised = vec3( texel.rgb ).toVar();
  33393. Loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  33394. const sampleDir = this._sampleVectors.element( i ).toVar();
  33395. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
  33396. const sampleUv = uvNode.add( offset ).toVar();
  33397. const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  33398. denoised.addAssign( result.xyz );
  33399. totalWeight.addAssign( result.w );
  33400. } );
  33401. If( totalWeight.greaterThan( float( 0 ) ), () => {
  33402. denoised.divAssign( totalWeight );
  33403. } );
  33404. return vec4( denoised, texel.a );
  33405. } ).setLayout( {
  33406. name: 'denoise',
  33407. type: 'vec4',
  33408. inputs: [
  33409. { name: 'uv', type: 'vec2' }
  33410. ]
  33411. } );
  33412. const output = Fn( () => {
  33413. return denoise( uvNode );
  33414. } );
  33415. const outputNode = output();
  33416. return outputNode;
  33417. }
  33418. }
  33419. function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
  33420. const poissonDisk = generateDenoiseSamples( samples, rings, radiusExponent );
  33421. const array = [];
  33422. for ( let i = 0; i < samples; i ++ ) {
  33423. const sample = poissonDisk[ i ];
  33424. array.push( sample );
  33425. }
  33426. return array;
  33427. }
  33428. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  33429. const samples = [];
  33430. for ( let i = 0; i < numSamples; i ++ ) {
  33431. const angle = 2 * Math.PI * numRings * i / numSamples;
  33432. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  33433. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  33434. }
  33435. return samples;
  33436. }
  33437. const denoise = ( node, depthNode, normalNode, noiseNode, camera ) => nodeObject( new DenoiseNode( convertToTexture( node ), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( noiseNode ), camera ) );
  33438. class FXAANode extends TempNode {
  33439. static get type() {
  33440. return 'FXAANode';
  33441. }
  33442. constructor( textureNode ) {
  33443. super();
  33444. this.textureNode = textureNode;
  33445. this.updateBeforeType = NodeUpdateType.RENDER;
  33446. this._invSize = uniform( new Vector2() );
  33447. }
  33448. updateBefore() {
  33449. const map = this.textureNode.value;
  33450. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  33451. }
  33452. setup() {
  33453. const textureNode = this.textureNode.bias( - 100 );
  33454. const uvNode = textureNode.uvNode || uv();
  33455. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  33456. //----------------------------------------------------------------------------------
  33457. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  33458. // SDK Version: v3.00
  33459. // Email: gameworks@nvidia.com
  33460. // Site: http://developer.nvidia.com/
  33461. //
  33462. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  33463. //
  33464. // Redistribution and use in source and binary forms, with or without
  33465. // modification, are permitted provided that the following conditions
  33466. // are met:
  33467. // * Redistributions of source code must retain the above copyright
  33468. // notice, this list of conditions and the following disclaimer.
  33469. // * Redistributions in binary form must reproduce the above copyright
  33470. // notice, this list of conditions and the following disclaimer in the
  33471. // documentation and/or other materials provided with the distribution.
  33472. // * Neither the name of NVIDIA CORPORATION nor the names of its
  33473. // contributors may be used to endorse or promote products derived
  33474. // from this software without specific prior written permission.
  33475. //
  33476. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  33477. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  33478. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  33479. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  33480. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  33481. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  33482. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  33483. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  33484. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33485. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33486. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33487. //
  33488. //----------------------------------------------------------------------------------
  33489. const FxaaTexTop = ( p ) => textureNode.uv( p );
  33490. const FxaaTexOff = ( p, o, r ) => textureNode.uv( p.add( o.mul( r ) ) );
  33491. const NUM_SAMPLES = int( 5 );
  33492. const contrast = Fn( ( [ a_immutable, b_immutable ] ) => {
  33493. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  33494. const b = vec4( b_immutable ).toVar();
  33495. const a = vec4( a_immutable ).toVar();
  33496. const diff = vec4( abs( a.sub( b ) ) ).toVar();
  33497. return max$1( max$1( max$1( diff.r, diff.g ), diff.b ), diff.a );
  33498. } );
  33499. // FXAA3 QUALITY - PC
  33500. const FxaaPixelShader = Fn( ( [ uv, fxaaQualityRcpFrame, fxaaQualityEdgeThreshold, fxaaQualityinvEdgeThreshold ] ) => {
  33501. const rgbaM = FxaaTexTop( uv ).toVar();
  33502. const rgbaS = FxaaTexOff( uv, vec2( 0.0, - 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33503. const rgbaE = FxaaTexOff( uv, vec2( 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33504. const rgbaN = FxaaTexOff( uv, vec2( 0.0, 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33505. const rgbaW = FxaaTexOff( uv, vec2( - 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33506. // . S .
  33507. // W M E
  33508. // . N .
  33509. const contrastN = contrast( rgbaM, rgbaN ).toVar();
  33510. const contrastS = contrast( rgbaM, rgbaS ).toVar();
  33511. const contrastE = contrast( rgbaM, rgbaE ).toVar();
  33512. const contrastW = contrast( rgbaM, rgbaW ).toVar();
  33513. const maxValue = max$1( contrastN, max$1( contrastS, max$1( contrastE, contrastW ) ) ).toVar();
  33514. // . 0 .
  33515. // 0 0 0
  33516. // . 0 .
  33517. If( maxValue.lessThan( fxaaQualityEdgeThreshold ), () => {
  33518. return rgbaM; // assuming define FXAA_DISCARD is always 0
  33519. } );
  33520. //
  33521. const relativeVContrast = sub( contrastN.add( contrastS ), ( contrastE.add( contrastW ) ) ).toVar();
  33522. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  33523. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  33524. If( abs( relativeVContrast ).lessThan( 0.3 ), () => {
  33525. // locate the edge
  33526. const x = contrastE.greaterThan( contrastW ).select( 1, - 1 ).toVar();
  33527. const y = contrastS.greaterThan( contrastN ).select( 1, - 1 ).toVar();
  33528. const dirToEdge = vec2( x, y ).toVar();
  33529. // . 2 . . 1 .
  33530. // 1 0 2 ~= 0 0 1
  33531. // . 1 . . 0 .
  33532. // tap 2 pixels and see which ones are "outside" the edge, to
  33533. // determine if the edge is vertical or horizontal
  33534. const rgbaAlongH = FxaaTexOff( uv, vec2( dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy );
  33535. const matchAlongH = contrast( rgbaM, rgbaAlongH ).toVar();
  33536. // . 1 .
  33537. // 0 0 1
  33538. // . 0 H
  33539. const rgbaAlongV = FxaaTexOff( uv, vec2( dirToEdge.x.negate(), dirToEdge.y.negate() ), fxaaQualityRcpFrame.xy );
  33540. const matchAlongV = contrast( rgbaM, rgbaAlongV ).toVar();
  33541. // V 1 .
  33542. // 0 0 1
  33543. // . 0 .
  33544. relativeVContrast.assign( matchAlongV.sub( matchAlongH ) );
  33545. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  33546. If( abs( relativeVContrast ).lessThan( 0.3 ), () => { // 45 deg edge
  33547. // 1 1 .
  33548. // 0 0 1
  33549. // . 0 1
  33550. // do a simple blur
  33551. const sum = rgbaN.add( rgbaS ).add( rgbaE ).add( rgbaW );
  33552. return mix( rgbaM, sum.mul( 0.25 ), 0.4 );
  33553. } );
  33554. } );
  33555. const offNP = vec2().toVar();
  33556. If( relativeVContrast.lessThanEqual( 0 ), () => {
  33557. rgbaN.assign( rgbaW );
  33558. rgbaS.assign( rgbaE );
  33559. // . 0 . 1
  33560. // 1 0 1 -> 0
  33561. // . 0 . 1
  33562. offNP.x.assign( 0 );
  33563. offNP.y.assign( fxaaQualityRcpFrame.y );
  33564. } ).Else( () => {
  33565. offNP.x.assign( fxaaQualityRcpFrame.x );
  33566. offNP.y.assign( 0 );
  33567. } );
  33568. const mn = contrast( rgbaM, rgbaN ).toVar();
  33569. const ms = contrast( rgbaM, rgbaS ).toVar();
  33570. If( mn.lessThanEqual( ms ), () => {
  33571. rgbaN.assign( rgbaS );
  33572. } );
  33573. const doneN = int( 0 ).toVar();
  33574. const doneP = int( 0 ).toVar();
  33575. const nDist = float( 0 ).toVar();
  33576. const pDist = float( 0 ).toVar();
  33577. const posN = vec2( uv ).toVar();
  33578. const posP = vec2( uv ).toVar();
  33579. const iterationsUsedN = int( 0 ).toVar();
  33580. const iterationsUsedP = int( 0 ).toVar();
  33581. Loop( NUM_SAMPLES, ( { i } ) => {
  33582. const increment = i.add( 1 ).toVar();
  33583. If( doneN.equal( 0 ), () => {
  33584. nDist.addAssign( increment );
  33585. posN.assign( uv.add( offNP.mul( nDist ) ) );
  33586. const rgbaEndN = FxaaTexTop( posN.xy );
  33587. const nm = contrast( rgbaEndN, rgbaM ).toVar();
  33588. const nn = contrast( rgbaEndN, rgbaN ).toVar();
  33589. If( nm.greaterThan( nn ), () => {
  33590. doneN.assign( 1 );
  33591. } );
  33592. iterationsUsedN.assign( i );
  33593. } );
  33594. If( doneP.equal( 0 ), () => {
  33595. pDist.addAssign( increment );
  33596. posP.assign( uv.sub( offNP.mul( pDist ) ) );
  33597. const rgbaEndP = FxaaTexTop( posP.xy );
  33598. const pm = contrast( rgbaEndP, rgbaM ).toVar();
  33599. const pn = contrast( rgbaEndP, rgbaN ).toVar();
  33600. If( pm.greaterThan( pn ), () => {
  33601. doneP.assign( 1 );
  33602. } );
  33603. iterationsUsedP.assign( i );
  33604. } );
  33605. If( doneN.equal( 1 ).or( doneP.equal( 1 ) ), () => {
  33606. Break();
  33607. } );
  33608. } );
  33609. If( doneN.equal( 0 ).and( doneP.equal( 0 ) ), () => {
  33610. return rgbaM; // failed to find end of edge
  33611. } );
  33612. const distN = float( 1 ).toVar();
  33613. const distP = float( 1 ).toVar();
  33614. If( doneN.equal( 1 ), () => {
  33615. distN.assign( float( iterationsUsedN ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  33616. } );
  33617. If( doneP.equal( 1 ), () => {
  33618. distP.assign( float( iterationsUsedP ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  33619. } );
  33620. const dist = min$1( distN, distP );
  33621. // hacky way of reduces blurriness of mostly diagonal edges
  33622. // but reduces AA quality
  33623. dist.assign( pow( dist, 0.5 ) );
  33624. dist.assign( float( 1 ).sub( dist ) );
  33625. return mix( rgbaM, rgbaN, dist.mul( 0.5 ) );
  33626. } ).setLayout( {
  33627. name: 'FxaaPixelShader',
  33628. type: 'vec4',
  33629. inputs: [
  33630. { name: 'uv', type: 'vec2' },
  33631. { name: 'fxaaQualityRcpFrame', type: 'vec2' },
  33632. { name: 'fxaaQualityEdgeThreshold', type: 'float' },
  33633. { name: 'fxaaQualityinvEdgeThreshold', type: 'float' },
  33634. ]
  33635. } );
  33636. const fxaa = Fn( () => {
  33637. const edgeDetectionQuality = float( 0.2 );
  33638. const invEdgeDetectionQuality = float( 1 ).div( edgeDetectionQuality );
  33639. return FxaaPixelShader( uvNode, this._invSize, edgeDetectionQuality, invEdgeDetectionQuality );
  33640. } );
  33641. const outputNode = fxaa();
  33642. return outputNode;
  33643. }
  33644. }
  33645. const fxaa = ( node ) => nodeObject( new FXAANode( convertToTexture( node ) ) );
  33646. const _quadMesh$2 = /*@__PURE__*/ new QuadMesh();
  33647. const _clearColor$1 = /*@__PURE__*/ new Color( 0, 0, 0 );
  33648. const _currentClearColor = /*@__PURE__*/ new Color();
  33649. const _size$4 = /*@__PURE__*/ new Vector2();
  33650. const _BlurDirectionX = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
  33651. const _BlurDirectionY = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
  33652. class BloomNode extends TempNode {
  33653. static get type() {
  33654. return 'BloomNode';
  33655. }
  33656. constructor( inputNode, strength = 1, radius = 0, threshold = 0 ) {
  33657. super();
  33658. this.inputNode = inputNode;
  33659. this.strength = uniform( strength );
  33660. this.radius = uniform( radius );
  33661. this.threshold = uniform( threshold );
  33662. this.smoothWidth = uniform( 0.01 );
  33663. //
  33664. this._renderTargetsHorizontal = [];
  33665. this._renderTargetsVertical = [];
  33666. this._nMips = 5;
  33667. // render targets
  33668. this._renderTargetBright = new RenderTarget( 1, 1, { type: HalfFloatType } );
  33669. this._renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  33670. this._renderTargetBright.texture.generateMipmaps = false;
  33671. for ( let i = 0; i < this._nMips; i ++ ) {
  33672. const renderTargetHorizontal = new RenderTarget( 1, 1, { type: HalfFloatType } );
  33673. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  33674. renderTargetHorizontal.texture.generateMipmaps = false;
  33675. this._renderTargetsHorizontal.push( renderTargetHorizontal );
  33676. const renderTargetVertical = new RenderTarget( 1, 1, { type: HalfFloatType } );
  33677. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  33678. renderTargetVertical.texture.generateMipmaps = false;
  33679. this._renderTargetsVertical.push( renderTargetVertical );
  33680. }
  33681. // materials
  33682. this._compositeMaterial = null;
  33683. this._highPassFilterMaterial = null;
  33684. this._separableBlurMaterials = [];
  33685. // pass and texture nodes
  33686. this._textureNodeBright = texture( this._renderTargetBright.texture );
  33687. this._textureNodeBlur0 = texture( this._renderTargetsVertical[ 0 ].texture );
  33688. this._textureNodeBlur1 = texture( this._renderTargetsVertical[ 1 ].texture );
  33689. this._textureNodeBlur2 = texture( this._renderTargetsVertical[ 2 ].texture );
  33690. this._textureNodeBlur3 = texture( this._renderTargetsVertical[ 3 ].texture );
  33691. this._textureNodeBlur4 = texture( this._renderTargetsVertical[ 4 ].texture );
  33692. this._textureOutput = passTexture( this, this._renderTargetsHorizontal[ 0 ].texture );
  33693. this.updateBeforeType = NodeUpdateType.FRAME;
  33694. }
  33695. getTextureNode() {
  33696. return this._textureOutput;
  33697. }
  33698. setSize( width, height ) {
  33699. let resx = Math.round( width / 2 );
  33700. let resy = Math.round( height / 2 );
  33701. this._renderTargetBright.setSize( resx, resy );
  33702. for ( let i = 0; i < this._nMips; i ++ ) {
  33703. this._renderTargetsHorizontal[ i ].setSize( resx, resy );
  33704. this._renderTargetsVertical[ i ].setSize( resx, resy );
  33705. this._separableBlurMaterials[ i ].invSize.value.set( 1 / resx, 1 / resy );
  33706. resx = Math.round( resx / 2 );
  33707. resy = Math.round( resy / 2 );
  33708. }
  33709. }
  33710. updateBefore( frame ) {
  33711. const { renderer } = frame;
  33712. const size = renderer.getDrawingBufferSize( _size$4 );
  33713. this.setSize( size.width, size.height );
  33714. const currentRenderTarget = renderer.getRenderTarget();
  33715. const currentMRT = renderer.getMRT();
  33716. renderer.getClearColor( _currentClearColor );
  33717. const currentClearAlpha = renderer.getClearAlpha();
  33718. this.setSize( size.width, size.height );
  33719. renderer.setMRT( null );
  33720. renderer.setClearColor( _clearColor$1, 0 );
  33721. // 1. Extract Bright Areas
  33722. renderer.setRenderTarget( this._renderTargetBright );
  33723. _quadMesh$2.material = this._highPassFilterMaterial;
  33724. _quadMesh$2.render( renderer );
  33725. // 2. Blur All the mips progressively
  33726. let inputRenderTarget = this._renderTargetBright;
  33727. for ( let i = 0; i < this._nMips; i ++ ) {
  33728. _quadMesh$2.material = this._separableBlurMaterials[ i ];
  33729. this._separableBlurMaterials[ i ].colorTexture.value = inputRenderTarget.texture;
  33730. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionX;
  33731. renderer.setRenderTarget( this._renderTargetsHorizontal[ i ] );
  33732. renderer.clear();
  33733. _quadMesh$2.render( renderer );
  33734. this._separableBlurMaterials[ i ].colorTexture.value = this._renderTargetsHorizontal[ i ].texture;
  33735. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionY;
  33736. renderer.setRenderTarget( this._renderTargetsVertical[ i ] );
  33737. renderer.clear();
  33738. _quadMesh$2.render( renderer );
  33739. inputRenderTarget = this._renderTargetsVertical[ i ];
  33740. }
  33741. // 3. Composite All the mips
  33742. renderer.setRenderTarget( this._renderTargetsHorizontal[ 0 ] );
  33743. renderer.clear();
  33744. _quadMesh$2.material = this._compositeMaterial;
  33745. _quadMesh$2.render( renderer );
  33746. // restore
  33747. renderer.setRenderTarget( currentRenderTarget );
  33748. renderer.setMRT( currentMRT );
  33749. renderer.setClearColor( _currentClearColor, currentClearAlpha );
  33750. }
  33751. setup( builder ) {
  33752. // luminosity high pass material
  33753. const luminosityHighPass = Fn( () => {
  33754. const texel = this.inputNode;
  33755. const v = luminance( texel.rgb );
  33756. const alpha = smoothstep( this.threshold, this.threshold.add( this.smoothWidth ), v );
  33757. return mix( vec4( 0 ), texel, alpha );
  33758. } );
  33759. this._highPassFilterMaterial = this._highPassFilterMaterial || new NodeMaterial();
  33760. this._highPassFilterMaterial.fragmentNode = luminosityHighPass().context( builder.getSharedContext() );
  33761. this._highPassFilterMaterial.name = 'Bloom_highPass';
  33762. this._highPassFilterMaterial.needsUpdate = true;
  33763. // gaussian blur materials
  33764. const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
  33765. for ( let i = 0; i < this._nMips; i ++ ) {
  33766. this._separableBlurMaterials.push( this._getSeperableBlurMaterial( builder, kernelSizeArray[ i ] ) );
  33767. }
  33768. // composite material
  33769. const bloomFactors = uniformArray( [ 1.0, 0.8, 0.6, 0.4, 0.2 ] );
  33770. 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 ) ] );
  33771. const lerpBloomFactor = Fn( ( [ factor, radius ] ) => {
  33772. const mirrorFactor = float( 1.2 ).sub( factor );
  33773. return mix( factor, mirrorFactor, radius );
  33774. } ).setLayout( {
  33775. name: 'lerpBloomFactor',
  33776. type: 'float',
  33777. inputs: [
  33778. { name: 'factor', type: 'float' },
  33779. { name: 'radius', type: 'float' },
  33780. ]
  33781. } );
  33782. const compositePass = Fn( () => {
  33783. const color0 = lerpBloomFactor( bloomFactors.element( 0 ), this.radius ).mul( vec4( bloomTintColors.element( 0 ), 1.0 ) ).mul( this._textureNodeBlur0 );
  33784. const color1 = lerpBloomFactor( bloomFactors.element( 1 ), this.radius ).mul( vec4( bloomTintColors.element( 1 ), 1.0 ) ).mul( this._textureNodeBlur1 );
  33785. const color2 = lerpBloomFactor( bloomFactors.element( 2 ), this.radius ).mul( vec4( bloomTintColors.element( 2 ), 1.0 ) ).mul( this._textureNodeBlur2 );
  33786. const color3 = lerpBloomFactor( bloomFactors.element( 3 ), this.radius ).mul( vec4( bloomTintColors.element( 3 ), 1.0 ) ).mul( this._textureNodeBlur3 );
  33787. const color4 = lerpBloomFactor( bloomFactors.element( 4 ), this.radius ).mul( vec4( bloomTintColors.element( 4 ), 1.0 ) ).mul( this._textureNodeBlur4 );
  33788. const sum = color0.add( color1 ).add( color2 ).add( color3 ).add( color4 );
  33789. return sum.mul( this.strength );
  33790. } );
  33791. this._compositeMaterial = this._compositeMaterial || new NodeMaterial();
  33792. this._compositeMaterial.fragmentNode = compositePass().context( builder.getSharedContext() );
  33793. this._compositeMaterial.name = 'Bloom_comp';
  33794. this._compositeMaterial.needsUpdate = true;
  33795. //
  33796. return this._textureOutput;
  33797. }
  33798. dispose() {
  33799. for ( let i = 0; i < this._renderTargetsHorizontal.length; i ++ ) {
  33800. this._renderTargetsHorizontal[ i ].dispose();
  33801. }
  33802. for ( let i = 0; i < this._renderTargetsVertical.length; i ++ ) {
  33803. this._renderTargetsVertical[ i ].dispose();
  33804. }
  33805. this._renderTargetBright.dispose();
  33806. }
  33807. _getSeperableBlurMaterial( builder, kernelRadius ) {
  33808. const coefficients = [];
  33809. for ( let i = 0; i < kernelRadius; i ++ ) {
  33810. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  33811. }
  33812. //
  33813. const colorTexture = texture();
  33814. const gaussianCoefficients = uniformArray( coefficients );
  33815. const invSize = uniform( new Vector2() );
  33816. const direction = uniform( new Vector2( 0.5, 0.5 ) );
  33817. const uvNode = uv();
  33818. const sampleTexel = ( uv ) => colorTexture.uv( uv );
  33819. const seperableBlurPass = Fn( () => {
  33820. const weightSum = gaussianCoefficients.element( 0 ).toVar();
  33821. const diffuseSum = sampleTexel( uvNode ).rgb.mul( weightSum ).toVar();
  33822. Loop( { start: int( 1 ), end: int( kernelRadius ), type: 'int', condition: '<' }, ( { i } ) => {
  33823. const x = float( i );
  33824. const w = gaussianCoefficients.element( i );
  33825. const uvOffset = direction.mul( invSize ).mul( x );
  33826. const sample1 = sampleTexel( uvNode.add( uvOffset ) ).rgb;
  33827. const sample2 = sampleTexel( uvNode.sub( uvOffset ) ).rgb;
  33828. diffuseSum.addAssign( add( sample1, sample2 ).mul( w ) );
  33829. weightSum.addAssign( float( 2.0 ).mul( w ) );
  33830. } );
  33831. return vec4( diffuseSum.div( weightSum ), 1.0 );
  33832. } );
  33833. const seperableBlurMaterial = new NodeMaterial();
  33834. seperableBlurMaterial.fragmentNode = seperableBlurPass().context( builder.getSharedContext() );
  33835. seperableBlurMaterial.name = 'Bloom_seperable';
  33836. seperableBlurMaterial.needsUpdate = true;
  33837. // uniforms
  33838. seperableBlurMaterial.colorTexture = colorTexture;
  33839. seperableBlurMaterial.direction = direction;
  33840. seperableBlurMaterial.invSize = invSize;
  33841. return seperableBlurMaterial;
  33842. }
  33843. }
  33844. const bloom = ( node, strength, radius, threshold ) => nodeObject( new BloomNode( nodeObject( node ), strength, radius, threshold ) );
  33845. class TransitionNode extends TempNode {
  33846. static get type() {
  33847. return 'TransitionNode';
  33848. }
  33849. constructor( textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode ) {
  33850. super();
  33851. // Input textures
  33852. this.textureNodeA = textureNodeA;
  33853. this.textureNodeB = textureNodeB;
  33854. this.mixTextureNode = mixTextureNode;
  33855. // Uniforms
  33856. this.mixRatioNode = mixRatioNode;
  33857. this.thresholdNode = thresholdNode;
  33858. this.useTextureNode = useTextureNode;
  33859. }
  33860. setup() {
  33861. const { textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode } = this;
  33862. const sampleTexture = ( textureNode ) => {
  33863. const uvNodeTexture = textureNode.uvNode || uv();
  33864. return textureNode.uv( uvNodeTexture );
  33865. };
  33866. const transition = Fn( () => {
  33867. const texelOne = sampleTexture( textureNodeA );
  33868. const texelTwo = sampleTexture( textureNodeB );
  33869. const color = vec4().toVar();
  33870. If( useTextureNode.equal( int( 1 ) ), () => {
  33871. const transitionTexel = sampleTexture( mixTextureNode );
  33872. const r = mixRatioNode.mul( thresholdNode.mul( 2.0 ).add( 1.0 ) ).sub( thresholdNode );
  33873. const mixf = clamp( sub( transitionTexel.r, r ).mul( float( 1.0 ).div( thresholdNode ) ), 0.0, 1.0 );
  33874. color.assign( mix( texelOne, texelTwo, mixf ) );
  33875. } ).Else( () => {
  33876. color.assign( mix( texelTwo, texelOne, mixRatioNode ) );
  33877. } );
  33878. return color;
  33879. } );
  33880. const outputNode = transition();
  33881. return outputNode;
  33882. }
  33883. }
  33884. 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 ) ) );
  33885. class PixelationNode extends TempNode {
  33886. static get type() {
  33887. return 'PixelationNode';
  33888. }
  33889. constructor( textureNode, depthNode, normalNode, pixelSize, normalEdgeStrength, depthEdgeStrength ) {
  33890. super();
  33891. // Input textures
  33892. this.textureNode = textureNode;
  33893. this.depthNode = depthNode;
  33894. this.normalNode = normalNode;
  33895. // Input uniforms
  33896. this.pixelSize = pixelSize;
  33897. this.normalEdgeStrength = normalEdgeStrength;
  33898. this.depthEdgeStrength = depthEdgeStrength;
  33899. // Private uniforms
  33900. this._resolution = uniform( new Vector4() );
  33901. this.updateBeforeType = NodeUpdateType.RENDER;
  33902. }
  33903. updateBefore() {
  33904. const map = this.textureNode.value;
  33905. const width = map.image.width;
  33906. const height = map.image.height;
  33907. this._resolution.value.set( width, height, 1 / width, 1 / height );
  33908. }
  33909. setup() {
  33910. const { textureNode, depthNode, normalNode } = this;
  33911. const uvNodeTexture = textureNode.uvNode || uv();
  33912. const uvNodeDepth = depthNode.uvNode || uv();
  33913. const uvNodeNormal = normalNode.uvNode || uv();
  33914. const sampleTexture = () => textureNode.uv( uvNodeTexture );
  33915. const sampleDepth = ( x, y ) => depthNode.uv( uvNodeDepth.add( vec2( x, y ).mul( this._resolution.zw ) ) ).r;
  33916. const sampleNormal = ( x, y ) => normalNode.uv( uvNodeNormal.add( vec2( x, y ).mul( this._resolution.zw ) ) ).rgb.normalize();
  33917. const depthEdgeIndicator = ( depth ) => {
  33918. const diff = property( 'float', 'diff' );
  33919. diff.addAssign( clamp( sampleDepth( 1, 0 ).sub( depth ) ) );
  33920. diff.addAssign( clamp( sampleDepth( - 1, 0 ).sub( depth ) ) );
  33921. diff.addAssign( clamp( sampleDepth( 0, 1 ).sub( depth ) ) );
  33922. diff.addAssign( clamp( sampleDepth( 0, - 1 ).sub( depth ) ) );
  33923. return floor( smoothstep( 0.01, 0.02, diff ).mul( 2 ) ).div( 2 );
  33924. };
  33925. const neighborNormalEdgeIndicator = ( x, y, depth, normal ) => {
  33926. const depthDiff = sampleDepth( x, y ).sub( depth );
  33927. const neighborNormal = sampleNormal( x, y );
  33928. // Edge pixels should yield to faces who's normals are closer to the bias normal.
  33929. const normalEdgeBias = vec3( 1, 1, 1 ); // This should probably be a parameter.
  33930. const normalDiff = dot( normal.sub( neighborNormal ), normalEdgeBias );
  33931. const normalIndicator = clamp( smoothstep( - 0.01, 0.01, normalDiff ), 0.0, 1.0 );
  33932. // Only the shallower pixel should detect the normal edge.
  33933. const depthIndicator = clamp( sign( depthDiff.mul( .25 ).add( .0025 ) ), 0.0, 1.0 );
  33934. return float( 1.0 ).sub( dot( normal, neighborNormal ) ).mul( depthIndicator ).mul( normalIndicator );
  33935. };
  33936. const normalEdgeIndicator = ( depth, normal ) => {
  33937. const indicator = property( 'float', 'indicator' );
  33938. indicator.addAssign( neighborNormalEdgeIndicator( 0, - 1, depth, normal ) );
  33939. indicator.addAssign( neighborNormalEdgeIndicator( 0, 1, depth, normal ) );
  33940. indicator.addAssign( neighborNormalEdgeIndicator( - 1, 0, depth, normal ) );
  33941. indicator.addAssign( neighborNormalEdgeIndicator( 1, 0, depth, normal ) );
  33942. return step( 0.1, indicator );
  33943. };
  33944. const pixelation = Fn( () => {
  33945. const texel = sampleTexture();
  33946. const depth = property( 'float', 'depth' );
  33947. const normal = property( 'vec3', 'normal' );
  33948. If( this.depthEdgeStrength.greaterThan( 0.0 ).or( this.normalEdgeStrength.greaterThan( 0.0 ) ), () => {
  33949. depth.assign( sampleDepth( 0, 0 ) );
  33950. normal.assign( sampleNormal( 0, 0 ) );
  33951. } );
  33952. const dei = property( 'float', 'dei' );
  33953. If( this.depthEdgeStrength.greaterThan( 0.0 ), () => {
  33954. dei.assign( depthEdgeIndicator( depth ) );
  33955. } );
  33956. const nei = property( 'float', 'nei' );
  33957. If( this.normalEdgeStrength.greaterThan( 0.0 ), () => {
  33958. nei.assign( normalEdgeIndicator( depth, normal ) );
  33959. } );
  33960. const strength = dei.greaterThan( 0 ).select( float( 1.0 ).sub( dei.mul( this.depthEdgeStrength ) ), nei.mul( this.normalEdgeStrength ).add( 1 ) );
  33961. return texel.mul( strength );
  33962. } );
  33963. const outputNode = pixelation();
  33964. return outputNode;
  33965. }
  33966. }
  33967. 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 ) ) );
  33968. class PixelationPassNode extends PassNode {
  33969. static get type() {
  33970. return 'PixelationPassNode';
  33971. }
  33972. constructor( scene, camera, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) {
  33973. super( 'color', scene, camera, { minFilter: NearestFilter, magFilter: NearestFilter } );
  33974. this.pixelSize = pixelSize;
  33975. this.normalEdgeStrength = normalEdgeStrength;
  33976. this.depthEdgeStrength = depthEdgeStrength;
  33977. this.isPixelationPassNode = true;
  33978. this._mrt = mrt( {
  33979. output: output,
  33980. normal: normalView
  33981. } );
  33982. }
  33983. setSize( width, height ) {
  33984. const pixelSize = this.pixelSize.value ? this.pixelSize.value : this.pixelSize;
  33985. const adjustedWidth = Math.floor( width / pixelSize );
  33986. const adjustedHeight = Math.floor( height / pixelSize );
  33987. super.setSize( adjustedWidth, adjustedHeight );
  33988. }
  33989. setup() {
  33990. const color = super.getTextureNode( 'output' );
  33991. const depth = super.getTextureNode( 'depth' );
  33992. const normal = super.getTextureNode( 'normal' );
  33993. return pixelation( color, depth, normal, this.pixelSize, this.normalEdgeStrength, this.depthEdgeStrength );
  33994. }
  33995. }
  33996. const pixelationPass = ( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) => nodeObject( new PixelationPassNode( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) );
  33997. const _size$3 = /*@__PURE__*/ new Vector2();
  33998. /**
  33999. *
  34000. * Supersample Anti-Aliasing Render Pass
  34001. *
  34002. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  34003. *
  34004. * References: https://en.wikipedia.org/wiki/Supersampling
  34005. *
  34006. */
  34007. class SSAAPassNode extends PassNode {
  34008. static get type() {
  34009. return 'SSAAPassNode';
  34010. }
  34011. constructor( scene, camera ) {
  34012. super( PassNode.COLOR, scene, camera );
  34013. this.isSSAAPassNode = true;
  34014. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  34015. this.unbiased = true;
  34016. this.clearColor = new Color( 0x000000 );
  34017. this.clearAlpha = 0;
  34018. this._currentClearColor = new Color();
  34019. this.sampleWeight = uniform( 1 );
  34020. this.sampleRenderTarget = null;
  34021. this._quadMesh = new QuadMesh();
  34022. }
  34023. updateBefore( frame ) {
  34024. const { renderer } = frame;
  34025. const { scene, camera } = this;
  34026. this._pixelRatio = renderer.getPixelRatio();
  34027. const size = renderer.getSize( _size$3 );
  34028. this.setSize( size.width, size.height );
  34029. this.sampleRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
  34030. // save current renderer settings
  34031. renderer.getClearColor( this._currentClearColor );
  34032. const currentClearAlpha = renderer.getClearAlpha();
  34033. const currentRenderTarget = renderer.getRenderTarget();
  34034. const currentMRT = renderer.getMRT();
  34035. const currentAutoClear = renderer.autoClear;
  34036. //
  34037. this._cameraNear.value = camera.near;
  34038. this._cameraFar.value = camera.far;
  34039. renderer.setMRT( this.getMRT() );
  34040. renderer.autoClear = false;
  34041. const jitterOffsets = _JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
  34042. const baseSampleWeight = 1.0 / jitterOffsets.length;
  34043. const roundingRange = 1 / 32;
  34044. const viewOffset = {
  34045. fullWidth: this.renderTarget.width,
  34046. fullHeight: this.renderTarget.height,
  34047. offsetX: 0,
  34048. offsetY: 0,
  34049. width: this.renderTarget.width,
  34050. height: this.renderTarget.height
  34051. };
  34052. const originalViewOffset = Object.assign( {}, camera.view );
  34053. if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );
  34054. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  34055. for ( let i = 0; i < jitterOffsets.length; i ++ ) {
  34056. const jitterOffset = jitterOffsets[ i ];
  34057. if ( camera.setViewOffset ) {
  34058. camera.setViewOffset(
  34059. viewOffset.fullWidth, viewOffset.fullHeight,
  34060. viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
  34061. viewOffset.width, viewOffset.height
  34062. );
  34063. }
  34064. this.sampleWeight.value = baseSampleWeight;
  34065. if ( this.unbiased ) {
  34066. // the theory is that equal weights for each sample lead to an accumulation of rounding errors.
  34067. // The following equation varies the sampleWeight per sample so that it is uniformly distributed
  34068. // across a range of values whose rounding errors cancel each other out.
  34069. const uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
  34070. this.sampleWeight.value += roundingRange * uniformCenteredDistribution;
  34071. }
  34072. renderer.setClearColor( this.clearColor, this.clearAlpha );
  34073. renderer.setRenderTarget( this.sampleRenderTarget );
  34074. renderer.clear();
  34075. renderer.render( scene, camera );
  34076. // accumulation
  34077. renderer.setRenderTarget( this.renderTarget );
  34078. if ( i === 0 ) {
  34079. renderer.setClearColor( 0x000000, 0.0 );
  34080. renderer.clear();
  34081. }
  34082. this._quadMesh.render( renderer );
  34083. }
  34084. renderer.copyTextureToTexture( this.sampleRenderTarget.depthTexture, this.renderTarget.depthTexture );
  34085. // restore
  34086. if ( camera.setViewOffset && originalViewOffset.enabled ) {
  34087. camera.setViewOffset(
  34088. originalViewOffset.fullWidth, originalViewOffset.fullHeight,
  34089. originalViewOffset.offsetX, originalViewOffset.offsetY,
  34090. originalViewOffset.width, originalViewOffset.height
  34091. );
  34092. } else if ( camera.clearViewOffset ) {
  34093. camera.clearViewOffset();
  34094. }
  34095. renderer.setRenderTarget( currentRenderTarget );
  34096. renderer.setMRT( currentMRT );
  34097. renderer.autoClear = currentAutoClear;
  34098. renderer.setClearColor( this._currentClearColor, currentClearAlpha );
  34099. }
  34100. setup( builder ) {
  34101. if ( this.sampleRenderTarget === null ) {
  34102. this.sampleRenderTarget = this.renderTarget.clone();
  34103. }
  34104. let sampleTexture;
  34105. const passMRT = this.getMRT();
  34106. if ( passMRT !== null ) {
  34107. const outputs = {};
  34108. for ( const name in passMRT.outputNodes ) {
  34109. const index = getTextureIndex( this.sampleRenderTarget.textures, name );
  34110. if ( index >= 0 ) {
  34111. outputs[ name ] = texture( this.sampleRenderTarget.textures[ index ] ).mul( this.sampleWeight );
  34112. }
  34113. }
  34114. sampleTexture = mrt( outputs );
  34115. } else {
  34116. sampleTexture = texture( this.sampleRenderTarget.texture ).mul( this.sampleWeight );
  34117. }
  34118. this._quadMesh.material = new NodeMaterial();
  34119. this._quadMesh.material.fragmentNode = sampleTexture;
  34120. this._quadMesh.material.transparent = true;
  34121. this._quadMesh.material.depthTest = false;
  34122. this._quadMesh.material.depthWrite = false;
  34123. this._quadMesh.material.premultipliedAlpha = true;
  34124. this._quadMesh.material.blending = AdditiveBlending;
  34125. this._quadMesh.material.normals = false;
  34126. this._quadMesh.material.name = 'SSAA';
  34127. return super.setup( builder );
  34128. }
  34129. dispose() {
  34130. super.dispose();
  34131. if ( this.sampleRenderTarget !== null ) {
  34132. this.sampleRenderTarget.dispose();
  34133. }
  34134. }
  34135. }
  34136. // These jitter vectors are specified in integers because it is easier.
  34137. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  34138. // before being used, thus these integers need to be scaled by 1/16.
  34139. //
  34140. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  34141. const _JitterVectors = [
  34142. [
  34143. [ 0, 0 ]
  34144. ],
  34145. [
  34146. [ 4, 4 ], [ - 4, - 4 ]
  34147. ],
  34148. [
  34149. [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  34150. ],
  34151. [
  34152. [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
  34153. [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  34154. ],
  34155. [
  34156. [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
  34157. [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
  34158. [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
  34159. [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  34160. ],
  34161. [
  34162. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  34163. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  34164. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  34165. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  34166. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  34167. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  34168. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  34169. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  34170. ]
  34171. ];
  34172. const ssaaPass = ( scene, camera ) => nodeObject( new SSAAPassNode( scene, camera ) );
  34173. const _size$2 = /*@__PURE__*/ new Vector2();
  34174. class StereoPassNode extends PassNode {
  34175. static get type() {
  34176. return 'StereoPassNode';
  34177. }
  34178. constructor( scene, camera ) {
  34179. super( PassNode.COLOR, scene, camera );
  34180. this.isStereoPassNode = true;
  34181. this.stereo = new StereoCamera();
  34182. this.stereo.aspect = 0.5;
  34183. }
  34184. updateBefore( frame ) {
  34185. const { renderer } = frame;
  34186. const { scene, camera, stereo, renderTarget } = this;
  34187. this._pixelRatio = renderer.getPixelRatio();
  34188. stereo.cameraL.coordinateSystem = renderer.coordinateSystem;
  34189. stereo.cameraR.coordinateSystem = renderer.coordinateSystem;
  34190. stereo.update( camera );
  34191. const size = renderer.getSize( _size$2 );
  34192. this.setSize( size.width, size.height );
  34193. const currentAutoClear = renderer.autoClear;
  34194. renderer.autoClear = false;
  34195. const currentRenderTarget = renderer.getRenderTarget();
  34196. const currentMRT = renderer.getMRT();
  34197. this._cameraNear.value = camera.near;
  34198. this._cameraFar.value = camera.far;
  34199. for ( const name in this._previousTextures ) {
  34200. this.toggleTexture( name );
  34201. }
  34202. renderer.setRenderTarget( renderTarget );
  34203. renderer.setMRT( this._mrt );
  34204. renderer.clear();
  34205. renderTarget.scissorTest = true;
  34206. renderTarget.scissor.set( 0, 0, renderTarget.width / 2, renderTarget.height );
  34207. renderTarget.viewport.set( 0, 0, renderTarget.width / 2, renderTarget.height );
  34208. renderer.render( scene, stereo.cameraL );
  34209. renderTarget.scissor.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
  34210. renderTarget.viewport.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
  34211. renderer.render( scene, stereo.cameraR );
  34212. renderTarget.scissorTest = false;
  34213. renderer.setRenderTarget( currentRenderTarget );
  34214. renderer.setMRT( currentMRT );
  34215. renderer.autoClear = currentAutoClear;
  34216. }
  34217. }
  34218. const stereoPass = ( scene, camera ) => nodeObject( new StereoPassNode( scene, camera ) );
  34219. const _size$1 = /*@__PURE__*/ new Vector2();
  34220. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  34221. class StereoCompositePassNode extends PassNode {
  34222. static get type() {
  34223. return 'StereoCompositePassNode';
  34224. }
  34225. constructor( scene, camera ) {
  34226. super( PassNode.COLOR, scene, camera );
  34227. this.isStereoCompositePassNode = true;
  34228. this.stereo = new StereoCamera();
  34229. const _params = { minFilter: LinearFilter, magFilter: NearestFilter, type: HalfFloatType };
  34230. this._renderTargetL = new RenderTarget( 1, 1, _params );
  34231. this._renderTargetR = new RenderTarget( 1, 1, _params );
  34232. this._mapLeft = texture( this._renderTargetL.texture );
  34233. this._mapRight = texture( this._renderTargetR.texture );
  34234. this._material = null;
  34235. }
  34236. updateStereoCamera( coordinateSystem ) {
  34237. this.stereo.cameraL.coordinateSystem = coordinateSystem;
  34238. this.stereo.cameraR.coordinateSystem = coordinateSystem;
  34239. this.stereo.update( this.camera );
  34240. }
  34241. setSize( width, height ) {
  34242. super.setSize( width, height );
  34243. this._renderTargetL.setSize( this.renderTarget.width, this.renderTarget.height );
  34244. this._renderTargetR.setSize( this.renderTarget.width, this.renderTarget.height );
  34245. }
  34246. updateBefore( frame ) {
  34247. const { renderer } = frame;
  34248. const { scene, stereo, renderTarget } = this;
  34249. this._pixelRatio = renderer.getPixelRatio();
  34250. this.updateStereoCamera( renderer.coordinateSystem );
  34251. const size = renderer.getSize( _size$1 );
  34252. this.setSize( size.width, size.height );
  34253. const currentRenderTarget = renderer.getRenderTarget();
  34254. // left
  34255. renderer.setRenderTarget( this._renderTargetL );
  34256. renderer.render( scene, stereo.cameraL );
  34257. // right
  34258. renderer.setRenderTarget( this._renderTargetR );
  34259. renderer.render( scene, stereo.cameraR );
  34260. // composite
  34261. renderer.setRenderTarget( renderTarget );
  34262. _quadMesh$1.material = this._material;
  34263. _quadMesh$1.render( renderer );
  34264. // restore
  34265. renderer.setRenderTarget( currentRenderTarget );
  34266. }
  34267. dispose() {
  34268. super.dispose();
  34269. this._renderTargetL.dispose();
  34270. this._renderTargetR.dispose();
  34271. if ( this._material !== null ) {
  34272. this._material.dispose();
  34273. }
  34274. }
  34275. }
  34276. class AnaglyphPassNode extends StereoCompositePassNode {
  34277. static get type() {
  34278. return 'AnaglyphPassNode';
  34279. }
  34280. constructor( scene, camera ) {
  34281. super( scene, camera );
  34282. this.isAnaglyphPassNode = true;
  34283. // Dubois matrices from https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.7.6968&rep=rep1&type=pdf#page=4
  34284. this._colorMatrixLeft = uniform( new Matrix3().fromArray( [
  34285. 0.456100, - 0.0400822, - 0.0152161,
  34286. 0.500484, - 0.0378246, - 0.0205971,
  34287. 0.176381, - 0.0157589, - 0.00546856
  34288. ] ) );
  34289. this._colorMatrixRight = uniform( new Matrix3().fromArray( [
  34290. - 0.0434706, 0.378476, - 0.0721527,
  34291. - 0.0879388, 0.73364, - 0.112961,
  34292. - 0.00155529, - 0.0184503, 1.2264
  34293. ] ) );
  34294. }
  34295. setup( builder ) {
  34296. const uvNode = uv();
  34297. const anaglyph = Fn( () => {
  34298. const colorL = this._mapLeft.uv( uvNode );
  34299. const colorR = this._mapRight.uv( uvNode );
  34300. const color = clamp( this._colorMatrixLeft.mul( colorL.rgb ).add( this._colorMatrixRight.mul( colorR.rgb ) ) );
  34301. return vec4( color.rgb, max$1( colorL.a, colorR.a ) );
  34302. } );
  34303. const material = this._material || ( this._material = new NodeMaterial() );
  34304. material.fragmentNode = anaglyph().context( builder.getSharedContext() );
  34305. material.name = 'Anaglyph';
  34306. material.needsUpdate = true;
  34307. return super.setup( builder );
  34308. }
  34309. }
  34310. const anaglyphPass = ( scene, camera ) => nodeObject( new AnaglyphPassNode( scene, camera ) );
  34311. class ParallaxBarrierPassNode extends StereoCompositePassNode {
  34312. static get type() {
  34313. return 'ParallaxBarrierPassNode';
  34314. }
  34315. constructor( scene, camera ) {
  34316. super( scene, camera );
  34317. this.isParallaxBarrierPassNode = true;
  34318. }
  34319. setup( builder ) {
  34320. const uvNode = uv();
  34321. const parallaxBarrier = Fn( () => {
  34322. const color = vec4().toVar();
  34323. If( mod( viewportCoordinate.y, 2 ).greaterThan( 1 ), () => {
  34324. color.assign( this._mapLeft.uv( uvNode ) );
  34325. } ).Else( () => {
  34326. color.assign( this._mapRight.uv( uvNode ) );
  34327. } );
  34328. return color;
  34329. } );
  34330. const material = this._material || ( this._material = new NodeMaterial() );
  34331. material.fragmentNode = parallaxBarrier().context( builder.getSharedContext() );
  34332. material.needsUpdate = true;
  34333. return super.setup( builder );
  34334. }
  34335. }
  34336. const parallaxBarrierPass = ( scene, camera ) => nodeObject( new ParallaxBarrierPassNode( scene, camera ) );
  34337. class ScriptableValueNode extends Node {
  34338. static get type() {
  34339. return 'ScriptableValueNode';
  34340. }
  34341. constructor( value = null ) {
  34342. super();
  34343. this._value = value;
  34344. this._cache = null;
  34345. this.inputType = null;
  34346. this.outpuType = null;
  34347. this.events = new EventDispatcher();
  34348. this.isScriptableValueNode = true;
  34349. }
  34350. get isScriptableOutputNode() {
  34351. return this.outputType !== null;
  34352. }
  34353. set value( val ) {
  34354. if ( this._value === val ) return;
  34355. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  34356. URL.revokeObjectURL( this._cache );
  34357. this._cache = null;
  34358. }
  34359. this._value = val;
  34360. this.events.dispatchEvent( { type: 'change' } );
  34361. this.refresh();
  34362. }
  34363. get value() {
  34364. return this._value;
  34365. }
  34366. refresh() {
  34367. this.events.dispatchEvent( { type: 'refresh' } );
  34368. }
  34369. getValue() {
  34370. const value = this.value;
  34371. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  34372. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  34373. } else if ( value && value.value !== null && value.value !== undefined && (
  34374. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  34375. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  34376. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  34377. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  34378. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  34379. ( this.inputType === 'Color' && value.value.isColor ) ||
  34380. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  34381. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  34382. ) ) {
  34383. return value.value;
  34384. }
  34385. return this._cache || value;
  34386. }
  34387. getNodeType( builder ) {
  34388. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  34389. }
  34390. setup() {
  34391. return this.value && this.value.isNode ? this.value : float();
  34392. }
  34393. serialize( data ) {
  34394. super.serialize( data );
  34395. if ( this.value !== null ) {
  34396. if ( this.inputType === 'ArrayBuffer' ) {
  34397. data.value = arrayBufferToBase64( this.value );
  34398. } else {
  34399. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  34400. }
  34401. } else {
  34402. data.value = null;
  34403. }
  34404. data.inputType = this.inputType;
  34405. data.outputType = this.outputType;
  34406. }
  34407. deserialize( data ) {
  34408. super.deserialize( data );
  34409. let value = null;
  34410. if ( data.value !== null ) {
  34411. if ( data.inputType === 'ArrayBuffer' ) {
  34412. value = base64ToArrayBuffer( data.value );
  34413. } else if ( data.inputType === 'Texture' ) {
  34414. value = data.meta.textures[ data.value ];
  34415. } else {
  34416. value = data.meta.nodes[ data.value ] || null;
  34417. }
  34418. }
  34419. this.value = value;
  34420. this.inputType = data.inputType;
  34421. this.outputType = data.outputType;
  34422. }
  34423. }
  34424. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  34425. class Resources extends Map {
  34426. get( key, callback = null, ...params ) {
  34427. if ( this.has( key ) ) return super.get( key );
  34428. if ( callback !== null ) {
  34429. const value = callback( ...params );
  34430. this.set( key, value );
  34431. return value;
  34432. }
  34433. }
  34434. }
  34435. class Parameters {
  34436. constructor( scriptableNode ) {
  34437. this.scriptableNode = scriptableNode;
  34438. }
  34439. get parameters() {
  34440. return this.scriptableNode.parameters;
  34441. }
  34442. get layout() {
  34443. return this.scriptableNode.getLayout();
  34444. }
  34445. getInputLayout( id ) {
  34446. return this.scriptableNode.getInputLayout( id );
  34447. }
  34448. get( name ) {
  34449. const param = this.parameters[ name ];
  34450. const value = param ? param.getValue() : null;
  34451. return value;
  34452. }
  34453. }
  34454. const global = new Resources();
  34455. class ScriptableNode extends Node {
  34456. static get type() {
  34457. return 'ScriptableNode';
  34458. }
  34459. constructor( codeNode = null, parameters = {} ) {
  34460. super();
  34461. this.codeNode = codeNode;
  34462. this.parameters = parameters;
  34463. this._local = new Resources();
  34464. this._output = scriptableValue();
  34465. this._outputs = {};
  34466. this._source = this.source;
  34467. this._method = null;
  34468. this._object = null;
  34469. this._value = null;
  34470. this._needsOutputUpdate = true;
  34471. this.onRefresh = this.onRefresh.bind( this );
  34472. this.isScriptableNode = true;
  34473. }
  34474. get source() {
  34475. return this.codeNode ? this.codeNode.code : '';
  34476. }
  34477. setLocal( name, value ) {
  34478. return this._local.set( name, value );
  34479. }
  34480. getLocal( name ) {
  34481. return this._local.get( name );
  34482. }
  34483. onRefresh() {
  34484. this._refresh();
  34485. }
  34486. getInputLayout( id ) {
  34487. for ( const element of this.getLayout() ) {
  34488. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  34489. return element;
  34490. }
  34491. }
  34492. }
  34493. getOutputLayout( id ) {
  34494. for ( const element of this.getLayout() ) {
  34495. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  34496. return element;
  34497. }
  34498. }
  34499. }
  34500. setOutput( name, value ) {
  34501. const outputs = this._outputs;
  34502. if ( outputs[ name ] === undefined ) {
  34503. outputs[ name ] = scriptableValue( value );
  34504. } else {
  34505. outputs[ name ].value = value;
  34506. }
  34507. return this;
  34508. }
  34509. getOutput( name ) {
  34510. return this._outputs[ name ];
  34511. }
  34512. getParameter( name ) {
  34513. return this.parameters[ name ];
  34514. }
  34515. setParameter( name, value ) {
  34516. const parameters = this.parameters;
  34517. if ( value && value.isScriptableNode ) {
  34518. this.deleteParameter( name );
  34519. parameters[ name ] = value;
  34520. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  34521. } else if ( value && value.isScriptableValueNode ) {
  34522. this.deleteParameter( name );
  34523. parameters[ name ] = value;
  34524. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  34525. } else if ( parameters[ name ] === undefined ) {
  34526. parameters[ name ] = scriptableValue( value );
  34527. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  34528. } else {
  34529. parameters[ name ].value = value;
  34530. }
  34531. return this;
  34532. }
  34533. getValue() {
  34534. return this.getDefaultOutput().getValue();
  34535. }
  34536. deleteParameter( name ) {
  34537. let valueNode = this.parameters[ name ];
  34538. if ( valueNode ) {
  34539. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  34540. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  34541. }
  34542. return this;
  34543. }
  34544. clearParameters() {
  34545. for ( const name of Object.keys( this.parameters ) ) {
  34546. this.deleteParameter( name );
  34547. }
  34548. this.needsUpdate = true;
  34549. return this;
  34550. }
  34551. call( name, ...params ) {
  34552. const object = this.getObject();
  34553. const method = object[ name ];
  34554. if ( typeof method === 'function' ) {
  34555. return method( ...params );
  34556. }
  34557. }
  34558. async callAsync( name, ...params ) {
  34559. const object = this.getObject();
  34560. const method = object[ name ];
  34561. if ( typeof method === 'function' ) {
  34562. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  34563. }
  34564. }
  34565. getNodeType( builder ) {
  34566. return this.getDefaultOutputNode().getNodeType( builder );
  34567. }
  34568. refresh( output = null ) {
  34569. if ( output !== null ) {
  34570. this.getOutput( output ).refresh();
  34571. } else {
  34572. this._refresh();
  34573. }
  34574. }
  34575. getObject() {
  34576. if ( this.needsUpdate ) this.dispose();
  34577. if ( this._object !== null ) return this._object;
  34578. //
  34579. const refresh = () => this.refresh();
  34580. const setOutput = ( id, value ) => this.setOutput( id, value );
  34581. const parameters = new Parameters( this );
  34582. const THREE = global.get( 'THREE' );
  34583. const TSL = global.get( 'TSL' );
  34584. const method = this.getMethod( this.codeNode );
  34585. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  34586. this._object = method( ...params );
  34587. const layout = this._object.layout;
  34588. if ( layout ) {
  34589. if ( layout.cache === false ) {
  34590. this._local.clear();
  34591. }
  34592. // default output
  34593. this._output.outputType = layout.outputType || null;
  34594. if ( Array.isArray( layout.elements ) ) {
  34595. for ( const element of layout.elements ) {
  34596. const id = element.id || element.name;
  34597. if ( element.inputType ) {
  34598. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  34599. this.getParameter( id ).inputType = element.inputType;
  34600. }
  34601. if ( element.outputType ) {
  34602. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  34603. this.getOutput( id ).outputType = element.outputType;
  34604. }
  34605. }
  34606. }
  34607. }
  34608. return this._object;
  34609. }
  34610. deserialize( data ) {
  34611. super.deserialize( data );
  34612. for ( const name in this.parameters ) {
  34613. let valueNode = this.parameters[ name ];
  34614. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  34615. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  34616. }
  34617. }
  34618. getLayout() {
  34619. return this.getObject().layout;
  34620. }
  34621. getDefaultOutputNode() {
  34622. const output = this.getDefaultOutput().value;
  34623. if ( output && output.isNode ) {
  34624. return output;
  34625. }
  34626. return float();
  34627. }
  34628. getDefaultOutput() {
  34629. return this._exec()._output;
  34630. }
  34631. getMethod() {
  34632. if ( this.needsUpdate ) this.dispose();
  34633. if ( this._method !== null ) return this._method;
  34634. //
  34635. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  34636. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  34637. const properties = interfaceProps.join( ', ' );
  34638. const declarations = 'var ' + properties + '; var output = {};\n';
  34639. const returns = '\nreturn { ...output, ' + properties + ' };';
  34640. const code = declarations + this.codeNode.code + returns;
  34641. //
  34642. this._method = new Function( ...parametersProps, code );
  34643. return this._method;
  34644. }
  34645. dispose() {
  34646. if ( this._method === null ) return;
  34647. if ( this._object && typeof this._object.dispose === 'function' ) {
  34648. this._object.dispose();
  34649. }
  34650. this._method = null;
  34651. this._object = null;
  34652. this._source = null;
  34653. this._value = null;
  34654. this._needsOutputUpdate = true;
  34655. this._output.value = null;
  34656. this._outputs = {};
  34657. }
  34658. setup() {
  34659. return this.getDefaultOutputNode();
  34660. }
  34661. getCacheKey( force ) {
  34662. const cacheKey = [ this.source, this.getDefaultOutputNode().getCacheKey( force ) ];
  34663. for ( const param in this.parameters ) {
  34664. cacheKey.push( this.parameters[ param ].getCacheKey( force ) );
  34665. }
  34666. return cacheKey.join( ',' );
  34667. }
  34668. set needsUpdate( value ) {
  34669. if ( value === true ) this.dispose();
  34670. }
  34671. get needsUpdate() {
  34672. return this.source !== this._source;
  34673. }
  34674. _exec() {
  34675. if ( this.codeNode === null ) return this;
  34676. if ( this._needsOutputUpdate === true ) {
  34677. this._value = this.call( 'main' );
  34678. this._needsOutputUpdate = false;
  34679. }
  34680. this._output.value = this._value;
  34681. return this;
  34682. }
  34683. _refresh() {
  34684. this.needsUpdate = true;
  34685. this._exec();
  34686. this._output.refresh();
  34687. }
  34688. }
  34689. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  34690. class FogNode extends Node {
  34691. static get type() {
  34692. return 'FogNode';
  34693. }
  34694. constructor( colorNode, factorNode ) {
  34695. super( 'float' );
  34696. this.isFogNode = true;
  34697. this.colorNode = colorNode;
  34698. this.factorNode = factorNode;
  34699. }
  34700. getViewZNode( builder ) {
  34701. let viewZ;
  34702. const getViewZ = builder.context.getViewZ;
  34703. if ( getViewZ !== undefined ) {
  34704. viewZ = getViewZ( this );
  34705. }
  34706. return ( viewZ || positionView.z ).negate();
  34707. }
  34708. setup() {
  34709. return this.factorNode;
  34710. }
  34711. }
  34712. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  34713. class FogRangeNode extends FogNode {
  34714. static get type() {
  34715. return 'FogRangeNode';
  34716. }
  34717. constructor( colorNode, nearNode, farNode ) {
  34718. super( colorNode );
  34719. this.isFogRangeNode = true;
  34720. this.nearNode = nearNode;
  34721. this.farNode = farNode;
  34722. }
  34723. setup( builder ) {
  34724. const viewZ = this.getViewZNode( builder );
  34725. return smoothstep( this.nearNode, this.farNode, viewZ );
  34726. }
  34727. }
  34728. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  34729. class FogExp2Node extends FogNode {
  34730. static get type() {
  34731. return 'FogExp2Node';
  34732. }
  34733. constructor( colorNode, densityNode ) {
  34734. super( colorNode );
  34735. this.isFogExp2Node = true;
  34736. this.densityNode = densityNode;
  34737. }
  34738. setup( builder ) {
  34739. const viewZ = this.getViewZNode( builder );
  34740. const density = this.densityNode;
  34741. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  34742. }
  34743. }
  34744. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  34745. let min = null;
  34746. let max = null;
  34747. class RangeNode extends Node {
  34748. static get type() {
  34749. return 'RangeNode';
  34750. }
  34751. constructor( minNode = float(), maxNode = float() ) {
  34752. super();
  34753. this.minNode = minNode;
  34754. this.maxNode = maxNode;
  34755. }
  34756. getVectorLength( builder ) {
  34757. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  34758. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  34759. return minLength > maxLength ? minLength : maxLength;
  34760. }
  34761. getNodeType( builder ) {
  34762. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  34763. }
  34764. setup( builder ) {
  34765. const object = builder.object;
  34766. let output = null;
  34767. if ( object.count > 1 ) {
  34768. const minValue = this.minNode.value;
  34769. const maxValue = this.maxNode.value;
  34770. const minLength = builder.getTypeLength( getValueType( minValue ) );
  34771. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  34772. min = min || new Vector4();
  34773. max = max || new Vector4();
  34774. min.setScalar( 0 );
  34775. max.setScalar( 0 );
  34776. if ( minLength === 1 ) min.setScalar( minValue );
  34777. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  34778. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  34779. if ( maxLength === 1 ) max.setScalar( maxValue );
  34780. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  34781. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  34782. const stride = 4;
  34783. const length = stride * object.count;
  34784. const array = new Float32Array( length );
  34785. for ( let i = 0; i < length; i ++ ) {
  34786. const index = i % stride;
  34787. const minElementValue = min.getComponent( index );
  34788. const maxElementValue = max.getComponent( index );
  34789. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  34790. }
  34791. const nodeType = this.getNodeType( builder );
  34792. if ( object.count <= 4096 ) {
  34793. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  34794. } else {
  34795. // TODO: Improve anonymous buffer attribute creation removing this part
  34796. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  34797. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  34798. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  34799. }
  34800. } else {
  34801. output = float( 0 );
  34802. }
  34803. return output;
  34804. }
  34805. }
  34806. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  34807. class LightNode extends Node {
  34808. static get type() {
  34809. return 'LightNode';
  34810. }
  34811. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  34812. super();
  34813. this.scope = scope;
  34814. this.light = light;
  34815. }
  34816. setup() {
  34817. const { scope, light } = this;
  34818. let output = null;
  34819. if ( scope === LightNode.TARGET_DIRECTION ) {
  34820. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  34821. }
  34822. return output;
  34823. }
  34824. serialize( data ) {
  34825. super.serialize( data );
  34826. data.scope = this.scope;
  34827. }
  34828. deserialize( data ) {
  34829. super.deserialize( data );
  34830. this.scope = data.scope;
  34831. }
  34832. }
  34833. LightNode.TARGET_DIRECTION = 'targetDirection';
  34834. const lightTargetDirection = /*@__PURE__*/ nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  34835. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  34836. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  34837. } );
  34838. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  34839. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  34840. const mapSize = reference( 'mapSize', 'vec2', shadow );
  34841. const radius = reference( 'radius', 'float', shadow );
  34842. const texelSize = vec2( 1 ).div( mapSize );
  34843. const dx0 = texelSize.x.negate().mul( radius );
  34844. const dy0 = texelSize.y.negate().mul( radius );
  34845. const dx1 = texelSize.x.mul( radius );
  34846. const dy1 = texelSize.y.mul( radius );
  34847. const dx2 = dx0.div( 2 );
  34848. const dy2 = dy0.div( 2 );
  34849. const dx3 = dx1.div( 2 );
  34850. const dy3 = dy1.div( 2 );
  34851. return add(
  34852. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  34853. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  34854. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  34855. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  34856. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  34857. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  34858. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  34859. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  34860. depthCompare( shadowCoord.xy, shadowCoord.z ),
  34861. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  34862. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  34863. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  34864. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  34865. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  34866. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  34867. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  34868. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  34869. ).mul( 1 / 17 );
  34870. } );
  34871. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  34872. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  34873. const mapSize = reference( 'mapSize', 'vec2', shadow );
  34874. const texelSize = vec2( 1 ).div( mapSize );
  34875. const dx = texelSize.x;
  34876. const dy = texelSize.y;
  34877. const uv = shadowCoord.xy;
  34878. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  34879. uv.subAssign( f.mul( texelSize ) );
  34880. return add(
  34881. depthCompare( uv, shadowCoord.z ),
  34882. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  34883. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  34884. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  34885. mix(
  34886. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  34887. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  34888. f.x
  34889. ),
  34890. mix(
  34891. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  34892. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  34893. f.x
  34894. ),
  34895. mix(
  34896. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  34897. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  34898. f.y
  34899. ),
  34900. mix(
  34901. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  34902. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  34903. f.y
  34904. ),
  34905. mix(
  34906. mix(
  34907. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  34908. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  34909. f.x
  34910. ),
  34911. mix(
  34912. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  34913. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  34914. f.x
  34915. ),
  34916. f.y
  34917. )
  34918. ).mul( 1 / 9 );
  34919. } );
  34920. const shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap ];
  34921. //
  34922. let overrideMaterial = null;
  34923. class AnalyticLightNode extends LightingNode {
  34924. static get type() {
  34925. return 'AnalyticLightNode';
  34926. }
  34927. constructor( light = null ) {
  34928. super();
  34929. this.updateType = NodeUpdateType.FRAME;
  34930. this.light = light;
  34931. this.color = new Color();
  34932. this.colorNode = uniform( this.color );
  34933. this.baseColorNode = null;
  34934. this.shadowMap = null;
  34935. this.shadowNode = null;
  34936. this.shadowColorNode = null;
  34937. this.isAnalyticLightNode = true;
  34938. }
  34939. getCacheKey() {
  34940. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  34941. }
  34942. getHash() {
  34943. return this.light.uuid;
  34944. }
  34945. setupShadow( builder ) {
  34946. const { object, renderer } = builder;
  34947. let shadowColorNode = this.shadowColorNode;
  34948. if ( shadowColorNode === null ) {
  34949. if ( overrideMaterial === null ) {
  34950. overrideMaterial = new NodeMaterial();
  34951. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  34952. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  34953. overrideMaterial.name = 'ShadowMaterial';
  34954. }
  34955. const depthTexture = new DepthTexture();
  34956. depthTexture.compareFunction = LessCompare;
  34957. const shadow = this.light.shadow;
  34958. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  34959. shadowMap.depthTexture = depthTexture;
  34960. shadow.camera.updateProjectionMatrix();
  34961. //
  34962. const shadowIntensity = reference( 'intensity', 'float', shadow );
  34963. const bias = reference( 'bias', 'float', shadow );
  34964. const normalBias = reference( 'normalBias', 'float', shadow );
  34965. const position = object.material.shadowPositionNode || positionWorld;
  34966. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  34967. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  34968. let coordZ = shadowCoord.z.add( bias );
  34969. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  34970. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  34971. }
  34972. shadowCoord = vec3(
  34973. shadowCoord.x,
  34974. shadowCoord.y.oneMinus(), // follow webgpu standards
  34975. coordZ
  34976. );
  34977. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  34978. .and( shadowCoord.x.lessThanEqual( 1 ) )
  34979. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  34980. .and( shadowCoord.y.lessThanEqual( 1 ) )
  34981. .and( shadowCoord.z.lessThanEqual( 1 ) );
  34982. //
  34983. const filterFn = shadow.filterNode || shadowFilterLib[ renderer.shadowMap.type ] || null;
  34984. if ( filterFn === null ) {
  34985. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  34986. }
  34987. const shadowColor = texture( shadowMap.texture, shadowCoord );
  34988. const shadowNode = frustumTest.select( filterFn( { depthTexture, shadowCoord, shadow } ), float( 1 ) );
  34989. this.shadowMap = shadowMap;
  34990. this.shadowNode = shadowNode;
  34991. this.shadowColorNode = shadowColorNode = this.colorNode.mul( mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ) );
  34992. this.baseColorNode = this.colorNode;
  34993. }
  34994. //
  34995. this.colorNode = shadowColorNode;
  34996. this.updateBeforeType = NodeUpdateType.RENDER;
  34997. }
  34998. setup( builder ) {
  34999. this.colorNode = this.baseColorNode || this.colorNode;
  35000. if ( this.light.castShadow ) {
  35001. if ( builder.object.receiveShadow ) {
  35002. this.setupShadow( builder );
  35003. }
  35004. } else if ( this.shadowNode !== null ) {
  35005. this.disposeShadow();
  35006. }
  35007. }
  35008. updateShadow( frame ) {
  35009. const { shadowMap, light } = this;
  35010. const { renderer, scene, camera } = frame;
  35011. const depthVersion = shadowMap.depthTexture.version;
  35012. this._depthVersionCached = depthVersion;
  35013. const currentOverrideMaterial = scene.overrideMaterial;
  35014. scene.overrideMaterial = overrideMaterial;
  35015. shadowMap.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  35016. light.shadow.updateMatrices( light );
  35017. light.shadow.camera.layers.mask = camera.layers.mask;
  35018. const currentRenderTarget = renderer.getRenderTarget();
  35019. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  35020. renderer.setRenderObjectFunction( ( object, ...params ) => {
  35021. if ( object.castShadow === true ) {
  35022. renderer.renderObject( object, ...params );
  35023. }
  35024. } );
  35025. renderer.setRenderTarget( shadowMap );
  35026. renderer.render( scene, light.shadow.camera );
  35027. renderer.setRenderTarget( currentRenderTarget );
  35028. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  35029. scene.overrideMaterial = currentOverrideMaterial;
  35030. }
  35031. disposeShadow() {
  35032. this.shadowMap.dispose();
  35033. this.shadowMap = null;
  35034. this.shadowNode = null;
  35035. this.shadowColorNode = null;
  35036. this.baseColorNode = null;
  35037. this.updateBeforeType = NodeUpdateType.NONE;
  35038. }
  35039. updateBefore( frame ) {
  35040. const shadow = this.light.shadow;
  35041. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  35042. if ( needsUpdate ) {
  35043. this.updateShadow( frame );
  35044. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  35045. shadow.needsUpdate = false;
  35046. }
  35047. }
  35048. }
  35049. update( /*frame*/ ) {
  35050. const { light } = this;
  35051. this.color.copy( light.color ).multiplyScalar( light.intensity );
  35052. }
  35053. }
  35054. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  35055. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  35056. // based upon Frostbite 3 Moving to Physically-based Rendering
  35057. // page 32, equation 26: E[window1]
  35058. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  35059. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  35060. return cutoffDistance.greaterThan( 0 ).select(
  35061. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  35062. distanceFalloff
  35063. );
  35064. } ); // validated
  35065. class PointLightNode extends AnalyticLightNode {
  35066. static get type() {
  35067. return 'PointLightNode';
  35068. }
  35069. constructor( light = null ) {
  35070. super( light );
  35071. this.cutoffDistanceNode = uniform( 0 );
  35072. this.decayExponentNode = uniform( 0 );
  35073. }
  35074. update( frame ) {
  35075. const { light } = this;
  35076. super.update( frame );
  35077. this.cutoffDistanceNode.value = light.distance;
  35078. this.decayExponentNode.value = light.decay;
  35079. }
  35080. setup( builder ) {
  35081. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  35082. const lightingModel = builder.context.lightingModel;
  35083. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  35084. const lightDirection = lVector.normalize();
  35085. const lightDistance = lVector.length();
  35086. const lightAttenuation = getDistanceAttenuation( {
  35087. lightDistance,
  35088. cutoffDistance: cutoffDistanceNode,
  35089. decayExponent: decayExponentNode
  35090. } );
  35091. const lightColor = colorNode.mul( lightAttenuation );
  35092. const reflectedLight = builder.context.reflectedLight;
  35093. lightingModel.direct( {
  35094. lightDirection,
  35095. lightColor,
  35096. reflectedLight
  35097. }, builder.stack, builder );
  35098. }
  35099. }
  35100. class DirectionalLightNode extends AnalyticLightNode {
  35101. static get type() {
  35102. return 'DirectionalLightNode';
  35103. }
  35104. constructor( light = null ) {
  35105. super( light );
  35106. }
  35107. setup( builder ) {
  35108. super.setup( builder );
  35109. const lightingModel = builder.context.lightingModel;
  35110. const lightColor = this.colorNode;
  35111. const lightDirection = lightTargetDirection( this.light );
  35112. const reflectedLight = builder.context.reflectedLight;
  35113. lightingModel.direct( {
  35114. lightDirection,
  35115. lightColor,
  35116. reflectedLight
  35117. }, builder.stack, builder );
  35118. }
  35119. }
  35120. const _matrix41 = /*@__PURE__*/ new Matrix4();
  35121. const _matrix42 = /*@__PURE__*/ new Matrix4();
  35122. let ltcLib = null;
  35123. class RectAreaLightNode extends AnalyticLightNode {
  35124. static get type() {
  35125. return 'RectAreaLightNode';
  35126. }
  35127. constructor( light = null ) {
  35128. super( light );
  35129. this.halfHeight = uniform( new Vector3() );
  35130. this.halfWidth = uniform( new Vector3() );
  35131. }
  35132. update( frame ) {
  35133. super.update( frame );
  35134. const { light } = this;
  35135. const viewMatrix = frame.camera.matrixWorldInverse;
  35136. _matrix42.identity();
  35137. _matrix41.copy( light.matrixWorld );
  35138. _matrix41.premultiply( viewMatrix );
  35139. _matrix42.extractRotation( _matrix41 );
  35140. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  35141. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  35142. this.halfWidth.value.applyMatrix4( _matrix42 );
  35143. this.halfHeight.value.applyMatrix4( _matrix42 );
  35144. }
  35145. setup( builder ) {
  35146. super.setup( builder );
  35147. let ltc_1, ltc_2;
  35148. if ( builder.isAvailable( 'float32Filterable' ) ) {
  35149. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  35150. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  35151. } else {
  35152. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  35153. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  35154. }
  35155. const { colorNode, light } = this;
  35156. const lightingModel = builder.context.lightingModel;
  35157. const lightPosition = objectViewPosition( light );
  35158. const reflectedLight = builder.context.reflectedLight;
  35159. lightingModel.directRectArea( {
  35160. lightColor: colorNode,
  35161. lightPosition,
  35162. halfWidth: this.halfWidth,
  35163. halfHeight: this.halfHeight,
  35164. reflectedLight,
  35165. ltc_1,
  35166. ltc_2
  35167. }, builder.stack, builder );
  35168. }
  35169. static setLTC( ltc ) {
  35170. ltcLib = ltc;
  35171. }
  35172. }
  35173. class SpotLightNode extends AnalyticLightNode {
  35174. static get type() {
  35175. return 'SpotLightNode';
  35176. }
  35177. constructor( light = null ) {
  35178. super( light );
  35179. this.coneCosNode = uniform( 0 );
  35180. this.penumbraCosNode = uniform( 0 );
  35181. this.cutoffDistanceNode = uniform( 0 );
  35182. this.decayExponentNode = uniform( 0 );
  35183. }
  35184. update( frame ) {
  35185. super.update( frame );
  35186. const { light } = this;
  35187. this.coneCosNode.value = Math.cos( light.angle );
  35188. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  35189. this.cutoffDistanceNode.value = light.distance;
  35190. this.decayExponentNode.value = light.decay;
  35191. }
  35192. getSpotAttenuation( angleCosine ) {
  35193. const { coneCosNode, penumbraCosNode } = this;
  35194. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  35195. }
  35196. setup( builder ) {
  35197. super.setup( builder );
  35198. const lightingModel = builder.context.lightingModel;
  35199. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  35200. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  35201. const lightDirection = lVector.normalize();
  35202. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  35203. const spotAttenuation = this.getSpotAttenuation( angleCos );
  35204. const lightDistance = lVector.length();
  35205. const lightAttenuation = getDistanceAttenuation( {
  35206. lightDistance,
  35207. cutoffDistance: cutoffDistanceNode,
  35208. decayExponent: decayExponentNode
  35209. } );
  35210. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  35211. const reflectedLight = builder.context.reflectedLight;
  35212. lightingModel.direct( {
  35213. lightDirection,
  35214. lightColor,
  35215. reflectedLight
  35216. }, builder.stack, builder );
  35217. }
  35218. }
  35219. class IESSpotLightNode extends SpotLightNode {
  35220. static get type() {
  35221. return 'IESSpotLightNode';
  35222. }
  35223. getSpotAttenuation( angleCosine ) {
  35224. const iesMap = this.light.iesMap;
  35225. let spotAttenuation = null;
  35226. if ( iesMap && iesMap.isTexture === true ) {
  35227. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  35228. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  35229. } else {
  35230. spotAttenuation = super.getSpotAttenuation( angleCosine );
  35231. }
  35232. return spotAttenuation;
  35233. }
  35234. }
  35235. class AmbientLightNode extends AnalyticLightNode {
  35236. static get type() {
  35237. return 'AmbientLightNode';
  35238. }
  35239. constructor( light = null ) {
  35240. super( light );
  35241. }
  35242. setup( { context } ) {
  35243. context.irradiance.addAssign( this.colorNode );
  35244. }
  35245. }
  35246. class HemisphereLightNode extends AnalyticLightNode {
  35247. static get type() {
  35248. return 'HemisphereLightNode';
  35249. }
  35250. constructor( light = null ) {
  35251. super( light );
  35252. this.lightPositionNode = objectPosition( light );
  35253. this.lightDirectionNode = this.lightPositionNode.normalize();
  35254. this.groundColorNode = uniform( new Color() );
  35255. }
  35256. update( frame ) {
  35257. const { light } = this;
  35258. super.update( frame );
  35259. this.lightPositionNode.object3d = light;
  35260. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  35261. }
  35262. setup( builder ) {
  35263. const { colorNode, groundColorNode, lightDirectionNode } = this;
  35264. const dotNL = normalView.dot( lightDirectionNode );
  35265. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  35266. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  35267. builder.context.irradiance.addAssign( irradiance );
  35268. }
  35269. }
  35270. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  35271. // normal is assumed to have unit length
  35272. const x = normal.x, y = normal.y, z = normal.z;
  35273. // band 0
  35274. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  35275. // band 1
  35276. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  35277. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  35278. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  35279. // band 2
  35280. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  35281. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  35282. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  35283. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  35284. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  35285. return result;
  35286. } );
  35287. class LightProbeNode extends AnalyticLightNode {
  35288. static get type() {
  35289. return 'LightProbeNode';
  35290. }
  35291. constructor( light = null ) {
  35292. super( light );
  35293. const array = [];
  35294. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  35295. this.lightProbe = uniformArray( array );
  35296. }
  35297. update( frame ) {
  35298. const { light } = this;
  35299. super.update( frame );
  35300. //
  35301. for ( let i = 0; i < 9; i ++ ) {
  35302. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  35303. }
  35304. }
  35305. setup( builder ) {
  35306. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  35307. builder.context.irradiance.addAssign( irradiance );
  35308. }
  35309. }
  35310. class NodeParser {
  35311. parseFunction( /*source*/ ) {
  35312. console.warn( 'Abstract function.' );
  35313. }
  35314. }
  35315. class NodeFunction {
  35316. constructor( type, inputs, name = '', precision = '' ) {
  35317. this.type = type;
  35318. this.inputs = inputs;
  35319. this.name = name;
  35320. this.precision = precision;
  35321. }
  35322. getCode( /*name = this.name*/ ) {
  35323. console.warn( 'Abstract function.' );
  35324. }
  35325. }
  35326. NodeFunction.isNodeFunction = true;
  35327. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  35328. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  35329. const pragmaMain = '#pragma main';
  35330. const parse$1 = ( source ) => {
  35331. source = source.trim();
  35332. const pragmaMainIndex = source.indexOf( pragmaMain );
  35333. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  35334. const declaration = mainCode.match( declarationRegexp$1 );
  35335. if ( declaration !== null && declaration.length === 5 ) {
  35336. // tokenizer
  35337. const inputsCode = declaration[ 4 ];
  35338. const propsMatches = [];
  35339. let nameMatch = null;
  35340. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  35341. propsMatches.push( nameMatch );
  35342. }
  35343. // parser
  35344. const inputs = [];
  35345. let i = 0;
  35346. while ( i < propsMatches.length ) {
  35347. const isConst = propsMatches[ i ][ 0 ] === 'const';
  35348. if ( isConst === true ) {
  35349. i ++;
  35350. }
  35351. let qualifier = propsMatches[ i ][ 0 ];
  35352. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  35353. i ++;
  35354. } else {
  35355. qualifier = '';
  35356. }
  35357. const type = propsMatches[ i ++ ][ 0 ];
  35358. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  35359. if ( Number.isNaN( count ) === false ) i ++;
  35360. else count = null;
  35361. const name = propsMatches[ i ++ ][ 0 ];
  35362. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  35363. }
  35364. //
  35365. const blockCode = mainCode.substring( declaration[ 0 ].length );
  35366. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  35367. const type = declaration[ 2 ];
  35368. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  35369. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  35370. return {
  35371. type,
  35372. inputs,
  35373. name,
  35374. precision,
  35375. inputsCode,
  35376. blockCode,
  35377. headerCode
  35378. };
  35379. } else {
  35380. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  35381. }
  35382. };
  35383. class GLSLNodeFunction extends NodeFunction {
  35384. constructor( source ) {
  35385. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  35386. super( type, inputs, name, precision );
  35387. this.inputsCode = inputsCode;
  35388. this.blockCode = blockCode;
  35389. this.headerCode = headerCode;
  35390. }
  35391. getCode( name = this.name ) {
  35392. let code;
  35393. const blockCode = this.blockCode;
  35394. if ( blockCode !== '' ) {
  35395. const { type, inputsCode, headerCode, precision } = this;
  35396. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  35397. if ( precision !== '' ) {
  35398. declarationCode = `${ precision } ${ declarationCode }`;
  35399. }
  35400. code = headerCode + declarationCode + blockCode;
  35401. } else {
  35402. // interface function
  35403. code = '';
  35404. }
  35405. return code;
  35406. }
  35407. }
  35408. class GLSLNodeParser extends NodeParser {
  35409. parseFunction( source ) {
  35410. return new GLSLNodeFunction( source );
  35411. }
  35412. }
  35413. function painterSortStable( a, b ) {
  35414. if ( a.groupOrder !== b.groupOrder ) {
  35415. return a.groupOrder - b.groupOrder;
  35416. } else if ( a.renderOrder !== b.renderOrder ) {
  35417. return a.renderOrder - b.renderOrder;
  35418. } else if ( a.material.id !== b.material.id ) {
  35419. return a.material.id - b.material.id;
  35420. } else if ( a.z !== b.z ) {
  35421. return a.z - b.z;
  35422. } else {
  35423. return a.id - b.id;
  35424. }
  35425. }
  35426. function reversePainterSortStable( a, b ) {
  35427. if ( a.groupOrder !== b.groupOrder ) {
  35428. return a.groupOrder - b.groupOrder;
  35429. } else if ( a.renderOrder !== b.renderOrder ) {
  35430. return a.renderOrder - b.renderOrder;
  35431. } else if ( a.z !== b.z ) {
  35432. return b.z - a.z;
  35433. } else {
  35434. return a.id - b.id;
  35435. }
  35436. }
  35437. class RenderList {
  35438. constructor() {
  35439. this.renderItems = [];
  35440. this.renderItemsIndex = 0;
  35441. this.opaque = [];
  35442. this.transparent = [];
  35443. this.bundles = [];
  35444. this.lightsNode = new LightsNode( [] );
  35445. this.lightsArray = [];
  35446. this.occlusionQueryCount = 0;
  35447. }
  35448. begin() {
  35449. this.renderItemsIndex = 0;
  35450. this.opaque.length = 0;
  35451. this.transparent.length = 0;
  35452. this.bundles.length = 0;
  35453. this.lightsArray.length = 0;
  35454. this.occlusionQueryCount = 0;
  35455. return this;
  35456. }
  35457. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  35458. let renderItem = this.renderItems[ this.renderItemsIndex ];
  35459. if ( renderItem === undefined ) {
  35460. renderItem = {
  35461. id: object.id,
  35462. object: object,
  35463. geometry: geometry,
  35464. material: material,
  35465. groupOrder: groupOrder,
  35466. renderOrder: object.renderOrder,
  35467. z: z,
  35468. group: group
  35469. };
  35470. this.renderItems[ this.renderItemsIndex ] = renderItem;
  35471. } else {
  35472. renderItem.id = object.id;
  35473. renderItem.object = object;
  35474. renderItem.geometry = geometry;
  35475. renderItem.material = material;
  35476. renderItem.groupOrder = groupOrder;
  35477. renderItem.renderOrder = object.renderOrder;
  35478. renderItem.z = z;
  35479. renderItem.group = group;
  35480. }
  35481. this.renderItemsIndex ++;
  35482. return renderItem;
  35483. }
  35484. push( object, geometry, material, groupOrder, z, group ) {
  35485. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  35486. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  35487. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  35488. }
  35489. unshift( object, geometry, material, groupOrder, z, group ) {
  35490. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  35491. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  35492. }
  35493. pushBundle( group ) {
  35494. this.bundles.push( group );
  35495. }
  35496. pushLight( light ) {
  35497. this.lightsArray.push( light );
  35498. }
  35499. getLightsNode() {
  35500. return this.lightsNode.fromLights( this.lightsArray );
  35501. }
  35502. sort( customOpaqueSort, customTransparentSort ) {
  35503. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  35504. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  35505. }
  35506. finish() {
  35507. // update lights
  35508. this.lightsNode.setLights( this.lightsArray );
  35509. // Clear references from inactive renderItems in the list
  35510. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  35511. const renderItem = this.renderItems[ i ];
  35512. if ( renderItem.id === null ) break;
  35513. renderItem.id = null;
  35514. renderItem.object = null;
  35515. renderItem.geometry = null;
  35516. renderItem.material = null;
  35517. renderItem.groupOrder = null;
  35518. renderItem.renderOrder = null;
  35519. renderItem.z = null;
  35520. renderItem.group = null;
  35521. }
  35522. }
  35523. }
  35524. class RenderLists {
  35525. constructor() {
  35526. this.lists = new ChainMap();
  35527. }
  35528. get( scene, camera ) {
  35529. const lists = this.lists;
  35530. const keys = [ scene, camera ];
  35531. let list = lists.get( keys );
  35532. if ( list === undefined ) {
  35533. list = new RenderList();
  35534. lists.set( keys, list );
  35535. }
  35536. return list;
  35537. }
  35538. dispose() {
  35539. this.lists = new ChainMap();
  35540. }
  35541. }
  35542. let id = 0;
  35543. class RenderContext {
  35544. constructor() {
  35545. this.id = id ++;
  35546. this.color = true;
  35547. this.clearColor = true;
  35548. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  35549. this.depth = true;
  35550. this.clearDepth = true;
  35551. this.clearDepthValue = 1;
  35552. this.stencil = false;
  35553. this.clearStencil = true;
  35554. this.clearStencilValue = 1;
  35555. this.viewport = false;
  35556. this.viewportValue = new Vector4();
  35557. this.scissor = false;
  35558. this.scissorValue = new Vector4();
  35559. this.textures = null;
  35560. this.depthTexture = null;
  35561. this.activeCubeFace = 0;
  35562. this.sampleCount = 1;
  35563. this.width = 0;
  35564. this.height = 0;
  35565. this.isRenderContext = true;
  35566. }
  35567. getCacheKey() {
  35568. return getCacheKey( this );
  35569. }
  35570. }
  35571. function getCacheKey( renderContext ) {
  35572. const { textures, activeCubeFace } = renderContext;
  35573. let key = '';
  35574. for ( const texture of textures ) {
  35575. key += texture.id + ',';
  35576. }
  35577. key += activeCubeFace;
  35578. return key;
  35579. }
  35580. class RenderContexts {
  35581. constructor() {
  35582. this.chainMaps = {};
  35583. }
  35584. get( scene, camera, renderTarget = null ) {
  35585. const chainKey = [ scene, camera ];
  35586. let attachmentState;
  35587. if ( renderTarget === null ) {
  35588. attachmentState = 'default';
  35589. } else {
  35590. const format = renderTarget.texture.format;
  35591. const count = renderTarget.textures.length;
  35592. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  35593. }
  35594. const chainMap = this.getChainMap( attachmentState );
  35595. let renderState = chainMap.get( chainKey );
  35596. if ( renderState === undefined ) {
  35597. renderState = new RenderContext();
  35598. chainMap.set( chainKey, renderState );
  35599. }
  35600. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  35601. return renderState;
  35602. }
  35603. getChainMap( attachmentState ) {
  35604. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  35605. }
  35606. dispose() {
  35607. this.chainMaps = {};
  35608. }
  35609. }
  35610. const _size = /*@__PURE__*/ new Vector3();
  35611. class Textures extends DataMap {
  35612. constructor( renderer, backend, info ) {
  35613. super();
  35614. this.renderer = renderer;
  35615. this.backend = backend;
  35616. this.info = info;
  35617. }
  35618. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  35619. const renderTargetData = this.get( renderTarget );
  35620. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  35621. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  35622. const textures = renderTarget.textures;
  35623. const size = this.getSize( textures[ 0 ] );
  35624. const mipWidth = size.width >> activeMipmapLevel;
  35625. const mipHeight = size.height >> activeMipmapLevel;
  35626. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  35627. let textureNeedsUpdate = false;
  35628. if ( depthTexture === undefined ) {
  35629. depthTexture = new DepthTexture();
  35630. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  35631. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  35632. depthTexture.image.width = mipWidth;
  35633. depthTexture.image.height = mipHeight;
  35634. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  35635. }
  35636. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  35637. textureNeedsUpdate = true;
  35638. depthTexture.needsUpdate = true;
  35639. depthTexture.image.width = mipWidth;
  35640. depthTexture.image.height = mipHeight;
  35641. }
  35642. renderTargetData.width = size.width;
  35643. renderTargetData.height = size.height;
  35644. renderTargetData.textures = textures;
  35645. renderTargetData.depthTexture = depthTexture;
  35646. renderTargetData.depth = renderTarget.depthBuffer;
  35647. renderTargetData.stencil = renderTarget.stencilBuffer;
  35648. renderTargetData.renderTarget = renderTarget;
  35649. if ( renderTargetData.sampleCount !== sampleCount ) {
  35650. textureNeedsUpdate = true;
  35651. depthTexture.needsUpdate = true;
  35652. renderTargetData.sampleCount = sampleCount;
  35653. }
  35654. //
  35655. const options = { sampleCount };
  35656. for ( let i = 0; i < textures.length; i ++ ) {
  35657. const texture = textures[ i ];
  35658. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  35659. this.updateTexture( texture, options );
  35660. }
  35661. this.updateTexture( depthTexture, options );
  35662. // dispose handler
  35663. if ( renderTargetData.initialized !== true ) {
  35664. renderTargetData.initialized = true;
  35665. // dispose
  35666. const onDispose = () => {
  35667. renderTarget.removeEventListener( 'dispose', onDispose );
  35668. for ( let i = 0; i < textures.length; i ++ ) {
  35669. this._destroyTexture( textures[ i ] );
  35670. }
  35671. this._destroyTexture( depthTexture );
  35672. this.delete( renderTarget );
  35673. };
  35674. renderTarget.addEventListener( 'dispose', onDispose );
  35675. }
  35676. }
  35677. updateTexture( texture, options = {} ) {
  35678. const textureData = this.get( texture );
  35679. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  35680. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  35681. const backend = this.backend;
  35682. if ( isRenderTarget && textureData.initialized === true ) {
  35683. // it's an update
  35684. backend.destroySampler( texture );
  35685. backend.destroyTexture( texture );
  35686. }
  35687. //
  35688. if ( texture.isFramebufferTexture ) {
  35689. const renderer = this.renderer;
  35690. const renderTarget = renderer.getRenderTarget();
  35691. if ( renderTarget ) {
  35692. texture.type = renderTarget.texture.type;
  35693. } else {
  35694. texture.type = UnsignedByteType;
  35695. }
  35696. }
  35697. //
  35698. const { width, height, depth } = this.getSize( texture );
  35699. options.width = width;
  35700. options.height = height;
  35701. options.depth = depth;
  35702. options.needsMipmaps = this.needsMipmaps( texture );
  35703. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  35704. //
  35705. if ( isRenderTarget || texture.isStorageTexture === true ) {
  35706. backend.createSampler( texture );
  35707. backend.createTexture( texture, options );
  35708. textureData.generation = texture.version;
  35709. } else {
  35710. const needsCreate = textureData.initialized !== true;
  35711. if ( needsCreate ) backend.createSampler( texture );
  35712. if ( texture.version > 0 ) {
  35713. const image = texture.image;
  35714. if ( image === undefined ) {
  35715. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  35716. } else if ( image.complete === false ) {
  35717. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  35718. } else {
  35719. if ( texture.images ) {
  35720. const images = [];
  35721. for ( const image of texture.images ) {
  35722. images.push( image );
  35723. }
  35724. options.images = images;
  35725. } else {
  35726. options.image = image;
  35727. }
  35728. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  35729. backend.createTexture( texture, options );
  35730. textureData.isDefaultTexture = false;
  35731. textureData.generation = texture.version;
  35732. }
  35733. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  35734. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  35735. }
  35736. } else {
  35737. // async update
  35738. backend.createDefaultTexture( texture );
  35739. textureData.isDefaultTexture = true;
  35740. textureData.generation = texture.version;
  35741. }
  35742. }
  35743. // dispose handler
  35744. if ( textureData.initialized !== true ) {
  35745. textureData.initialized = true;
  35746. textureData.generation = texture.version;
  35747. //
  35748. this.info.memory.textures ++;
  35749. // dispose
  35750. const onDispose = () => {
  35751. texture.removeEventListener( 'dispose', onDispose );
  35752. this._destroyTexture( texture );
  35753. this.info.memory.textures --;
  35754. };
  35755. texture.addEventListener( 'dispose', onDispose );
  35756. }
  35757. //
  35758. textureData.version = texture.version;
  35759. }
  35760. getSize( texture, target = _size ) {
  35761. let image = texture.images ? texture.images[ 0 ] : texture.image;
  35762. if ( image ) {
  35763. if ( image.image !== undefined ) image = image.image;
  35764. target.width = image.width;
  35765. target.height = image.height;
  35766. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  35767. } else {
  35768. target.width = target.height = target.depth = 1;
  35769. }
  35770. return target;
  35771. }
  35772. getMipLevels( texture, width, height ) {
  35773. let mipLevelCount;
  35774. if ( texture.isCompressedTexture ) {
  35775. mipLevelCount = texture.mipmaps.length;
  35776. } else {
  35777. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  35778. }
  35779. return mipLevelCount;
  35780. }
  35781. needsMipmaps( texture ) {
  35782. if ( this.isEnvironmentTexture( texture ) ) return true;
  35783. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  35784. }
  35785. isEnvironmentTexture( texture ) {
  35786. const mapping = texture.mapping;
  35787. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  35788. }
  35789. _destroyTexture( texture ) {
  35790. this.backend.destroySampler( texture );
  35791. this.backend.destroyTexture( texture );
  35792. this.delete( texture );
  35793. }
  35794. }
  35795. class Color4 extends Color {
  35796. constructor( r, g, b, a = 1 ) {
  35797. super( r, g, b );
  35798. this.a = a;
  35799. }
  35800. set( r, g, b, a = 1 ) {
  35801. this.a = a;
  35802. return super.set( r, g, b );
  35803. }
  35804. copy( color ) {
  35805. if ( color.a !== undefined ) this.a = color.a;
  35806. return super.copy( color );
  35807. }
  35808. clone() {
  35809. return new this.constructor( this.r, this.g, this.b, this.a );
  35810. }
  35811. }
  35812. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  35813. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  35814. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  35815. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  35816. const result = word.shiftRight( 22 ).bitXor( word );
  35817. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  35818. } );
  35819. // remapping functions https://iquilezles.org/articles/functions/
  35820. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  35821. 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 ) );
  35822. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  35823. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  35824. // https://github.com/cabbibo/glsl-tri-noise-3d
  35825. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  35826. return x.fract().sub( .5 ).abs();
  35827. } ).setLayout( {
  35828. name: 'tri',
  35829. type: 'float',
  35830. inputs: [
  35831. { name: 'x', type: 'float' }
  35832. ]
  35833. } );
  35834. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  35835. 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. ) ) ) ) );
  35836. } ).setLayout( {
  35837. name: 'tri3',
  35838. type: 'vec3',
  35839. inputs: [
  35840. { name: 'p', type: 'vec3' }
  35841. ]
  35842. } );
  35843. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  35844. const p = vec3( p_immutable ).toVar();
  35845. const z = float( 1.4 ).toVar();
  35846. const rz = float( 0.0 ).toVar();
  35847. const bp = vec3( p ).toVar();
  35848. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  35849. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  35850. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  35851. bp.mulAssign( 1.8 );
  35852. z.mulAssign( 1.5 );
  35853. p.mulAssign( 1.2 );
  35854. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  35855. rz.addAssign( t.div( z ) );
  35856. bp.addAssign( 0.14 );
  35857. } );
  35858. return rz;
  35859. } ).setLayout( {
  35860. name: 'triNoise3D',
  35861. type: 'float',
  35862. inputs: [
  35863. { name: 'p', type: 'vec3' },
  35864. { name: 'spd', type: 'float' },
  35865. { name: 'time', type: 'float' }
  35866. ]
  35867. } );
  35868. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  35869. return rotate( uv.sub( center ), rotation ).add( center );
  35870. } );
  35871. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  35872. const delta = uv.sub( center );
  35873. const delta2 = delta.dot( delta );
  35874. const delta4 = delta2.mul( delta2 );
  35875. const deltaOffset = delta4.mul( strength );
  35876. return uv.add( delta.mul( deltaOffset ) );
  35877. } );
  35878. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  35879. let worldMatrix;
  35880. if ( position !== null ) {
  35881. worldMatrix = modelWorldMatrix.toVar();
  35882. worldMatrix[ 3 ][ 0 ] = position.x;
  35883. worldMatrix[ 3 ][ 1 ] = position.y;
  35884. worldMatrix[ 3 ][ 2 ] = position.z;
  35885. } else {
  35886. worldMatrix = modelWorldMatrix;
  35887. }
  35888. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  35889. if ( defined( horizontal ) ) {
  35890. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  35891. modelViewMatrix[ 0 ][ 1 ] = 0;
  35892. modelViewMatrix[ 0 ][ 2 ] = 0;
  35893. }
  35894. if ( defined( vertical ) ) {
  35895. modelViewMatrix[ 1 ][ 0 ] = 0;
  35896. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  35897. modelViewMatrix[ 1 ][ 2 ] = 0;
  35898. }
  35899. modelViewMatrix[ 2 ][ 0 ] = 0;
  35900. modelViewMatrix[ 2 ][ 1 ] = 0;
  35901. modelViewMatrix[ 2 ][ 2 ] = 1;
  35902. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  35903. } );
  35904. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  35905. const depth = linearDepth();
  35906. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  35907. const finalUV = depthDiff.lessThan( 0 ).select( viewportUV, uv );
  35908. return finalUV;
  35909. } );
  35910. const _objectData = new WeakMap();
  35911. class VelocityNode extends TempNode {
  35912. static get type() {
  35913. return 'VelocityNode';
  35914. }
  35915. constructor() {
  35916. super( 'vec2' );
  35917. this.updateType = NodeUpdateType.OBJECT;
  35918. this.updateAfterType = NodeUpdateType.OBJECT;
  35919. this.previousModelWorldMatrix = uniform( new Matrix4() );
  35920. this.previousProjectionMatrix = uniform( new Matrix4() );
  35921. this.previousCameraViewMatrix = uniform( new Matrix4() );
  35922. }
  35923. update( { frameId, camera, object } ) {
  35924. const previousModelMatrix = getPreviousMatrix( object );
  35925. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  35926. //
  35927. const cameraData = getData( camera );
  35928. if ( cameraData.frameId !== frameId ) {
  35929. cameraData.frameId = frameId;
  35930. if ( cameraData.previousProjectionMatrix === undefined ) {
  35931. cameraData.previousProjectionMatrix = new Matrix4();
  35932. cameraData.previousCameraViewMatrix = new Matrix4();
  35933. cameraData.currentProjectionMatrix = new Matrix4();
  35934. cameraData.currentCameraViewMatrix = new Matrix4();
  35935. cameraData.previousProjectionMatrix.copy( camera.projectionMatrix );
  35936. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  35937. } else {
  35938. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  35939. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  35940. }
  35941. cameraData.currentProjectionMatrix.copy( camera.projectionMatrix );
  35942. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  35943. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  35944. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  35945. }
  35946. }
  35947. updateAfter( { object } ) {
  35948. getPreviousMatrix( object ).copy( object.matrixWorld );
  35949. }
  35950. setup( /*builder*/ ) {
  35951. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  35952. const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  35953. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  35954. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  35955. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  35956. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  35957. return velocity;
  35958. }
  35959. }
  35960. function getData( object ) {
  35961. let objectData = _objectData.get( object );
  35962. if ( objectData === undefined ) {
  35963. objectData = {};
  35964. _objectData.set( object, objectData );
  35965. }
  35966. return objectData;
  35967. }
  35968. function getPreviousMatrix( object, index = 0 ) {
  35969. const objectData = getData( object );
  35970. let matrix = objectData[ index ];
  35971. if ( matrix === undefined ) {
  35972. objectData[ index ] = matrix = new Matrix4();
  35973. }
  35974. return matrix;
  35975. }
  35976. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  35977. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35978. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  35979. } ).setLayout( {
  35980. name: 'burnBlend',
  35981. type: 'vec3',
  35982. inputs: [
  35983. { name: 'base', type: 'vec3' },
  35984. { name: 'blend', type: 'vec3' }
  35985. ]
  35986. } );
  35987. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35988. return min$1( base.div( blend.oneMinus() ), 1.0 );
  35989. } ).setLayout( {
  35990. name: 'dodgeBlend',
  35991. type: 'vec3',
  35992. inputs: [
  35993. { name: 'base', type: 'vec3' },
  35994. { name: 'blend', type: 'vec3' }
  35995. ]
  35996. } );
  35997. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35998. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  35999. } ).setLayout( {
  36000. name: 'screenBlend',
  36001. type: 'vec3',
  36002. inputs: [
  36003. { name: 'base', type: 'vec3' },
  36004. { name: 'blend', type: 'vec3' }
  36005. ]
  36006. } );
  36007. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  36008. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  36009. } ).setLayout( {
  36010. name: 'overlayBlend',
  36011. type: 'vec3',
  36012. inputs: [
  36013. { name: 'base', type: 'vec3' },
  36014. { name: 'blend', type: 'vec3' }
  36015. ]
  36016. } );
  36017. const motionBlur = /*@__PURE__*/ Fn( ( [ inputNode, velocity, numSamples = int( 16 ) ] ) => {
  36018. const sampleColor = ( uv ) => inputNode.uv( uv );
  36019. const uvs = uv();
  36020. const colorResult = sampleColor( uvs ).toVar();
  36021. const fSamples = float( numSamples );
  36022. Loop( { start: int( 1 ), end: numSamples, type: 'int', condition: '<=' }, ( { i } ) => {
  36023. const offset = velocity.mul( float( i ).div( fSamples.sub( 1 ) ).sub( 0.5 ) );
  36024. colorResult.addAssign( sampleColor( uvs.add( offset ) ) );
  36025. } );
  36026. colorResult.divAssign( fSamples );
  36027. return colorResult;
  36028. } );
  36029. const bleach = /*@__PURE__*/ Fn( ( [ color, opacity = 1 ] ) => {
  36030. const base = color;
  36031. const lum = luminance( base.rgb );
  36032. const blend = vec3( lum );
  36033. const L = min$1( 1.0, max$1( 0.0, float( 10.0 ).mul( lum.sub( 0.45 ) ) ) );
  36034. const result1 = blend.mul( base.rgb ).mul( 2.0 );
  36035. const result2 = float( 2.0 ).mul( blend.oneMinus() ).mul( base.rgb.oneMinus() ).oneMinus();
  36036. const newColor = mix( result1, result2, L );
  36037. const A2 = base.a.mul( opacity );
  36038. const mixRGB = A2.mul( newColor.rgb );
  36039. mixRGB.addAssign( base.rgb.mul( A2.oneMinus() ) );
  36040. return vec4( mixRGB, base.a );
  36041. } );
  36042. const sepia = /*@__PURE__*/ Fn( ( [ color ] ) => {
  36043. const c = vec3( color );
  36044. // https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/sepia.js
  36045. return vec4(
  36046. dot( c, vec3( 0.393, 0.769, 0.189 ) ),
  36047. dot( c, vec3( 0.349, 0.686, 0.168 ) ),
  36048. dot( c, vec3( 0.272, 0.534, 0.131 ) ),
  36049. color.a
  36050. );
  36051. } );
  36052. const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  36053. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  36054. const b = color.mul( 0.0773993808 );
  36055. const factor = color.lessThanEqual( 0.04045 );
  36056. const rgbResult = mix( a, b, factor );
  36057. return rgbResult;
  36058. } ).setLayout( {
  36059. name: 'sRGBToLinearSRGB',
  36060. type: 'vec3',
  36061. inputs: [
  36062. { name: 'color', type: 'vec3' }
  36063. ]
  36064. } );
  36065. const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  36066. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  36067. const b = color.mul( 12.92 );
  36068. const factor = color.lessThanEqual( 0.0031308 );
  36069. const rgbResult = mix( a, b, factor );
  36070. return rgbResult;
  36071. } ).setLayout( {
  36072. name: 'linearSRGBTosRGB',
  36073. type: 'vec3',
  36074. inputs: [
  36075. { name: 'color', type: 'vec3' }
  36076. ]
  36077. } );
  36078. // exposure only
  36079. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36080. return color.mul( exposure ).clamp();
  36081. } ).setLayout( {
  36082. name: 'linearToneMapping',
  36083. type: 'vec3',
  36084. inputs: [
  36085. { name: 'color', type: 'vec3' },
  36086. { name: 'exposure', type: 'float' }
  36087. ]
  36088. } );
  36089. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  36090. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36091. color = color.mul( exposure );
  36092. return color.div( color.add( 1.0 ) ).clamp();
  36093. } ).setLayout( {
  36094. name: 'reinhardToneMapping',
  36095. type: 'vec3',
  36096. inputs: [
  36097. { name: 'color', type: 'vec3' },
  36098. { name: 'exposure', type: 'float' }
  36099. ]
  36100. } );
  36101. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  36102. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36103. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  36104. color = color.mul( exposure );
  36105. color = color.sub( 0.004 ).max( 0.0 );
  36106. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  36107. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  36108. return a.div( b ).pow( 2.2 );
  36109. } ).setLayout( {
  36110. name: 'cineonToneMapping',
  36111. type: 'vec3',
  36112. inputs: [
  36113. { name: 'color', type: 'vec3' },
  36114. { name: 'exposure', type: 'float' }
  36115. ]
  36116. } );
  36117. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  36118. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  36119. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  36120. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  36121. return a.div( b );
  36122. } );
  36123. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  36124. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36125. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  36126. const ACESInputMat = mat3(
  36127. 0.59719, 0.35458, 0.04823,
  36128. 0.07600, 0.90834, 0.01566,
  36129. 0.02840, 0.13383, 0.83777
  36130. );
  36131. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  36132. const ACESOutputMat = mat3(
  36133. 1.60475, - 0.53108, - 0.07367,
  36134. - 0.10208, 1.10813, - 0.00605,
  36135. - 0.00327, - 0.07276, 1.07602
  36136. );
  36137. color = color.mul( exposure ).div( 0.6 );
  36138. color = ACESInputMat.mul( color );
  36139. // Apply RRT and ODT
  36140. color = RRTAndODTFit( color );
  36141. color = ACESOutputMat.mul( color );
  36142. // Clamp to [0, 1]
  36143. return color.clamp();
  36144. } ).setLayout( {
  36145. name: 'acesFilmicToneMapping',
  36146. type: 'vec3',
  36147. inputs: [
  36148. { name: 'color', type: 'vec3' },
  36149. { name: 'exposure', type: 'float' }
  36150. ]
  36151. } );
  36152. 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 ) );
  36153. 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 ) );
  36154. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36155. const x = vec3( x_immutable ).toVar();
  36156. const x2 = vec3( x.mul( x ) ).toVar();
  36157. const x4 = vec3( x2.mul( x2 ) ).toVar();
  36158. 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 ) ) ) );
  36159. } );
  36160. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36161. const colortone = vec3( color ).toVar();
  36162. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  36163. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  36164. const AgxMinEv = float( - 12.47393 );
  36165. const AgxMaxEv = float( 4.026069 );
  36166. colortone.mulAssign( exposure );
  36167. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  36168. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  36169. colortone.assign( max$1( colortone, 1e-10 ) );
  36170. colortone.assign( log2( colortone ) );
  36171. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  36172. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  36173. colortone.assign( agxDefaultContrastApprox( colortone ) );
  36174. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  36175. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  36176. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  36177. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  36178. return colortone;
  36179. } ).setLayout( {
  36180. name: 'agxToneMapping',
  36181. type: 'vec3',
  36182. inputs: [
  36183. { name: 'color', type: 'vec3' },
  36184. { name: 'exposure', type: 'float' }
  36185. ]
  36186. } );
  36187. // https://modelviewer.dev/examples/tone-mapping
  36188. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  36189. const StartCompression = float( 0.8 - 0.04 );
  36190. const Desaturation = float( 0.15 );
  36191. color = color.mul( exposure );
  36192. const x = min$1( color.r, min$1( color.g, color.b ) );
  36193. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  36194. color.subAssign( offset );
  36195. const peak = max$1( color.r, max$1( color.g, color.b ) );
  36196. If( peak.lessThan( StartCompression ), () => {
  36197. return color;
  36198. } );
  36199. const d = sub( 1, StartCompression );
  36200. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  36201. color.mulAssign( newPeak.div( peak ) );
  36202. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  36203. return mix( color, vec3( newPeak ), g );
  36204. } ).setLayout( {
  36205. name: 'neutralToneMapping',
  36206. type: 'vec3',
  36207. inputs: [
  36208. { name: 'color', type: 'vec3' },
  36209. { name: 'exposure', type: 'float' }
  36210. ]
  36211. } );
  36212. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  36213. const uv = coord.mul( 2.0 );
  36214. const cx = uv.x.floor();
  36215. const cy = uv.y.floor();
  36216. const result = cx.add( cy ).mod( 2.0 );
  36217. return result.sign();
  36218. } );
  36219. // Three.js Transpiler
  36220. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  36221. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  36222. const f = float( f_immutable ).toVar();
  36223. const t = float( t_immutable ).toVar();
  36224. const b = bool( b_immutable ).toVar();
  36225. return select( b, t, f );
  36226. } ).setLayout( {
  36227. name: 'mx_select',
  36228. type: 'float',
  36229. inputs: [
  36230. { name: 'b', type: 'bool' },
  36231. { name: 't', type: 'float' },
  36232. { name: 'f', type: 'float' }
  36233. ]
  36234. } );
  36235. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  36236. const b = bool( b_immutable ).toVar();
  36237. const val = float( val_immutable ).toVar();
  36238. return select( b, val.negate(), val );
  36239. } ).setLayout( {
  36240. name: 'mx_negate_if',
  36241. type: 'float',
  36242. inputs: [
  36243. { name: 'val', type: 'float' },
  36244. { name: 'b', type: 'bool' }
  36245. ]
  36246. } );
  36247. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36248. const x = float( x_immutable ).toVar();
  36249. return int( floor( x ) );
  36250. } ).setLayout( {
  36251. name: 'mx_floor',
  36252. type: 'int',
  36253. inputs: [
  36254. { name: 'x', type: 'float' }
  36255. ]
  36256. } );
  36257. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  36258. const x = float( x_immutable ).toVar();
  36259. i.assign( mx_floor( x ) );
  36260. return x.sub( float( i ) );
  36261. } );
  36262. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  36263. const t = float( t_immutable ).toVar();
  36264. const s = float( s_immutable ).toVar();
  36265. const v3 = float( v3_immutable ).toVar();
  36266. const v2 = float( v2_immutable ).toVar();
  36267. const v1 = float( v1_immutable ).toVar();
  36268. const v0 = float( v0_immutable ).toVar();
  36269. const s1 = float( sub( 1.0, s ) ).toVar();
  36270. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  36271. } ).setLayout( {
  36272. name: 'mx_bilerp_0',
  36273. type: 'float',
  36274. inputs: [
  36275. { name: 'v0', type: 'float' },
  36276. { name: 'v1', type: 'float' },
  36277. { name: 'v2', type: 'float' },
  36278. { name: 'v3', type: 'float' },
  36279. { name: 's', type: 'float' },
  36280. { name: 't', type: 'float' }
  36281. ]
  36282. } );
  36283. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  36284. const t = float( t_immutable ).toVar();
  36285. const s = float( s_immutable ).toVar();
  36286. const v3 = vec3( v3_immutable ).toVar();
  36287. const v2 = vec3( v2_immutable ).toVar();
  36288. const v1 = vec3( v1_immutable ).toVar();
  36289. const v0 = vec3( v0_immutable ).toVar();
  36290. const s1 = float( sub( 1.0, s ) ).toVar();
  36291. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  36292. } ).setLayout( {
  36293. name: 'mx_bilerp_1',
  36294. type: 'vec3',
  36295. inputs: [
  36296. { name: 'v0', type: 'vec3' },
  36297. { name: 'v1', type: 'vec3' },
  36298. { name: 'v2', type: 'vec3' },
  36299. { name: 'v3', type: 'vec3' },
  36300. { name: 's', type: 'float' },
  36301. { name: 't', type: 'float' }
  36302. ]
  36303. } );
  36304. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  36305. 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 ] ) => {
  36306. const r = float( r_immutable ).toVar();
  36307. const t = float( t_immutable ).toVar();
  36308. const s = float( s_immutable ).toVar();
  36309. const v7 = float( v7_immutable ).toVar();
  36310. const v6 = float( v6_immutable ).toVar();
  36311. const v5 = float( v5_immutable ).toVar();
  36312. const v4 = float( v4_immutable ).toVar();
  36313. const v3 = float( v3_immutable ).toVar();
  36314. const v2 = float( v2_immutable ).toVar();
  36315. const v1 = float( v1_immutable ).toVar();
  36316. const v0 = float( v0_immutable ).toVar();
  36317. const s1 = float( sub( 1.0, s ) ).toVar();
  36318. const t1 = float( sub( 1.0, t ) ).toVar();
  36319. const r1 = float( sub( 1.0, r ) ).toVar();
  36320. 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 ) ) ) ) ) );
  36321. } ).setLayout( {
  36322. name: 'mx_trilerp_0',
  36323. type: 'float',
  36324. inputs: [
  36325. { name: 'v0', type: 'float' },
  36326. { name: 'v1', type: 'float' },
  36327. { name: 'v2', type: 'float' },
  36328. { name: 'v3', type: 'float' },
  36329. { name: 'v4', type: 'float' },
  36330. { name: 'v5', type: 'float' },
  36331. { name: 'v6', type: 'float' },
  36332. { name: 'v7', type: 'float' },
  36333. { name: 's', type: 'float' },
  36334. { name: 't', type: 'float' },
  36335. { name: 'r', type: 'float' }
  36336. ]
  36337. } );
  36338. 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 ] ) => {
  36339. const r = float( r_immutable ).toVar();
  36340. const t = float( t_immutable ).toVar();
  36341. const s = float( s_immutable ).toVar();
  36342. const v7 = vec3( v7_immutable ).toVar();
  36343. const v6 = vec3( v6_immutable ).toVar();
  36344. const v5 = vec3( v5_immutable ).toVar();
  36345. const v4 = vec3( v4_immutable ).toVar();
  36346. const v3 = vec3( v3_immutable ).toVar();
  36347. const v2 = vec3( v2_immutable ).toVar();
  36348. const v1 = vec3( v1_immutable ).toVar();
  36349. const v0 = vec3( v0_immutable ).toVar();
  36350. const s1 = float( sub( 1.0, s ) ).toVar();
  36351. const t1 = float( sub( 1.0, t ) ).toVar();
  36352. const r1 = float( sub( 1.0, r ) ).toVar();
  36353. 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 ) ) ) ) ) );
  36354. } ).setLayout( {
  36355. name: 'mx_trilerp_1',
  36356. type: 'vec3',
  36357. inputs: [
  36358. { name: 'v0', type: 'vec3' },
  36359. { name: 'v1', type: 'vec3' },
  36360. { name: 'v2', type: 'vec3' },
  36361. { name: 'v3', type: 'vec3' },
  36362. { name: 'v4', type: 'vec3' },
  36363. { name: 'v5', type: 'vec3' },
  36364. { name: 'v6', type: 'vec3' },
  36365. { name: 'v7', type: 'vec3' },
  36366. { name: 's', type: 'float' },
  36367. { name: 't', type: 'float' },
  36368. { name: 'r', type: 'float' }
  36369. ]
  36370. } );
  36371. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  36372. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  36373. const y = float( y_immutable ).toVar();
  36374. const x = float( x_immutable ).toVar();
  36375. const hash = uint( hash_immutable ).toVar();
  36376. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  36377. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  36378. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  36379. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  36380. } ).setLayout( {
  36381. name: 'mx_gradient_float_0',
  36382. type: 'float',
  36383. inputs: [
  36384. { name: 'hash', type: 'uint' },
  36385. { name: 'x', type: 'float' },
  36386. { name: 'y', type: 'float' }
  36387. ]
  36388. } );
  36389. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  36390. const z = float( z_immutable ).toVar();
  36391. const y = float( y_immutable ).toVar();
  36392. const x = float( x_immutable ).toVar();
  36393. const hash = uint( hash_immutable ).toVar();
  36394. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  36395. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  36396. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  36397. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  36398. } ).setLayout( {
  36399. name: 'mx_gradient_float_1',
  36400. type: 'float',
  36401. inputs: [
  36402. { name: 'hash', type: 'uint' },
  36403. { name: 'x', type: 'float' },
  36404. { name: 'y', type: 'float' },
  36405. { name: 'z', type: 'float' }
  36406. ]
  36407. } );
  36408. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  36409. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  36410. const y = float( y_immutable ).toVar();
  36411. const x = float( x_immutable ).toVar();
  36412. const hash = uvec3( hash_immutable ).toVar();
  36413. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  36414. } ).setLayout( {
  36415. name: 'mx_gradient_vec3_0',
  36416. type: 'vec3',
  36417. inputs: [
  36418. { name: 'hash', type: 'uvec3' },
  36419. { name: 'x', type: 'float' },
  36420. { name: 'y', type: 'float' }
  36421. ]
  36422. } );
  36423. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  36424. const z = float( z_immutable ).toVar();
  36425. const y = float( y_immutable ).toVar();
  36426. const x = float( x_immutable ).toVar();
  36427. const hash = uvec3( hash_immutable ).toVar();
  36428. 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 ) );
  36429. } ).setLayout( {
  36430. name: 'mx_gradient_vec3_1',
  36431. type: 'vec3',
  36432. inputs: [
  36433. { name: 'hash', type: 'uvec3' },
  36434. { name: 'x', type: 'float' },
  36435. { name: 'y', type: 'float' },
  36436. { name: 'z', type: 'float' }
  36437. ]
  36438. } );
  36439. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  36440. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36441. const v = float( v_immutable ).toVar();
  36442. return mul( 0.6616, v );
  36443. } ).setLayout( {
  36444. name: 'mx_gradient_scale2d_0',
  36445. type: 'float',
  36446. inputs: [
  36447. { name: 'v', type: 'float' }
  36448. ]
  36449. } );
  36450. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36451. const v = float( v_immutable ).toVar();
  36452. return mul( 0.9820, v );
  36453. } ).setLayout( {
  36454. name: 'mx_gradient_scale3d_0',
  36455. type: 'float',
  36456. inputs: [
  36457. { name: 'v', type: 'float' }
  36458. ]
  36459. } );
  36460. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36461. const v = vec3( v_immutable ).toVar();
  36462. return mul( 0.6616, v );
  36463. } ).setLayout( {
  36464. name: 'mx_gradient_scale2d_1',
  36465. type: 'vec3',
  36466. inputs: [
  36467. { name: 'v', type: 'vec3' }
  36468. ]
  36469. } );
  36470. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  36471. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36472. const v = vec3( v_immutable ).toVar();
  36473. return mul( 0.9820, v );
  36474. } ).setLayout( {
  36475. name: 'mx_gradient_scale3d_1',
  36476. type: 'vec3',
  36477. inputs: [
  36478. { name: 'v', type: 'vec3' }
  36479. ]
  36480. } );
  36481. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  36482. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  36483. const k = int( k_immutable ).toVar();
  36484. const x = uint( x_immutable ).toVar();
  36485. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  36486. } ).setLayout( {
  36487. name: 'mx_rotl32',
  36488. type: 'uint',
  36489. inputs: [
  36490. { name: 'x', type: 'uint' },
  36491. { name: 'k', type: 'int' }
  36492. ]
  36493. } );
  36494. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  36495. a.subAssign( c );
  36496. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  36497. c.addAssign( b );
  36498. b.subAssign( a );
  36499. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  36500. a.addAssign( c );
  36501. c.subAssign( b );
  36502. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  36503. b.addAssign( a );
  36504. a.subAssign( c );
  36505. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  36506. c.addAssign( b );
  36507. b.subAssign( a );
  36508. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  36509. a.addAssign( c );
  36510. c.subAssign( b );
  36511. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  36512. b.addAssign( a );
  36513. } );
  36514. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  36515. const c = uint( c_immutable ).toVar();
  36516. const b = uint( b_immutable ).toVar();
  36517. const a = uint( a_immutable ).toVar();
  36518. c.bitXorAssign( b );
  36519. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  36520. a.bitXorAssign( c );
  36521. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  36522. b.bitXorAssign( a );
  36523. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  36524. c.bitXorAssign( b );
  36525. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  36526. a.bitXorAssign( c );
  36527. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  36528. b.bitXorAssign( a );
  36529. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  36530. c.bitXorAssign( b );
  36531. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  36532. return c;
  36533. } ).setLayout( {
  36534. name: 'mx_bjfinal',
  36535. type: 'uint',
  36536. inputs: [
  36537. { name: 'a', type: 'uint' },
  36538. { name: 'b', type: 'uint' },
  36539. { name: 'c', type: 'uint' }
  36540. ]
  36541. } );
  36542. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  36543. const bits = uint( bits_immutable ).toVar();
  36544. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  36545. } ).setLayout( {
  36546. name: 'mx_bits_to_01',
  36547. type: 'float',
  36548. inputs: [
  36549. { name: 'bits', type: 'uint' }
  36550. ]
  36551. } );
  36552. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  36553. const t = float( t_immutable ).toVar();
  36554. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  36555. } ).setLayout( {
  36556. name: 'mx_fade',
  36557. type: 'float',
  36558. inputs: [
  36559. { name: 't', type: 'float' }
  36560. ]
  36561. } );
  36562. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36563. const x = int( x_immutable ).toVar();
  36564. const len = uint( uint( 1 ) ).toVar();
  36565. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  36566. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  36567. } ).setLayout( {
  36568. name: 'mx_hash_int_0',
  36569. type: 'uint',
  36570. inputs: [
  36571. { name: 'x', type: 'int' }
  36572. ]
  36573. } );
  36574. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  36575. const y = int( y_immutable ).toVar();
  36576. const x = int( x_immutable ).toVar();
  36577. const len = uint( uint( 2 ) ).toVar();
  36578. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36579. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36580. a.addAssign( uint( x ) );
  36581. b.addAssign( uint( y ) );
  36582. return mx_bjfinal( a, b, c );
  36583. } ).setLayout( {
  36584. name: 'mx_hash_int_1',
  36585. type: 'uint',
  36586. inputs: [
  36587. { name: 'x', type: 'int' },
  36588. { name: 'y', type: 'int' }
  36589. ]
  36590. } );
  36591. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  36592. const z = int( z_immutable ).toVar();
  36593. const y = int( y_immutable ).toVar();
  36594. const x = int( x_immutable ).toVar();
  36595. const len = uint( uint( 3 ) ).toVar();
  36596. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36597. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36598. a.addAssign( uint( x ) );
  36599. b.addAssign( uint( y ) );
  36600. c.addAssign( uint( z ) );
  36601. return mx_bjfinal( a, b, c );
  36602. } ).setLayout( {
  36603. name: 'mx_hash_int_2',
  36604. type: 'uint',
  36605. inputs: [
  36606. { name: 'x', type: 'int' },
  36607. { name: 'y', type: 'int' },
  36608. { name: 'z', type: 'int' }
  36609. ]
  36610. } );
  36611. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  36612. const xx = int( xx_immutable ).toVar();
  36613. const z = int( z_immutable ).toVar();
  36614. const y = int( y_immutable ).toVar();
  36615. const x = int( x_immutable ).toVar();
  36616. const len = uint( uint( 4 ) ).toVar();
  36617. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36618. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36619. a.addAssign( uint( x ) );
  36620. b.addAssign( uint( y ) );
  36621. c.addAssign( uint( z ) );
  36622. mx_bjmix( a, b, c );
  36623. a.addAssign( uint( xx ) );
  36624. return mx_bjfinal( a, b, c );
  36625. } ).setLayout( {
  36626. name: 'mx_hash_int_3',
  36627. type: 'uint',
  36628. inputs: [
  36629. { name: 'x', type: 'int' },
  36630. { name: 'y', type: 'int' },
  36631. { name: 'z', type: 'int' },
  36632. { name: 'xx', type: 'int' }
  36633. ]
  36634. } );
  36635. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  36636. const yy = int( yy_immutable ).toVar();
  36637. const xx = int( xx_immutable ).toVar();
  36638. const z = int( z_immutable ).toVar();
  36639. const y = int( y_immutable ).toVar();
  36640. const x = int( x_immutable ).toVar();
  36641. const len = uint( uint( 5 ) ).toVar();
  36642. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36643. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36644. a.addAssign( uint( x ) );
  36645. b.addAssign( uint( y ) );
  36646. c.addAssign( uint( z ) );
  36647. mx_bjmix( a, b, c );
  36648. a.addAssign( uint( xx ) );
  36649. b.addAssign( uint( yy ) );
  36650. return mx_bjfinal( a, b, c );
  36651. } ).setLayout( {
  36652. name: 'mx_hash_int_4',
  36653. type: 'uint',
  36654. inputs: [
  36655. { name: 'x', type: 'int' },
  36656. { name: 'y', type: 'int' },
  36657. { name: 'z', type: 'int' },
  36658. { name: 'xx', type: 'int' },
  36659. { name: 'yy', type: 'int' }
  36660. ]
  36661. } );
  36662. 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 ] );
  36663. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  36664. const y = int( y_immutable ).toVar();
  36665. const x = int( x_immutable ).toVar();
  36666. const h = uint( mx_hash_int( x, y ) ).toVar();
  36667. const result = uvec3().toVar();
  36668. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  36669. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  36670. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  36671. return result;
  36672. } ).setLayout( {
  36673. name: 'mx_hash_vec3_0',
  36674. type: 'uvec3',
  36675. inputs: [
  36676. { name: 'x', type: 'int' },
  36677. { name: 'y', type: 'int' }
  36678. ]
  36679. } );
  36680. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  36681. const z = int( z_immutable ).toVar();
  36682. const y = int( y_immutable ).toVar();
  36683. const x = int( x_immutable ).toVar();
  36684. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  36685. const result = uvec3().toVar();
  36686. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  36687. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  36688. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  36689. return result;
  36690. } ).setLayout( {
  36691. name: 'mx_hash_vec3_1',
  36692. type: 'uvec3',
  36693. inputs: [
  36694. { name: 'x', type: 'int' },
  36695. { name: 'y', type: 'int' },
  36696. { name: 'z', type: 'int' }
  36697. ]
  36698. } );
  36699. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  36700. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36701. const p = vec2( p_immutable ).toVar();
  36702. const X = int().toVar(), Y = int().toVar();
  36703. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36704. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36705. const u = float( mx_fade( fx ) ).toVar();
  36706. const v = float( mx_fade( fy ) ).toVar();
  36707. 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();
  36708. return mx_gradient_scale2d( result );
  36709. } ).setLayout( {
  36710. name: 'mx_perlin_noise_float_0',
  36711. type: 'float',
  36712. inputs: [
  36713. { name: 'p', type: 'vec2' }
  36714. ]
  36715. } );
  36716. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36717. const p = vec3( p_immutable ).toVar();
  36718. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36719. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36720. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36721. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  36722. const u = float( mx_fade( fx ) ).toVar();
  36723. const v = float( mx_fade( fy ) ).toVar();
  36724. const w = float( mx_fade( fz ) ).toVar();
  36725. 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();
  36726. return mx_gradient_scale3d( result );
  36727. } ).setLayout( {
  36728. name: 'mx_perlin_noise_float_1',
  36729. type: 'float',
  36730. inputs: [
  36731. { name: 'p', type: 'vec3' }
  36732. ]
  36733. } );
  36734. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  36735. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36736. const p = vec2( p_immutable ).toVar();
  36737. const X = int().toVar(), Y = int().toVar();
  36738. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36739. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36740. const u = float( mx_fade( fx ) ).toVar();
  36741. const v = float( mx_fade( fy ) ).toVar();
  36742. 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();
  36743. return mx_gradient_scale2d( result );
  36744. } ).setLayout( {
  36745. name: 'mx_perlin_noise_vec3_0',
  36746. type: 'vec3',
  36747. inputs: [
  36748. { name: 'p', type: 'vec2' }
  36749. ]
  36750. } );
  36751. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36752. const p = vec3( p_immutable ).toVar();
  36753. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36754. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36755. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36756. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  36757. const u = float( mx_fade( fx ) ).toVar();
  36758. const v = float( mx_fade( fy ) ).toVar();
  36759. const w = float( mx_fade( fz ) ).toVar();
  36760. 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();
  36761. return mx_gradient_scale3d( result );
  36762. } ).setLayout( {
  36763. name: 'mx_perlin_noise_vec3_1',
  36764. type: 'vec3',
  36765. inputs: [
  36766. { name: 'p', type: 'vec3' }
  36767. ]
  36768. } );
  36769. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  36770. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36771. const p = float( p_immutable ).toVar();
  36772. const ix = int( mx_floor( p ) ).toVar();
  36773. return mx_bits_to_01( mx_hash_int( ix ) );
  36774. } ).setLayout( {
  36775. name: 'mx_cell_noise_float_0',
  36776. type: 'float',
  36777. inputs: [
  36778. { name: 'p', type: 'float' }
  36779. ]
  36780. } );
  36781. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36782. const p = vec2( p_immutable ).toVar();
  36783. const ix = int( mx_floor( p.x ) ).toVar();
  36784. const iy = int( mx_floor( p.y ) ).toVar();
  36785. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  36786. } ).setLayout( {
  36787. name: 'mx_cell_noise_float_1',
  36788. type: 'float',
  36789. inputs: [
  36790. { name: 'p', type: 'vec2' }
  36791. ]
  36792. } );
  36793. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36794. const p = vec3( p_immutable ).toVar();
  36795. const ix = int( mx_floor( p.x ) ).toVar();
  36796. const iy = int( mx_floor( p.y ) ).toVar();
  36797. const iz = int( mx_floor( p.z ) ).toVar();
  36798. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  36799. } ).setLayout( {
  36800. name: 'mx_cell_noise_float_2',
  36801. type: 'float',
  36802. inputs: [
  36803. { name: 'p', type: 'vec3' }
  36804. ]
  36805. } );
  36806. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36807. const p = vec4( p_immutable ).toVar();
  36808. const ix = int( mx_floor( p.x ) ).toVar();
  36809. const iy = int( mx_floor( p.y ) ).toVar();
  36810. const iz = int( mx_floor( p.z ) ).toVar();
  36811. const iw = int( mx_floor( p.w ) ).toVar();
  36812. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  36813. } ).setLayout( {
  36814. name: 'mx_cell_noise_float_3',
  36815. type: 'float',
  36816. inputs: [
  36817. { name: 'p', type: 'vec4' }
  36818. ]
  36819. } );
  36820. 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 ] );
  36821. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36822. const p = float( p_immutable ).toVar();
  36823. const ix = int( mx_floor( p ) ).toVar();
  36824. 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 ) ) ) );
  36825. } ).setLayout( {
  36826. name: 'mx_cell_noise_vec3_0',
  36827. type: 'vec3',
  36828. inputs: [
  36829. { name: 'p', type: 'float' }
  36830. ]
  36831. } );
  36832. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36833. const p = vec2( p_immutable ).toVar();
  36834. const ix = int( mx_floor( p.x ) ).toVar();
  36835. const iy = int( mx_floor( p.y ) ).toVar();
  36836. 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 ) ) ) );
  36837. } ).setLayout( {
  36838. name: 'mx_cell_noise_vec3_1',
  36839. type: 'vec3',
  36840. inputs: [
  36841. { name: 'p', type: 'vec2' }
  36842. ]
  36843. } );
  36844. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36845. const p = vec3( p_immutable ).toVar();
  36846. const ix = int( mx_floor( p.x ) ).toVar();
  36847. const iy = int( mx_floor( p.y ) ).toVar();
  36848. const iz = int( mx_floor( p.z ) ).toVar();
  36849. 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 ) ) ) );
  36850. } ).setLayout( {
  36851. name: 'mx_cell_noise_vec3_2',
  36852. type: 'vec3',
  36853. inputs: [
  36854. { name: 'p', type: 'vec3' }
  36855. ]
  36856. } );
  36857. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36858. const p = vec4( p_immutable ).toVar();
  36859. const ix = int( mx_floor( p.x ) ).toVar();
  36860. const iy = int( mx_floor( p.y ) ).toVar();
  36861. const iz = int( mx_floor( p.z ) ).toVar();
  36862. const iw = int( mx_floor( p.w ) ).toVar();
  36863. 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 ) ) ) );
  36864. } ).setLayout( {
  36865. name: 'mx_cell_noise_vec3_3',
  36866. type: 'vec3',
  36867. inputs: [
  36868. { name: 'p', type: 'vec4' }
  36869. ]
  36870. } );
  36871. 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 ] );
  36872. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36873. const diminish = float( diminish_immutable ).toVar();
  36874. const lacunarity = float( lacunarity_immutable ).toVar();
  36875. const octaves = int( octaves_immutable ).toVar();
  36876. const p = vec3( p_immutable ).toVar();
  36877. const result = float( 0.0 ).toVar();
  36878. const amplitude = float( 1.0 ).toVar();
  36879. Loop( octaves, () => {
  36880. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  36881. amplitude.mulAssign( diminish );
  36882. p.mulAssign( lacunarity );
  36883. } );
  36884. return result;
  36885. } ).setLayout( {
  36886. name: 'mx_fractal_noise_float',
  36887. type: 'float',
  36888. inputs: [
  36889. { name: 'p', type: 'vec3' },
  36890. { name: 'octaves', type: 'int' },
  36891. { name: 'lacunarity', type: 'float' },
  36892. { name: 'diminish', type: 'float' }
  36893. ]
  36894. } );
  36895. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36896. const diminish = float( diminish_immutable ).toVar();
  36897. const lacunarity = float( lacunarity_immutable ).toVar();
  36898. const octaves = int( octaves_immutable ).toVar();
  36899. const p = vec3( p_immutable ).toVar();
  36900. const result = vec3( 0.0 ).toVar();
  36901. const amplitude = float( 1.0 ).toVar();
  36902. Loop( octaves, () => {
  36903. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  36904. amplitude.mulAssign( diminish );
  36905. p.mulAssign( lacunarity );
  36906. } );
  36907. return result;
  36908. } ).setLayout( {
  36909. name: 'mx_fractal_noise_vec3',
  36910. type: 'vec3',
  36911. inputs: [
  36912. { name: 'p', type: 'vec3' },
  36913. { name: 'octaves', type: 'int' },
  36914. { name: 'lacunarity', type: 'float' },
  36915. { name: 'diminish', type: 'float' }
  36916. ]
  36917. } );
  36918. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36919. const diminish = float( diminish_immutable ).toVar();
  36920. const lacunarity = float( lacunarity_immutable ).toVar();
  36921. const octaves = int( octaves_immutable ).toVar();
  36922. const p = vec3( p_immutable ).toVar();
  36923. 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 ) );
  36924. } ).setLayout( {
  36925. name: 'mx_fractal_noise_vec2',
  36926. type: 'vec2',
  36927. inputs: [
  36928. { name: 'p', type: 'vec3' },
  36929. { name: 'octaves', type: 'int' },
  36930. { name: 'lacunarity', type: 'float' },
  36931. { name: 'diminish', type: 'float' }
  36932. ]
  36933. } );
  36934. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36935. const diminish = float( diminish_immutable ).toVar();
  36936. const lacunarity = float( lacunarity_immutable ).toVar();
  36937. const octaves = int( octaves_immutable ).toVar();
  36938. const p = vec3( p_immutable ).toVar();
  36939. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  36940. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  36941. return vec4( c, f );
  36942. } ).setLayout( {
  36943. name: 'mx_fractal_noise_vec4',
  36944. type: 'vec4',
  36945. inputs: [
  36946. { name: 'p', type: 'vec3' },
  36947. { name: 'octaves', type: 'int' },
  36948. { name: 'lacunarity', type: 'float' },
  36949. { name: 'diminish', type: 'float' }
  36950. ]
  36951. } );
  36952. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  36953. const metric = int( metric_immutable ).toVar();
  36954. const jitter = float( jitter_immutable ).toVar();
  36955. const yoff = int( yoff_immutable ).toVar();
  36956. const xoff = int( xoff_immutable ).toVar();
  36957. const y = int( y_immutable ).toVar();
  36958. const x = int( x_immutable ).toVar();
  36959. const p = vec2( p_immutable ).toVar();
  36960. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  36961. const off = vec2( tmp.x, tmp.y ).toVar();
  36962. off.subAssign( 0.5 );
  36963. off.mulAssign( jitter );
  36964. off.addAssign( 0.5 );
  36965. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  36966. const diff = vec2( cellpos.sub( p ) ).toVar();
  36967. If( metric.equal( int( 2 ) ), () => {
  36968. return abs( diff.x ).add( abs( diff.y ) );
  36969. } );
  36970. If( metric.equal( int( 3 ) ), () => {
  36971. return max$1( abs( diff.x ), abs( diff.y ) );
  36972. } );
  36973. return dot( diff, diff );
  36974. } ).setLayout( {
  36975. name: 'mx_worley_distance_0',
  36976. type: 'float',
  36977. inputs: [
  36978. { name: 'p', type: 'vec2' },
  36979. { name: 'x', type: 'int' },
  36980. { name: 'y', type: 'int' },
  36981. { name: 'xoff', type: 'int' },
  36982. { name: 'yoff', type: 'int' },
  36983. { name: 'jitter', type: 'float' },
  36984. { name: 'metric', type: 'int' }
  36985. ]
  36986. } );
  36987. 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 ] ) => {
  36988. const metric = int( metric_immutable ).toVar();
  36989. const jitter = float( jitter_immutable ).toVar();
  36990. const zoff = int( zoff_immutable ).toVar();
  36991. const yoff = int( yoff_immutable ).toVar();
  36992. const xoff = int( xoff_immutable ).toVar();
  36993. const z = int( z_immutable ).toVar();
  36994. const y = int( y_immutable ).toVar();
  36995. const x = int( x_immutable ).toVar();
  36996. const p = vec3( p_immutable ).toVar();
  36997. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  36998. off.subAssign( 0.5 );
  36999. off.mulAssign( jitter );
  37000. off.addAssign( 0.5 );
  37001. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  37002. const diff = vec3( cellpos.sub( p ) ).toVar();
  37003. If( metric.equal( int( 2 ) ), () => {
  37004. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  37005. } );
  37006. If( metric.equal( int( 3 ) ), () => {
  37007. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  37008. } );
  37009. return dot( diff, diff );
  37010. } ).setLayout( {
  37011. name: 'mx_worley_distance_1',
  37012. type: 'float',
  37013. inputs: [
  37014. { name: 'p', type: 'vec3' },
  37015. { name: 'x', type: 'int' },
  37016. { name: 'y', type: 'int' },
  37017. { name: 'z', type: 'int' },
  37018. { name: 'xoff', type: 'int' },
  37019. { name: 'yoff', type: 'int' },
  37020. { name: 'zoff', type: 'int' },
  37021. { name: 'jitter', type: 'float' },
  37022. { name: 'metric', type: 'int' }
  37023. ]
  37024. } );
  37025. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  37026. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37027. const metric = int( metric_immutable ).toVar();
  37028. const jitter = float( jitter_immutable ).toVar();
  37029. const p = vec2( p_immutable ).toVar();
  37030. const X = int().toVar(), Y = int().toVar();
  37031. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  37032. const sqdist = float( 1e6 ).toVar();
  37033. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37034. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37035. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  37036. sqdist.assign( min$1( sqdist, dist ) );
  37037. } );
  37038. } );
  37039. If( metric.equal( int( 0 ) ), () => {
  37040. sqdist.assign( sqrt( sqdist ) );
  37041. } );
  37042. return sqdist;
  37043. } ).setLayout( {
  37044. name: 'mx_worley_noise_float_0',
  37045. type: 'float',
  37046. inputs: [
  37047. { name: 'p', type: 'vec2' },
  37048. { name: 'jitter', type: 'float' },
  37049. { name: 'metric', type: 'int' }
  37050. ]
  37051. } );
  37052. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37053. const metric = int( metric_immutable ).toVar();
  37054. const jitter = float( jitter_immutable ).toVar();
  37055. const p = vec2( p_immutable ).toVar();
  37056. const X = int().toVar(), Y = int().toVar();
  37057. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  37058. const sqdist = vec2( 1e6, 1e6 ).toVar();
  37059. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37060. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37061. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  37062. If( dist.lessThan( sqdist.x ), () => {
  37063. sqdist.y.assign( sqdist.x );
  37064. sqdist.x.assign( dist );
  37065. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37066. sqdist.y.assign( dist );
  37067. } );
  37068. } );
  37069. } );
  37070. If( metric.equal( int( 0 ) ), () => {
  37071. sqdist.assign( sqrt( sqdist ) );
  37072. } );
  37073. return sqdist;
  37074. } ).setLayout( {
  37075. name: 'mx_worley_noise_vec2_0',
  37076. type: 'vec2',
  37077. inputs: [
  37078. { name: 'p', type: 'vec2' },
  37079. { name: 'jitter', type: 'float' },
  37080. { name: 'metric', type: 'int' }
  37081. ]
  37082. } );
  37083. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37084. const metric = int( metric_immutable ).toVar();
  37085. const jitter = float( jitter_immutable ).toVar();
  37086. const p = vec2( p_immutable ).toVar();
  37087. const X = int().toVar(), Y = int().toVar();
  37088. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  37089. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  37090. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37091. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37092. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  37093. If( dist.lessThan( sqdist.x ), () => {
  37094. sqdist.z.assign( sqdist.y );
  37095. sqdist.y.assign( sqdist.x );
  37096. sqdist.x.assign( dist );
  37097. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37098. sqdist.z.assign( sqdist.y );
  37099. sqdist.y.assign( dist );
  37100. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  37101. sqdist.z.assign( dist );
  37102. } );
  37103. } );
  37104. } );
  37105. If( metric.equal( int( 0 ) ), () => {
  37106. sqdist.assign( sqrt( sqdist ) );
  37107. } );
  37108. return sqdist;
  37109. } ).setLayout( {
  37110. name: 'mx_worley_noise_vec3_0',
  37111. type: 'vec3',
  37112. inputs: [
  37113. { name: 'p', type: 'vec2' },
  37114. { name: 'jitter', type: 'float' },
  37115. { name: 'metric', type: 'int' }
  37116. ]
  37117. } );
  37118. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37119. const metric = int( metric_immutable ).toVar();
  37120. const jitter = float( jitter_immutable ).toVar();
  37121. const p = vec3( p_immutable ).toVar();
  37122. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  37123. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  37124. const sqdist = float( 1e6 ).toVar();
  37125. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37126. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37127. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  37128. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  37129. sqdist.assign( min$1( sqdist, dist ) );
  37130. } );
  37131. } );
  37132. } );
  37133. If( metric.equal( int( 0 ) ), () => {
  37134. sqdist.assign( sqrt( sqdist ) );
  37135. } );
  37136. return sqdist;
  37137. } ).setLayout( {
  37138. name: 'mx_worley_noise_float_1',
  37139. type: 'float',
  37140. inputs: [
  37141. { name: 'p', type: 'vec3' },
  37142. { name: 'jitter', type: 'float' },
  37143. { name: 'metric', type: 'int' }
  37144. ]
  37145. } );
  37146. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  37147. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37148. const metric = int( metric_immutable ).toVar();
  37149. const jitter = float( jitter_immutable ).toVar();
  37150. const p = vec3( p_immutable ).toVar();
  37151. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  37152. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  37153. const sqdist = vec2( 1e6, 1e6 ).toVar();
  37154. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37155. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37156. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  37157. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  37158. If( dist.lessThan( sqdist.x ), () => {
  37159. sqdist.y.assign( sqdist.x );
  37160. sqdist.x.assign( dist );
  37161. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37162. sqdist.y.assign( dist );
  37163. } );
  37164. } );
  37165. } );
  37166. } );
  37167. If( metric.equal( int( 0 ) ), () => {
  37168. sqdist.assign( sqrt( sqdist ) );
  37169. } );
  37170. return sqdist;
  37171. } ).setLayout( {
  37172. name: 'mx_worley_noise_vec2_1',
  37173. type: 'vec2',
  37174. inputs: [
  37175. { name: 'p', type: 'vec3' },
  37176. { name: 'jitter', type: 'float' },
  37177. { name: 'metric', type: 'int' }
  37178. ]
  37179. } );
  37180. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  37181. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  37182. const metric = int( metric_immutable ).toVar();
  37183. const jitter = float( jitter_immutable ).toVar();
  37184. const p = vec3( p_immutable ).toVar();
  37185. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  37186. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  37187. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  37188. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37189. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37190. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  37191. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  37192. If( dist.lessThan( sqdist.x ), () => {
  37193. sqdist.z.assign( sqdist.y );
  37194. sqdist.y.assign( sqdist.x );
  37195. sqdist.x.assign( dist );
  37196. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37197. sqdist.z.assign( sqdist.y );
  37198. sqdist.y.assign( dist );
  37199. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  37200. sqdist.z.assign( dist );
  37201. } );
  37202. } );
  37203. } );
  37204. } );
  37205. If( metric.equal( int( 0 ) ), () => {
  37206. sqdist.assign( sqrt( sqdist ) );
  37207. } );
  37208. return sqdist;
  37209. } ).setLayout( {
  37210. name: 'mx_worley_noise_vec3_1',
  37211. type: 'vec3',
  37212. inputs: [
  37213. { name: 'p', type: 'vec3' },
  37214. { name: 'jitter', type: 'float' },
  37215. { name: 'metric', type: 'int' }
  37216. ]
  37217. } );
  37218. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  37219. // Three.js Transpiler
  37220. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  37221. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  37222. const s = hsv.y;
  37223. const v = hsv.z;
  37224. const result = vec3().toVar();
  37225. If( s.lessThan( 0.0001 ), () => {
  37226. result.assign( vec3( v, v, v ) );
  37227. } ).Else( () => {
  37228. let h = hsv.x;
  37229. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  37230. const hi = int( trunc( h ) );
  37231. const f = h.sub( float( hi ) );
  37232. const p = v.mul( s.oneMinus() );
  37233. const q = v.mul( s.mul( f ).oneMinus() );
  37234. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  37235. If( hi.equal( int( 0 ) ), () => {
  37236. result.assign( vec3( v, t, p ) );
  37237. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  37238. result.assign( vec3( q, v, p ) );
  37239. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  37240. result.assign( vec3( p, v, t ) );
  37241. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  37242. result.assign( vec3( p, q, v ) );
  37243. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  37244. result.assign( vec3( t, p, v ) );
  37245. } ).Else( () => {
  37246. result.assign( vec3( v, p, q ) );
  37247. } );
  37248. } );
  37249. return result;
  37250. } ).setLayout( {
  37251. name: 'mx_hsvtorgb',
  37252. type: 'vec3',
  37253. inputs: [
  37254. { name: 'hsv', type: 'vec3' }
  37255. ]
  37256. } );
  37257. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  37258. const c = vec3( c_immutable ).toVar();
  37259. const r = float( c.x ).toVar();
  37260. const g = float( c.y ).toVar();
  37261. const b = float( c.z ).toVar();
  37262. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  37263. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  37264. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  37265. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  37266. v.assign( maxcomp );
  37267. If( maxcomp.greaterThan( 0.0 ), () => {
  37268. s.assign( delta.div( maxcomp ) );
  37269. } ).Else( () => {
  37270. s.assign( 0.0 );
  37271. } );
  37272. If( s.lessThanEqual( 0.0 ), () => {
  37273. h.assign( 0.0 );
  37274. } ).Else( () => {
  37275. If( r.greaterThanEqual( maxcomp ), () => {
  37276. h.assign( g.sub( b ).div( delta ) );
  37277. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  37278. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  37279. } ).Else( () => {
  37280. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  37281. } );
  37282. h.mulAssign( 1.0 / 6.0 );
  37283. If( h.lessThan( 0.0 ), () => {
  37284. h.addAssign( 1.0 );
  37285. } );
  37286. } );
  37287. return vec3( h, s, v );
  37288. } ).setLayout( {
  37289. name: 'mx_rgbtohsv',
  37290. type: 'vec3',
  37291. inputs: [
  37292. { name: 'c', type: 'vec3' }
  37293. ]
  37294. } );
  37295. // Three.js Transpiler
  37296. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  37297. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  37298. const color = vec3( color_immutable ).toVar();
  37299. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  37300. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  37301. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  37302. return mix( linSeg, powSeg, isAbove );
  37303. } ).setLayout( {
  37304. name: 'mx_srgb_texture_to_lin_rec709',
  37305. type: 'vec3',
  37306. inputs: [
  37307. { name: 'color', type: 'vec3' }
  37308. ]
  37309. } );
  37310. const mx_aastep = ( threshold, value ) => {
  37311. threshold = float( threshold );
  37312. value = float( value );
  37313. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  37314. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  37315. };
  37316. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  37317. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  37318. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  37319. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  37320. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  37321. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  37322. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  37323. const mx_safepower = ( in1, in2 = 1 ) => {
  37324. in1 = float( in1 );
  37325. return in1.abs().pow( in2 ).mul( in1.sign() );
  37326. };
  37327. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  37328. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37329. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37330. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37331. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  37332. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  37333. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  37334. return noise_vec4.mul( amplitude ).add( pivot );
  37335. };
  37336. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37337. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37338. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37339. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  37340. 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 );
  37341. 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 );
  37342. 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 );
  37343. 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 );
  37344. const _clearColor = /*@__PURE__*/ new Color4();
  37345. class Background extends DataMap {
  37346. constructor( renderer, nodes ) {
  37347. super();
  37348. this.renderer = renderer;
  37349. this.nodes = nodes;
  37350. }
  37351. update( scene, renderList, renderContext ) {
  37352. const renderer = this.renderer;
  37353. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  37354. let forceClear = false;
  37355. if ( background === null ) {
  37356. // no background settings, use clear color configuration from the renderer
  37357. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  37358. _clearColor.a = renderer._clearColor.a;
  37359. } else if ( background.isColor === true ) {
  37360. // background is an opaque color
  37361. background.getRGB( _clearColor, LinearSRGBColorSpace );
  37362. _clearColor.a = 1;
  37363. forceClear = true;
  37364. } else if ( background.isNode === true ) {
  37365. const sceneData = this.get( scene );
  37366. const backgroundNode = background;
  37367. _clearColor.copy( renderer._clearColor );
  37368. let backgroundMesh = sceneData.backgroundMesh;
  37369. if ( backgroundMesh === undefined ) {
  37370. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  37371. // @TODO: Add Texture2D support using node context
  37372. getUV: () => normalWorld,
  37373. getTextureLevel: () => backgroundBlurriness
  37374. } );
  37375. let viewProj = modelViewProjection();
  37376. viewProj = viewProj.setZ( viewProj.w );
  37377. const nodeMaterial = new NodeMaterial();
  37378. nodeMaterial.name = 'Background.material';
  37379. nodeMaterial.side = BackSide;
  37380. nodeMaterial.depthTest = false;
  37381. nodeMaterial.depthWrite = false;
  37382. nodeMaterial.fog = false;
  37383. nodeMaterial.lights = false;
  37384. nodeMaterial.vertexNode = viewProj;
  37385. nodeMaterial.colorNode = backgroundMeshNode;
  37386. sceneData.backgroundMeshNode = backgroundMeshNode;
  37387. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  37388. backgroundMesh.frustumCulled = false;
  37389. backgroundMesh.name = 'Background.mesh';
  37390. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  37391. this.matrixWorld.copyPosition( camera.matrixWorld );
  37392. };
  37393. }
  37394. const backgroundCacheKey = backgroundNode.getCacheKey();
  37395. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  37396. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  37397. sceneData.backgroundMeshNode.needsUpdate = true;
  37398. backgroundMesh.material.needsUpdate = true;
  37399. sceneData.backgroundCacheKey = backgroundCacheKey;
  37400. }
  37401. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  37402. } else {
  37403. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  37404. }
  37405. //
  37406. if ( renderer.autoClear === true || forceClear === true ) {
  37407. _clearColor.multiplyScalar( _clearColor.a );
  37408. const clearColorValue = renderContext.clearColorValue;
  37409. clearColorValue.r = _clearColor.r;
  37410. clearColorValue.g = _clearColor.g;
  37411. clearColorValue.b = _clearColor.b;
  37412. clearColorValue.a = _clearColor.a;
  37413. renderContext.depthClearValue = renderer._clearDepth;
  37414. renderContext.stencilClearValue = renderer._clearStencil;
  37415. renderContext.clearColor = renderer.autoClearColor === true;
  37416. renderContext.clearDepth = renderer.autoClearDepth === true;
  37417. renderContext.clearStencil = renderer.autoClearStencil === true;
  37418. } else {
  37419. renderContext.clearColor = false;
  37420. renderContext.clearDepth = false;
  37421. renderContext.clearStencil = false;
  37422. }
  37423. }
  37424. }
  37425. class NodeBuilderState {
  37426. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  37427. this.vertexShader = vertexShader;
  37428. this.fragmentShader = fragmentShader;
  37429. this.computeShader = computeShader;
  37430. this.transforms = transforms;
  37431. this.nodeAttributes = nodeAttributes;
  37432. this.bindings = bindings;
  37433. this.updateNodes = updateNodes;
  37434. this.updateBeforeNodes = updateBeforeNodes;
  37435. this.updateAfterNodes = updateAfterNodes;
  37436. this.instanceBindGroups = instanceBindGroups;
  37437. this.usedTimes = 0;
  37438. }
  37439. createBindings() {
  37440. const bindings = [];
  37441. for ( const instanceGroup of this.bindings ) {
  37442. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  37443. if ( shared !== true ) {
  37444. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  37445. bindings.push( bindingsGroup );
  37446. for ( const instanceBinding of instanceGroup.bindings ) {
  37447. bindingsGroup.bindings.push( instanceBinding.clone() );
  37448. }
  37449. } else {
  37450. bindings.push( instanceGroup );
  37451. }
  37452. }
  37453. return bindings;
  37454. }
  37455. }
  37456. const outputNodeMap = new WeakMap();
  37457. class Nodes extends DataMap {
  37458. constructor( renderer, backend ) {
  37459. super();
  37460. this.renderer = renderer;
  37461. this.backend = backend;
  37462. this.nodeFrame = new NodeFrame();
  37463. this.nodeBuilderCache = new Map();
  37464. this.callHashCache = new ChainMap();
  37465. this.groupsData = new ChainMap();
  37466. }
  37467. updateGroup( nodeUniformsGroup ) {
  37468. const groupNode = nodeUniformsGroup.groupNode;
  37469. const name = groupNode.name;
  37470. // objectGroup is every updated
  37471. if ( name === objectGroup.name ) return true;
  37472. // renderGroup is updated once per render/compute call
  37473. if ( name === renderGroup.name ) {
  37474. const uniformsGroupData = this.get( nodeUniformsGroup );
  37475. const renderId = this.nodeFrame.renderId;
  37476. if ( uniformsGroupData.renderId !== renderId ) {
  37477. uniformsGroupData.renderId = renderId;
  37478. return true;
  37479. }
  37480. return false;
  37481. }
  37482. // frameGroup is updated once per frame
  37483. if ( name === frameGroup.name ) {
  37484. const uniformsGroupData = this.get( nodeUniformsGroup );
  37485. const frameId = this.nodeFrame.frameId;
  37486. if ( uniformsGroupData.frameId !== frameId ) {
  37487. uniformsGroupData.frameId = frameId;
  37488. return true;
  37489. }
  37490. return false;
  37491. }
  37492. // other groups are updated just when groupNode.needsUpdate is true
  37493. const groupChain = [ groupNode, nodeUniformsGroup ];
  37494. let groupData = this.groupsData.get( groupChain );
  37495. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  37496. if ( groupData.version !== groupNode.version ) {
  37497. groupData.version = groupNode.version;
  37498. return true;
  37499. }
  37500. return false;
  37501. }
  37502. getForRenderCacheKey( renderObject ) {
  37503. return renderObject.initialCacheKey;
  37504. }
  37505. getForRender( renderObject ) {
  37506. const renderObjectData = this.get( renderObject );
  37507. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37508. if ( nodeBuilderState === undefined ) {
  37509. const { nodeBuilderCache } = this;
  37510. const cacheKey = this.getForRenderCacheKey( renderObject );
  37511. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37512. if ( nodeBuilderState === undefined ) {
  37513. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37514. nodeBuilder.scene = renderObject.scene;
  37515. nodeBuilder.material = renderObject.material;
  37516. nodeBuilder.camera = renderObject.camera;
  37517. nodeBuilder.context.material = renderObject.material;
  37518. nodeBuilder.lightsNode = renderObject.lightsNode;
  37519. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37520. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37521. nodeBuilder.clippingContext = renderObject.clippingContext;
  37522. nodeBuilder.build();
  37523. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37524. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37525. }
  37526. nodeBuilderState.usedTimes ++;
  37527. renderObjectData.nodeBuilderState = nodeBuilderState;
  37528. }
  37529. return nodeBuilderState;
  37530. }
  37531. delete( object ) {
  37532. if ( object.isRenderObject ) {
  37533. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37534. nodeBuilderState.usedTimes --;
  37535. if ( nodeBuilderState.usedTimes === 0 ) {
  37536. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37537. }
  37538. }
  37539. return super.delete( object );
  37540. }
  37541. getForCompute( computeNode ) {
  37542. const computeData = this.get( computeNode );
  37543. let nodeBuilderState = computeData.nodeBuilderState;
  37544. if ( nodeBuilderState === undefined ) {
  37545. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37546. nodeBuilder.build();
  37547. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37548. computeData.nodeBuilderState = nodeBuilderState;
  37549. }
  37550. return nodeBuilderState;
  37551. }
  37552. _createNodeBuilderState( nodeBuilder ) {
  37553. return new NodeBuilderState(
  37554. nodeBuilder.vertexShader,
  37555. nodeBuilder.fragmentShader,
  37556. nodeBuilder.computeShader,
  37557. nodeBuilder.getAttributesArray(),
  37558. nodeBuilder.getBindings(),
  37559. nodeBuilder.updateNodes,
  37560. nodeBuilder.updateBeforeNodes,
  37561. nodeBuilder.updateAfterNodes,
  37562. nodeBuilder.instanceBindGroups,
  37563. nodeBuilder.transforms
  37564. );
  37565. }
  37566. getEnvironmentNode( scene ) {
  37567. return scene.environmentNode || this.get( scene ).environmentNode || null;
  37568. }
  37569. getBackgroundNode( scene ) {
  37570. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  37571. }
  37572. getFogNode( scene ) {
  37573. return scene.fogNode || this.get( scene ).fogNode || null;
  37574. }
  37575. getCacheKey( scene, lightsNode ) {
  37576. const chain = [ scene, lightsNode ];
  37577. const callId = this.renderer.info.calls;
  37578. let cacheKeyData = this.callHashCache.get( chain );
  37579. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  37580. const environmentNode = this.getEnvironmentNode( scene );
  37581. const fogNode = this.getFogNode( scene );
  37582. const cacheKey = [];
  37583. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey( true ) );
  37584. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  37585. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  37586. cacheKeyData = {
  37587. callId,
  37588. cacheKey: cacheKey.join( ',' )
  37589. };
  37590. this.callHashCache.set( chain, cacheKeyData );
  37591. }
  37592. return cacheKeyData.cacheKey;
  37593. }
  37594. updateScene( scene ) {
  37595. this.updateEnvironment( scene );
  37596. this.updateFog( scene );
  37597. this.updateBackground( scene );
  37598. }
  37599. get isToneMappingState() {
  37600. return this.renderer.getRenderTarget() ? false : true;
  37601. }
  37602. updateBackground( scene ) {
  37603. const sceneData = this.get( scene );
  37604. const background = scene.background;
  37605. if ( background ) {
  37606. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37607. if ( sceneData.background !== background || forceUpdate ) {
  37608. let backgroundNode = null;
  37609. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37610. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37611. backgroundNode = pmremTexture( background, normalWorld );
  37612. } else {
  37613. let envMap;
  37614. if ( background.isCubeTexture === true ) {
  37615. envMap = cubeTexture( background );
  37616. } else {
  37617. envMap = texture( background );
  37618. }
  37619. backgroundNode = cubeMapNode( envMap );
  37620. }
  37621. } else if ( background.isTexture === true ) {
  37622. backgroundNode = texture( background, viewportUV.flipY() ).setUpdateMatrix( true );
  37623. } else if ( background.isColor !== true ) {
  37624. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  37625. }
  37626. sceneData.backgroundNode = backgroundNode;
  37627. sceneData.background = background;
  37628. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37629. }
  37630. } else if ( sceneData.backgroundNode ) {
  37631. delete sceneData.backgroundNode;
  37632. delete sceneData.background;
  37633. }
  37634. }
  37635. updateFog( scene ) {
  37636. const sceneData = this.get( scene );
  37637. const fog = scene.fog;
  37638. if ( fog ) {
  37639. if ( sceneData.fog !== fog ) {
  37640. let fogNode = null;
  37641. if ( fog.isFogExp2 ) {
  37642. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  37643. } else if ( fog.isFog ) {
  37644. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  37645. } else {
  37646. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  37647. }
  37648. sceneData.fogNode = fogNode;
  37649. sceneData.fog = fog;
  37650. }
  37651. } else {
  37652. delete sceneData.fogNode;
  37653. delete sceneData.fog;
  37654. }
  37655. }
  37656. updateEnvironment( scene ) {
  37657. const sceneData = this.get( scene );
  37658. const environment = scene.environment;
  37659. if ( environment ) {
  37660. if ( sceneData.environment !== environment ) {
  37661. let environmentNode = null;
  37662. if ( environment.isCubeTexture === true ) {
  37663. environmentNode = cubeTexture( environment );
  37664. } else if ( environment.isTexture === true ) {
  37665. environmentNode = texture( environment );
  37666. } else {
  37667. console.error( 'Nodes: Unsupported environment configuration.', environment );
  37668. }
  37669. sceneData.environmentNode = environmentNode;
  37670. sceneData.environment = environment;
  37671. }
  37672. } else if ( sceneData.environmentNode ) {
  37673. delete sceneData.environmentNode;
  37674. delete sceneData.environment;
  37675. }
  37676. }
  37677. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37678. const nodeFrame = this.nodeFrame;
  37679. nodeFrame.renderer = renderer;
  37680. nodeFrame.scene = scene;
  37681. nodeFrame.object = object;
  37682. nodeFrame.camera = camera;
  37683. nodeFrame.material = material;
  37684. return nodeFrame;
  37685. }
  37686. getNodeFrameForRender( renderObject ) {
  37687. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37688. }
  37689. getOutputCacheKey() {
  37690. const renderer = this.renderer;
  37691. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  37692. }
  37693. hasOutputChange( outputTarget ) {
  37694. const cacheKey = outputNodeMap.get( outputTarget );
  37695. return cacheKey !== this.getOutputCacheKey();
  37696. }
  37697. getOutputNode( outputTexture ) {
  37698. const renderer = this.renderer;
  37699. const cacheKey = this.getOutputCacheKey();
  37700. const output = texture( outputTexture, viewportUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37701. outputNodeMap.set( outputTexture, cacheKey );
  37702. return output;
  37703. }
  37704. updateBefore( renderObject ) {
  37705. const nodeBuilder = renderObject.getNodeBuilderState();
  37706. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37707. // update frame state for each node
  37708. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37709. }
  37710. }
  37711. updateAfter( renderObject ) {
  37712. const nodeBuilder = renderObject.getNodeBuilderState();
  37713. for ( const node of nodeBuilder.updateAfterNodes ) {
  37714. // update frame state for each node
  37715. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37716. }
  37717. }
  37718. updateForCompute( computeNode ) {
  37719. const nodeFrame = this.getNodeFrame();
  37720. const nodeBuilder = this.getForCompute( computeNode );
  37721. for ( const node of nodeBuilder.updateNodes ) {
  37722. nodeFrame.updateNode( node );
  37723. }
  37724. }
  37725. updateForRender( renderObject ) {
  37726. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37727. const nodeBuilder = renderObject.getNodeBuilderState();
  37728. for ( const node of nodeBuilder.updateNodes ) {
  37729. nodeFrame.updateNode( node );
  37730. }
  37731. }
  37732. dispose() {
  37733. super.dispose();
  37734. this.nodeFrame = new NodeFrame();
  37735. this.nodeBuilderCache = new Map();
  37736. }
  37737. }
  37738. class RenderBundle {
  37739. constructor( scene, camera ) {
  37740. this.scene = scene;
  37741. this.camera = camera;
  37742. }
  37743. clone() {
  37744. return Object.assign( new this.constructor(), this );
  37745. }
  37746. }
  37747. class RenderBundles {
  37748. constructor() {
  37749. this.lists = new ChainMap();
  37750. }
  37751. get( scene, camera ) {
  37752. const lists = this.lists;
  37753. const keys = [ scene, camera ];
  37754. let list = lists.get( keys );
  37755. if ( list === undefined ) {
  37756. list = new RenderBundle( scene, camera );
  37757. lists.set( keys, list );
  37758. }
  37759. return list;
  37760. }
  37761. dispose() {
  37762. this.lists = new ChainMap();
  37763. }
  37764. }
  37765. class NodeLibrary {
  37766. constructor() {
  37767. this.lightNodes = new WeakMap();
  37768. this.materialNodes = new Map();
  37769. this.toneMappingNodes = new Map();
  37770. this.colorSpaceNodes = new Map();
  37771. }
  37772. fromMaterial( material ) {
  37773. if ( material.isNodeMaterial ) return material;
  37774. let nodeMaterial = null;
  37775. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37776. if ( nodeMaterialClass !== null ) {
  37777. nodeMaterial = new nodeMaterialClass();
  37778. for ( const key in material ) {
  37779. nodeMaterial[ key ] = material[ key ];
  37780. }
  37781. }
  37782. return nodeMaterial;
  37783. }
  37784. addColorSpace( colorSpaceNode, colorSpace ) {
  37785. this.addType( colorSpaceNode, colorSpace, this.colorSpaceNodes );
  37786. }
  37787. getColorSpaceFunction( colorSpace ) {
  37788. return this.colorSpaceNodes.get( colorSpace ) || null;
  37789. }
  37790. addToneMapping( toneMappingNode, toneMapping ) {
  37791. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37792. }
  37793. getToneMappingFunction( toneMapping ) {
  37794. return this.toneMappingNodes.get( toneMapping ) || null;
  37795. }
  37796. getMaterialNodeClass( materialType ) {
  37797. return this.materialNodes.get( materialType ) || null;
  37798. }
  37799. addMaterial( materialNodeClass, materialClass ) {
  37800. this.addType( materialNodeClass, materialClass.name, this.materialNodes );
  37801. }
  37802. getLightNodeClass( light ) {
  37803. return this.lightNodes.get( light ) || null;
  37804. }
  37805. addLight( lightNodeClass, lightClass ) {
  37806. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37807. }
  37808. addType( nodeClass, type, library ) {
  37809. if ( library.has( type ) ) {
  37810. console.warn( `Redefinition of node ${ type }` );
  37811. return;
  37812. }
  37813. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37814. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37815. library.set( type, nodeClass );
  37816. }
  37817. addClass( nodeClass, baseClass, library ) {
  37818. if ( library.has( baseClass ) ) {
  37819. console.warn( `Redefinition of node ${ baseClass.name }` );
  37820. return;
  37821. }
  37822. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37823. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37824. library.set( baseClass, nodeClass );
  37825. }
  37826. }
  37827. const _scene = /*@__PURE__*/ new Scene();
  37828. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37829. const _screen = /*@__PURE__*/ new Vector4();
  37830. const _frustum = /*@__PURE__*/ new Frustum();
  37831. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37832. const _vector4 = /*@__PURE__*/ new Vector4();
  37833. class Renderer {
  37834. constructor( backend, parameters = {} ) {
  37835. this.isRenderer = true;
  37836. //
  37837. const {
  37838. logarithmicDepthBuffer = false,
  37839. alpha = true,
  37840. antialias = false,
  37841. samples = 0,
  37842. getFallback = null
  37843. } = parameters;
  37844. // public
  37845. this.domElement = backend.getDomElement();
  37846. this.backend = backend;
  37847. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37848. this.autoClear = true;
  37849. this.autoClearColor = true;
  37850. this.autoClearDepth = true;
  37851. this.autoClearStencil = true;
  37852. this.alpha = alpha;
  37853. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37854. this.outputColorSpace = SRGBColorSpace;
  37855. this.toneMapping = NoToneMapping;
  37856. this.toneMappingExposure = 1.0;
  37857. this.sortObjects = true;
  37858. this.depth = true;
  37859. this.stencil = false;
  37860. this.clippingPlanes = [];
  37861. this.info = new Info();
  37862. this.nodes = {
  37863. library: new NodeLibrary(),
  37864. modelViewMatrix: null,
  37865. modelNormalMatrix: null
  37866. };
  37867. // internals
  37868. this._getFallback = getFallback;
  37869. this._pixelRatio = 1;
  37870. this._width = this.domElement.width;
  37871. this._height = this.domElement.height;
  37872. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37873. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37874. this._scissorTest = false;
  37875. this._attributes = null;
  37876. this._geometries = null;
  37877. this._nodes = null;
  37878. this._animation = null;
  37879. this._bindings = null;
  37880. this._objects = null;
  37881. this._pipelines = null;
  37882. this._bundles = null;
  37883. this._renderLists = null;
  37884. this._renderContexts = null;
  37885. this._textures = null;
  37886. this._background = null;
  37887. this._quad = new QuadMesh( new NodeMaterial() );
  37888. this._quad.material.type = 'Renderer_output';
  37889. this._currentRenderContext = null;
  37890. this._opaqueSort = null;
  37891. this._transparentSort = null;
  37892. this._frameBufferTarget = null;
  37893. const alphaClear = this.alpha === true ? 0 : 1;
  37894. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37895. this._clearDepth = 1;
  37896. this._clearStencil = 0;
  37897. this._renderTarget = null;
  37898. this._activeCubeFace = 0;
  37899. this._activeMipmapLevel = 0;
  37900. this._mrt = null;
  37901. this._renderObjectFunction = null;
  37902. this._currentRenderObjectFunction = null;
  37903. this._currentRenderBundle = null;
  37904. this._handleObjectFunction = this._renderObjectDirect;
  37905. this._initialized = false;
  37906. this._initPromise = null;
  37907. this._compilationPromises = null;
  37908. this.transparent = true;
  37909. this.opaque = true;
  37910. this.shadowMap = {
  37911. enabled: false,
  37912. type: PCFShadowMap$1
  37913. };
  37914. this.xr = {
  37915. enabled: false
  37916. };
  37917. this.debug = {
  37918. checkShaderErrors: true,
  37919. onShaderError: null,
  37920. getShaderAsync: async ( scene, camera, object ) => {
  37921. await this.compileAsync( scene, camera );
  37922. const renderList = this._renderLists.get( scene, camera );
  37923. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37924. const material = scene.overrideMaterial || object.material;
  37925. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37926. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37927. return { fragmentShader, vertexShader };
  37928. }
  37929. };
  37930. }
  37931. async init() {
  37932. if ( this._initialized ) {
  37933. throw new Error( 'Renderer: Backend has already been initialized.' );
  37934. }
  37935. if ( this._initPromise !== null ) {
  37936. return this._initPromise;
  37937. }
  37938. this._initPromise = new Promise( async ( resolve, reject ) => {
  37939. let backend = this.backend;
  37940. try {
  37941. await backend.init( this );
  37942. } catch ( error ) {
  37943. if ( this._getFallback !== null ) {
  37944. // try the fallback
  37945. try {
  37946. this.backend = backend = this._getFallback( error );
  37947. await backend.init( this );
  37948. } catch ( error ) {
  37949. reject( error );
  37950. return;
  37951. }
  37952. } else {
  37953. reject( error );
  37954. return;
  37955. }
  37956. }
  37957. this._nodes = new Nodes( this, backend );
  37958. this._animation = new Animation( this._nodes, this.info );
  37959. this._attributes = new Attributes( backend );
  37960. this._background = new Background( this, this._nodes );
  37961. this._geometries = new Geometries( this._attributes, this.info );
  37962. this._textures = new Textures( this, backend, this.info );
  37963. this._pipelines = new Pipelines( backend, this._nodes );
  37964. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37965. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37966. this._renderLists = new RenderLists();
  37967. this._bundles = new RenderBundles();
  37968. this._renderContexts = new RenderContexts();
  37969. //
  37970. this._initialized = true;
  37971. resolve();
  37972. } );
  37973. return this._initPromise;
  37974. }
  37975. get coordinateSystem() {
  37976. return this.backend.coordinateSystem;
  37977. }
  37978. async compileAsync( scene, camera, targetScene = null ) {
  37979. if ( this._initialized === false ) await this.init();
  37980. // preserve render tree
  37981. const nodeFrame = this._nodes.nodeFrame;
  37982. const previousRenderId = nodeFrame.renderId;
  37983. const previousRenderContext = this._currentRenderContext;
  37984. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37985. const previousCompilationPromises = this._compilationPromises;
  37986. //
  37987. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37988. if ( targetScene === null ) targetScene = scene;
  37989. const renderTarget = this._renderTarget;
  37990. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37991. const activeMipmapLevel = this._activeMipmapLevel;
  37992. const compilationPromises = [];
  37993. this._currentRenderContext = renderContext;
  37994. this._currentRenderObjectFunction = this.renderObject;
  37995. this._handleObjectFunction = this._createObjectPipeline;
  37996. this._compilationPromises = compilationPromises;
  37997. nodeFrame.renderId ++;
  37998. //
  37999. nodeFrame.update();
  38000. //
  38001. renderContext.depth = this.depth;
  38002. renderContext.stencil = this.stencil;
  38003. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38004. renderContext.clippingContext.updateGlobal( this, camera );
  38005. //
  38006. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38007. //
  38008. const renderList = this._renderLists.get( scene, camera );
  38009. renderList.begin();
  38010. this._projectObject( scene, camera, 0, renderList );
  38011. // include lights from target scene
  38012. if ( targetScene !== scene ) {
  38013. targetScene.traverseVisible( function ( object ) {
  38014. if ( object.isLight && object.layers.test( camera.layers ) ) {
  38015. renderList.pushLight( object );
  38016. }
  38017. } );
  38018. }
  38019. renderList.finish();
  38020. //
  38021. if ( renderTarget !== null ) {
  38022. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38023. const renderTargetData = this._textures.get( renderTarget );
  38024. renderContext.textures = renderTargetData.textures;
  38025. renderContext.depthTexture = renderTargetData.depthTexture;
  38026. } else {
  38027. renderContext.textures = null;
  38028. renderContext.depthTexture = null;
  38029. }
  38030. //
  38031. this._nodes.updateScene( sceneRef );
  38032. //
  38033. this._background.update( sceneRef, renderList, renderContext );
  38034. // process render lists
  38035. const opaqueObjects = renderList.opaque;
  38036. const transparentObjects = renderList.transparent;
  38037. const lightsNode = renderList.lightsNode;
  38038. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38039. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  38040. // restore render tree
  38041. nodeFrame.renderId = previousRenderId;
  38042. this._currentRenderContext = previousRenderContext;
  38043. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38044. this._compilationPromises = previousCompilationPromises;
  38045. this._handleObjectFunction = this._renderObjectDirect;
  38046. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  38047. await Promise.all( compilationPromises );
  38048. }
  38049. async renderAsync( scene, camera ) {
  38050. if ( this._initialized === false ) await this.init();
  38051. const renderContext = this._renderScene( scene, camera );
  38052. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  38053. }
  38054. setMRT( mrt ) {
  38055. this._mrt = mrt;
  38056. return this;
  38057. }
  38058. getMRT() {
  38059. return this._mrt;
  38060. }
  38061. _renderBundle( bundle, sceneRef, lightsNode ) {
  38062. const { bundleGroup, camera, renderList } = bundle;
  38063. const renderContext = this._currentRenderContext;
  38064. //
  38065. const renderBundle = this._bundles.get( bundleGroup, camera );
  38066. const renderBundleData = this.backend.get( renderBundle );
  38067. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  38068. //
  38069. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || bundleGroup.needsUpdate === true;
  38070. renderBundleData.renderContexts.add( renderContext );
  38071. if ( renderBundleNeedsUpdate ) {
  38072. this.backend.beginBundle( renderContext );
  38073. if ( renderBundleData.renderObjects === undefined || bundleGroup.needsUpdate === true ) {
  38074. renderBundleData.renderObjects = [];
  38075. }
  38076. this._currentRenderBundle = renderBundle;
  38077. const opaqueObjects = renderList.opaque;
  38078. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38079. this._currentRenderBundle = null;
  38080. //
  38081. this.backend.finishBundle( renderContext, renderBundle );
  38082. bundleGroup.needsUpdate = false;
  38083. } else {
  38084. const renderObjects = renderBundleData.renderObjects;
  38085. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  38086. const renderObject = renderObjects[ i ];
  38087. this._nodes.updateBefore( renderObject );
  38088. this._nodes.updateForRender( renderObject );
  38089. this._bindings.updateForRender( renderObject );
  38090. this._nodes.updateAfter( renderObject );
  38091. }
  38092. }
  38093. this.backend.addBundle( renderContext, renderBundle );
  38094. }
  38095. render( scene, camera ) {
  38096. if ( this._initialized === false ) {
  38097. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  38098. return this.renderAsync( scene, camera );
  38099. }
  38100. this._renderScene( scene, camera );
  38101. }
  38102. _getFrameBufferTarget() {
  38103. const { currentToneMapping, currentColorSpace } = this;
  38104. const useToneMapping = currentToneMapping !== NoToneMapping;
  38105. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  38106. if ( useToneMapping === false && useColorSpace === false ) return null;
  38107. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  38108. const { depth, stencil } = this;
  38109. let frameBufferTarget = this._frameBufferTarget;
  38110. if ( frameBufferTarget === null ) {
  38111. frameBufferTarget = new RenderTarget( width, height, {
  38112. depthBuffer: depth,
  38113. stencilBuffer: stencil,
  38114. type: HalfFloatType, // FloatType
  38115. format: RGBAFormat,
  38116. colorSpace: LinearSRGBColorSpace,
  38117. generateMipmaps: false,
  38118. minFilter: LinearFilter,
  38119. magFilter: LinearFilter,
  38120. samples: this.samples
  38121. } );
  38122. frameBufferTarget.isPostProcessingRenderTarget = true;
  38123. this._frameBufferTarget = frameBufferTarget;
  38124. }
  38125. frameBufferTarget.depthBuffer = depth;
  38126. frameBufferTarget.stencilBuffer = stencil;
  38127. frameBufferTarget.setSize( width, height );
  38128. frameBufferTarget.viewport.copy( this._viewport );
  38129. frameBufferTarget.scissor.copy( this._scissor );
  38130. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  38131. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  38132. frameBufferTarget.scissorTest = this._scissorTest;
  38133. return frameBufferTarget;
  38134. }
  38135. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  38136. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  38137. // preserve render tree
  38138. const nodeFrame = this._nodes.nodeFrame;
  38139. const previousRenderId = nodeFrame.renderId;
  38140. const previousRenderContext = this._currentRenderContext;
  38141. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38142. //
  38143. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38144. const outputRenderTarget = this._renderTarget;
  38145. const activeCubeFace = this._activeCubeFace;
  38146. const activeMipmapLevel = this._activeMipmapLevel;
  38147. //
  38148. let renderTarget;
  38149. if ( frameBufferTarget !== null ) {
  38150. renderTarget = frameBufferTarget;
  38151. this.setRenderTarget( renderTarget );
  38152. } else {
  38153. renderTarget = outputRenderTarget;
  38154. }
  38155. //
  38156. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  38157. this._currentRenderContext = renderContext;
  38158. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  38159. //
  38160. this.info.calls ++;
  38161. this.info.render.calls ++;
  38162. this.info.render.frameCalls ++;
  38163. nodeFrame.renderId = this.info.calls;
  38164. //
  38165. const coordinateSystem = this.coordinateSystem;
  38166. if ( camera.coordinateSystem !== coordinateSystem ) {
  38167. camera.coordinateSystem = coordinateSystem;
  38168. camera.updateProjectionMatrix();
  38169. }
  38170. //
  38171. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  38172. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  38173. //
  38174. let viewport = this._viewport;
  38175. let scissor = this._scissor;
  38176. let pixelRatio = this._pixelRatio;
  38177. if ( renderTarget !== null ) {
  38178. viewport = renderTarget.viewport;
  38179. scissor = renderTarget.scissor;
  38180. pixelRatio = 1;
  38181. }
  38182. this.getDrawingBufferSize( _drawingBufferSize );
  38183. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  38184. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  38185. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  38186. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  38187. renderContext.viewportValue.width >>= activeMipmapLevel;
  38188. renderContext.viewportValue.height >>= activeMipmapLevel;
  38189. renderContext.viewportValue.minDepth = minDepth;
  38190. renderContext.viewportValue.maxDepth = maxDepth;
  38191. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  38192. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  38193. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  38194. renderContext.scissorValue.width >>= activeMipmapLevel;
  38195. renderContext.scissorValue.height >>= activeMipmapLevel;
  38196. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38197. renderContext.clippingContext.updateGlobal( this, camera );
  38198. //
  38199. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38200. //
  38201. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  38202. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  38203. const renderList = this._renderLists.get( scene, camera );
  38204. renderList.begin();
  38205. this._projectObject( scene, camera, 0, renderList );
  38206. renderList.finish();
  38207. if ( this.sortObjects === true ) {
  38208. renderList.sort( this._opaqueSort, this._transparentSort );
  38209. }
  38210. //
  38211. if ( renderTarget !== null ) {
  38212. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38213. const renderTargetData = this._textures.get( renderTarget );
  38214. renderContext.textures = renderTargetData.textures;
  38215. renderContext.depthTexture = renderTargetData.depthTexture;
  38216. renderContext.width = renderTargetData.width;
  38217. renderContext.height = renderTargetData.height;
  38218. renderContext.renderTarget = renderTarget;
  38219. renderContext.depth = renderTarget.depthBuffer;
  38220. renderContext.stencil = renderTarget.stencilBuffer;
  38221. } else {
  38222. renderContext.textures = null;
  38223. renderContext.depthTexture = null;
  38224. renderContext.width = this.domElement.width;
  38225. renderContext.height = this.domElement.height;
  38226. renderContext.depth = this.depth;
  38227. renderContext.stencil = this.stencil;
  38228. }
  38229. renderContext.width >>= activeMipmapLevel;
  38230. renderContext.height >>= activeMipmapLevel;
  38231. renderContext.activeCubeFace = activeCubeFace;
  38232. renderContext.activeMipmapLevel = activeMipmapLevel;
  38233. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  38234. //
  38235. this._nodes.updateScene( sceneRef );
  38236. //
  38237. this._background.update( sceneRef, renderList, renderContext );
  38238. //
  38239. this.backend.beginRender( renderContext );
  38240. // process render lists
  38241. const opaqueObjects = renderList.opaque;
  38242. const transparentObjects = renderList.transparent;
  38243. const bundles = renderList.bundles;
  38244. const lightsNode = renderList.lightsNode;
  38245. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  38246. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38247. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  38248. // finish render pass
  38249. this.backend.finishRender( renderContext );
  38250. // restore render tree
  38251. nodeFrame.renderId = previousRenderId;
  38252. this._currentRenderContext = previousRenderContext;
  38253. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38254. //
  38255. if ( frameBufferTarget !== null ) {
  38256. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  38257. const quad = this._quad;
  38258. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38259. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38260. quad.material.needsUpdate = true;
  38261. }
  38262. this._renderScene( quad, quad.camera, false );
  38263. }
  38264. //
  38265. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  38266. //
  38267. return renderContext;
  38268. }
  38269. getMaxAnisotropy() {
  38270. return this.backend.getMaxAnisotropy();
  38271. }
  38272. getActiveCubeFace() {
  38273. return this._activeCubeFace;
  38274. }
  38275. getActiveMipmapLevel() {
  38276. return this._activeMipmapLevel;
  38277. }
  38278. async setAnimationLoop( callback ) {
  38279. if ( this._initialized === false ) await this.init();
  38280. this._animation.setAnimationLoop( callback );
  38281. }
  38282. async getArrayBufferAsync( attribute ) {
  38283. return await this.backend.getArrayBufferAsync( attribute );
  38284. }
  38285. getContext() {
  38286. return this.backend.getContext();
  38287. }
  38288. getPixelRatio() {
  38289. return this._pixelRatio;
  38290. }
  38291. getDrawingBufferSize( target ) {
  38292. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  38293. }
  38294. getSize( target ) {
  38295. return target.set( this._width, this._height );
  38296. }
  38297. setPixelRatio( value = 1 ) {
  38298. this._pixelRatio = value;
  38299. this.setSize( this._width, this._height, false );
  38300. }
  38301. setDrawingBufferSize( width, height, pixelRatio ) {
  38302. this._width = width;
  38303. this._height = height;
  38304. this._pixelRatio = pixelRatio;
  38305. this.domElement.width = Math.floor( width * pixelRatio );
  38306. this.domElement.height = Math.floor( height * pixelRatio );
  38307. this.setViewport( 0, 0, width, height );
  38308. if ( this._initialized ) this.backend.updateSize();
  38309. }
  38310. setSize( width, height, updateStyle = true ) {
  38311. this._width = width;
  38312. this._height = height;
  38313. this.domElement.width = Math.floor( width * this._pixelRatio );
  38314. this.domElement.height = Math.floor( height * this._pixelRatio );
  38315. if ( updateStyle === true ) {
  38316. this.domElement.style.width = width + 'px';
  38317. this.domElement.style.height = height + 'px';
  38318. }
  38319. this.setViewport( 0, 0, width, height );
  38320. if ( this._initialized ) this.backend.updateSize();
  38321. }
  38322. setOpaqueSort( method ) {
  38323. this._opaqueSort = method;
  38324. }
  38325. setTransparentSort( method ) {
  38326. this._transparentSort = method;
  38327. }
  38328. getScissor( target ) {
  38329. const scissor = this._scissor;
  38330. target.x = scissor.x;
  38331. target.y = scissor.y;
  38332. target.width = scissor.width;
  38333. target.height = scissor.height;
  38334. return target;
  38335. }
  38336. setScissor( x, y, width, height ) {
  38337. const scissor = this._scissor;
  38338. if ( x.isVector4 ) {
  38339. scissor.copy( x );
  38340. } else {
  38341. scissor.set( x, y, width, height );
  38342. }
  38343. }
  38344. getScissorTest() {
  38345. return this._scissorTest;
  38346. }
  38347. setScissorTest( boolean ) {
  38348. this._scissorTest = boolean;
  38349. this.backend.setScissorTest( boolean );
  38350. }
  38351. getViewport( target ) {
  38352. return target.copy( this._viewport );
  38353. }
  38354. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  38355. const viewport = this._viewport;
  38356. if ( x.isVector4 ) {
  38357. viewport.copy( x );
  38358. } else {
  38359. viewport.set( x, y, width, height );
  38360. }
  38361. viewport.minDepth = minDepth;
  38362. viewport.maxDepth = maxDepth;
  38363. }
  38364. getClearColor( target ) {
  38365. return target.copy( this._clearColor );
  38366. }
  38367. setClearColor( color, alpha = 1 ) {
  38368. this._clearColor.set( color );
  38369. this._clearColor.a = alpha;
  38370. }
  38371. getClearAlpha() {
  38372. return this._clearColor.a;
  38373. }
  38374. setClearAlpha( alpha ) {
  38375. this._clearColor.a = alpha;
  38376. }
  38377. getClearDepth() {
  38378. return this._clearDepth;
  38379. }
  38380. setClearDepth( depth ) {
  38381. this._clearDepth = depth;
  38382. }
  38383. getClearStencil() {
  38384. return this._clearStencil;
  38385. }
  38386. setClearStencil( stencil ) {
  38387. this._clearStencil = stencil;
  38388. }
  38389. isOccluded( object ) {
  38390. const renderContext = this._currentRenderContext;
  38391. return renderContext && this.backend.isOccluded( renderContext, object );
  38392. }
  38393. clear( color = true, depth = true, stencil = true ) {
  38394. if ( this._initialized === false ) {
  38395. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38396. return this.clearAsync( color, depth, stencil );
  38397. }
  38398. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38399. let renderTargetData = null;
  38400. if ( renderTarget !== null ) {
  38401. this._textures.updateRenderTarget( renderTarget );
  38402. renderTargetData = this._textures.get( renderTarget );
  38403. }
  38404. this.backend.clear( color, depth, stencil, renderTargetData );
  38405. if ( renderTarget !== null && this._renderTarget === null ) {
  38406. // If a color space transform or tone mapping is required,
  38407. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  38408. const quad = this._quad;
  38409. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38410. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38411. quad.material.needsUpdate = true;
  38412. }
  38413. this._renderScene( quad, quad.camera, false );
  38414. }
  38415. }
  38416. clearColor() {
  38417. return this.clear( true, false, false );
  38418. }
  38419. clearDepth() {
  38420. return this.clear( false, true, false );
  38421. }
  38422. clearStencil() {
  38423. return this.clear( false, false, true );
  38424. }
  38425. async clearAsync( color = true, depth = true, stencil = true ) {
  38426. if ( this._initialized === false ) await this.init();
  38427. this.clear( color, depth, stencil );
  38428. }
  38429. clearColorAsync() {
  38430. return this.clearAsync( true, false, false );
  38431. }
  38432. clearDepthAsync() {
  38433. return this.clearAsync( false, true, false );
  38434. }
  38435. clearStencilAsync() {
  38436. return this.clearAsync( false, false, true );
  38437. }
  38438. get currentToneMapping() {
  38439. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  38440. }
  38441. get currentColorSpace() {
  38442. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  38443. }
  38444. dispose() {
  38445. this.info.dispose();
  38446. this._animation.dispose();
  38447. this._objects.dispose();
  38448. this._pipelines.dispose();
  38449. this._nodes.dispose();
  38450. this._bindings.dispose();
  38451. this._renderLists.dispose();
  38452. this._renderContexts.dispose();
  38453. this._textures.dispose();
  38454. this.setRenderTarget( null );
  38455. this.setAnimationLoop( null );
  38456. }
  38457. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38458. this._renderTarget = renderTarget;
  38459. this._activeCubeFace = activeCubeFace;
  38460. this._activeMipmapLevel = activeMipmapLevel;
  38461. }
  38462. getRenderTarget() {
  38463. return this._renderTarget;
  38464. }
  38465. setRenderObjectFunction( renderObjectFunction ) {
  38466. this._renderObjectFunction = renderObjectFunction;
  38467. }
  38468. getRenderObjectFunction() {
  38469. return this._renderObjectFunction;
  38470. }
  38471. async computeAsync( computeNodes ) {
  38472. if ( this._initialized === false ) await this.init();
  38473. const nodeFrame = this._nodes.nodeFrame;
  38474. const previousRenderId = nodeFrame.renderId;
  38475. //
  38476. this.info.calls ++;
  38477. this.info.compute.calls ++;
  38478. this.info.compute.frameCalls ++;
  38479. nodeFrame.renderId = this.info.calls;
  38480. //
  38481. const backend = this.backend;
  38482. const pipelines = this._pipelines;
  38483. const bindings = this._bindings;
  38484. const nodes = this._nodes;
  38485. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38486. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38487. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38488. }
  38489. backend.beginCompute( computeNodes );
  38490. for ( const computeNode of computeList ) {
  38491. // onInit
  38492. if ( pipelines.has( computeNode ) === false ) {
  38493. const dispose = () => {
  38494. computeNode.removeEventListener( 'dispose', dispose );
  38495. pipelines.delete( computeNode );
  38496. bindings.delete( computeNode );
  38497. nodes.delete( computeNode );
  38498. };
  38499. computeNode.addEventListener( 'dispose', dispose );
  38500. //
  38501. computeNode.onInit( { renderer: this } );
  38502. }
  38503. nodes.updateForCompute( computeNode );
  38504. bindings.updateForCompute( computeNode );
  38505. const computeBindings = bindings.getForCompute( computeNode );
  38506. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38507. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38508. }
  38509. backend.finishCompute( computeNodes );
  38510. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  38511. //
  38512. nodeFrame.renderId = previousRenderId;
  38513. }
  38514. async hasFeatureAsync( name ) {
  38515. if ( this._initialized === false ) await this.init();
  38516. return this.backend.hasFeature( name );
  38517. }
  38518. hasFeature( name ) {
  38519. if ( this._initialized === false ) {
  38520. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38521. return false;
  38522. }
  38523. return this.backend.hasFeature( name );
  38524. }
  38525. copyFramebufferToTexture( framebufferTexture ) {
  38526. const renderContext = this._currentRenderContext;
  38527. this._textures.updateTexture( framebufferTexture );
  38528. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  38529. }
  38530. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38531. this._textures.updateTexture( srcTexture );
  38532. this._textures.updateTexture( dstTexture );
  38533. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  38534. }
  38535. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  38536. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  38537. }
  38538. _projectObject( object, camera, groupOrder, renderList ) {
  38539. if ( object.visible === false ) return;
  38540. const visible = object.layers.test( camera.layers );
  38541. if ( visible ) {
  38542. if ( object.isGroup ) {
  38543. groupOrder = object.renderOrder;
  38544. } else if ( object.isLOD ) {
  38545. if ( object.autoUpdate === true ) object.update( camera );
  38546. } else if ( object.isLight ) {
  38547. renderList.pushLight( object );
  38548. } else if ( object.isSprite ) {
  38549. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  38550. if ( this.sortObjects === true ) {
  38551. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38552. }
  38553. const geometry = object.geometry;
  38554. const material = object.material;
  38555. if ( material.visible ) {
  38556. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38557. }
  38558. }
  38559. } else if ( object.isLineLoop ) {
  38560. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38561. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38562. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  38563. const geometry = object.geometry;
  38564. const material = object.material;
  38565. if ( this.sortObjects === true ) {
  38566. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38567. _vector4
  38568. .copy( geometry.boundingSphere.center )
  38569. .applyMatrix4( object.matrixWorld )
  38570. .applyMatrix4( _projScreenMatrix );
  38571. }
  38572. if ( Array.isArray( material ) ) {
  38573. const groups = geometry.groups;
  38574. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38575. const group = groups[ i ];
  38576. const groupMaterial = material[ group.materialIndex ];
  38577. if ( groupMaterial && groupMaterial.visible ) {
  38578. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  38579. }
  38580. }
  38581. } else if ( material.visible ) {
  38582. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38583. }
  38584. }
  38585. }
  38586. }
  38587. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38588. const baseRenderList = renderList;
  38589. // replace render list
  38590. renderList = this._renderLists.get( object, camera );
  38591. renderList.begin();
  38592. baseRenderList.pushBundle( {
  38593. bundleGroup: object,
  38594. camera,
  38595. renderList,
  38596. } );
  38597. renderList.finish();
  38598. }
  38599. const children = object.children;
  38600. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38601. this._projectObject( children[ i ], camera, groupOrder, renderList );
  38602. }
  38603. }
  38604. _renderBundles( bundles, sceneRef, lightsNode ) {
  38605. for ( const bundle of bundles ) {
  38606. this._renderBundle( bundle, sceneRef, lightsNode );
  38607. }
  38608. }
  38609. _renderObjects( renderList, camera, scene, lightsNode ) {
  38610. // process renderable objects
  38611. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38612. const renderItem = renderList[ i ];
  38613. // @TODO: Add support for multiple materials per object. This will require to extract
  38614. // the material from the renderItem object and pass it with its group data to renderObject().
  38615. const { object, geometry, material, group } = renderItem;
  38616. if ( camera.isArrayCamera ) {
  38617. const cameras = camera.cameras;
  38618. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  38619. const camera2 = cameras[ j ];
  38620. if ( object.layers.test( camera2.layers ) ) {
  38621. const vp = camera2.viewport;
  38622. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  38623. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  38624. const viewportValue = this._currentRenderContext.viewportValue;
  38625. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  38626. viewportValue.minDepth = minDepth;
  38627. viewportValue.maxDepth = maxDepth;
  38628. this.backend.updateViewport( this._currentRenderContext );
  38629. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  38630. }
  38631. }
  38632. } else {
  38633. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  38634. }
  38635. }
  38636. }
  38637. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  38638. let overridePositionNode;
  38639. let overrideFragmentNode;
  38640. let overrideDepthNode;
  38641. //
  38642. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38643. //
  38644. if ( scene.overrideMaterial !== null ) {
  38645. const overrideMaterial = scene.overrideMaterial;
  38646. if ( material.positionNode && material.positionNode.isNode ) {
  38647. overridePositionNode = overrideMaterial.positionNode;
  38648. overrideMaterial.positionNode = material.positionNode;
  38649. }
  38650. if ( overrideMaterial.isShadowNodeMaterial ) {
  38651. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38652. if ( material.depthNode && material.depthNode.isNode ) {
  38653. overrideDepthNode = overrideMaterial.depthNode;
  38654. overrideMaterial.depthNode = material.depthNode;
  38655. }
  38656. if ( material.shadowNode && material.shadowNode.isNode ) {
  38657. overrideFragmentNode = overrideMaterial.fragmentNode;
  38658. overrideMaterial.fragmentNode = material.shadowNode;
  38659. }
  38660. if ( this.localClippingEnabled ) {
  38661. if ( material.clipShadows ) {
  38662. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  38663. overrideMaterial.clippingPlanes = material.clippingPlanes;
  38664. overrideMaterial.needsUpdate = true;
  38665. }
  38666. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  38667. overrideMaterial.clipIntersection = material.clipIntersection;
  38668. }
  38669. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  38670. overrideMaterial.clippingPlanes = null;
  38671. overrideMaterial.needsUpdate = true;
  38672. }
  38673. }
  38674. }
  38675. material = overrideMaterial;
  38676. }
  38677. //
  38678. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38679. material.side = BackSide;
  38680. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  38681. material.side = FrontSide;
  38682. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  38683. material.side = DoubleSide;
  38684. } else {
  38685. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  38686. }
  38687. //
  38688. if ( overridePositionNode !== undefined ) {
  38689. scene.overrideMaterial.positionNode = overridePositionNode;
  38690. }
  38691. if ( overrideDepthNode !== undefined ) {
  38692. scene.overrideMaterial.depthNode = overrideDepthNode;
  38693. }
  38694. if ( overrideFragmentNode !== undefined ) {
  38695. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  38696. }
  38697. //
  38698. object.onAfterRender( this, scene, camera, geometry, material, group );
  38699. }
  38700. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  38701. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38702. renderObject.drawRange = object.geometry.drawRange;
  38703. renderObject.group = group;
  38704. //
  38705. this._nodes.updateBefore( renderObject );
  38706. this._nodes.updateForRender( renderObject );
  38707. this._geometries.updateForRender( renderObject );
  38708. this._bindings.updateForRender( renderObject );
  38709. this._pipelines.updateForRender( renderObject );
  38710. //
  38711. if ( this._currentRenderBundle !== null ) {
  38712. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38713. renderBundleData.renderObjects.push( renderObject );
  38714. }
  38715. this.backend.draw( renderObject, this.info );
  38716. this._nodes.updateAfter( renderObject );
  38717. }
  38718. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  38719. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38720. //
  38721. this._nodes.updateBefore( renderObject );
  38722. this._nodes.updateForRender( renderObject );
  38723. this._geometries.updateForRender( renderObject );
  38724. this._bindings.updateForRender( renderObject );
  38725. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38726. this._nodes.updateAfter( renderObject );
  38727. }
  38728. get compute() {
  38729. return this.computeAsync;
  38730. }
  38731. get compile() {
  38732. return this.compileAsync;
  38733. }
  38734. }
  38735. class Binding {
  38736. constructor( name = '' ) {
  38737. this.name = name;
  38738. this.visibility = 0;
  38739. }
  38740. setVisibility( visibility ) {
  38741. this.visibility |= visibility;
  38742. }
  38743. clone() {
  38744. return Object.assign( new this.constructor(), this );
  38745. }
  38746. }
  38747. function getFloatLength( floatLength ) {
  38748. // ensure chunk size alignment (STD140 layout)
  38749. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38750. }
  38751. class Buffer extends Binding {
  38752. constructor( name, buffer = null ) {
  38753. super( name );
  38754. this.isBuffer = true;
  38755. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38756. this._buffer = buffer;
  38757. }
  38758. get byteLength() {
  38759. return getFloatLength( this._buffer.byteLength );
  38760. }
  38761. get buffer() {
  38762. return this._buffer;
  38763. }
  38764. update() {
  38765. return true;
  38766. }
  38767. }
  38768. class UniformBuffer extends Buffer {
  38769. constructor( name, buffer = null ) {
  38770. super( name, buffer );
  38771. this.isUniformBuffer = true;
  38772. }
  38773. }
  38774. let _id$4 = 0;
  38775. class NodeUniformBuffer extends UniformBuffer {
  38776. constructor( nodeUniform, groupNode ) {
  38777. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38778. this.nodeUniform = nodeUniform;
  38779. this.groupNode = groupNode;
  38780. }
  38781. get buffer() {
  38782. return this.nodeUniform.value;
  38783. }
  38784. }
  38785. class UniformsGroup extends UniformBuffer {
  38786. constructor( name ) {
  38787. super( name );
  38788. this.isUniformsGroup = true;
  38789. this._values = null;
  38790. // the order of uniforms in this array must match the order of uniforms in the shader
  38791. this.uniforms = [];
  38792. }
  38793. addUniform( uniform ) {
  38794. this.uniforms.push( uniform );
  38795. return this;
  38796. }
  38797. removeUniform( uniform ) {
  38798. const index = this.uniforms.indexOf( uniform );
  38799. if ( index !== - 1 ) {
  38800. this.uniforms.splice( index, 1 );
  38801. }
  38802. return this;
  38803. }
  38804. get values() {
  38805. if ( this._values === null ) {
  38806. this._values = Array.from( this.buffer );
  38807. }
  38808. return this._values;
  38809. }
  38810. get buffer() {
  38811. let buffer = this._buffer;
  38812. if ( buffer === null ) {
  38813. const byteLength = this.byteLength;
  38814. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38815. this._buffer = buffer;
  38816. }
  38817. return buffer;
  38818. }
  38819. get byteLength() {
  38820. let offset = 0; // global buffer offset in bytes
  38821. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38822. const uniform = this.uniforms[ i ];
  38823. const { boundary, itemSize } = uniform;
  38824. // offset within a single chunk in bytes
  38825. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38826. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38827. // conformance tests
  38828. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38829. // check for chunk overflow
  38830. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38831. } else if ( chunkOffset % boundary !== 0 ) {
  38832. // check for correct alignment
  38833. offset += ( chunkOffset % boundary );
  38834. }
  38835. uniform.offset = ( offset / this.bytesPerElement );
  38836. offset += ( itemSize * this.bytesPerElement );
  38837. }
  38838. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38839. }
  38840. update() {
  38841. let updated = false;
  38842. for ( const uniform of this.uniforms ) {
  38843. if ( this.updateByType( uniform ) === true ) {
  38844. updated = true;
  38845. }
  38846. }
  38847. return updated;
  38848. }
  38849. updateByType( uniform ) {
  38850. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38851. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38852. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38853. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38854. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38855. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38856. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38857. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38858. }
  38859. updateNumber( uniform ) {
  38860. let updated = false;
  38861. const a = this.values;
  38862. const v = uniform.getValue();
  38863. const offset = uniform.offset;
  38864. if ( a[ offset ] !== v ) {
  38865. const b = this.buffer;
  38866. b[ offset ] = a[ offset ] = v;
  38867. updated = true;
  38868. }
  38869. return updated;
  38870. }
  38871. updateVector2( uniform ) {
  38872. let updated = false;
  38873. const a = this.values;
  38874. const v = uniform.getValue();
  38875. const offset = uniform.offset;
  38876. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38877. const b = this.buffer;
  38878. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38879. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38880. updated = true;
  38881. }
  38882. return updated;
  38883. }
  38884. updateVector3( uniform ) {
  38885. let updated = false;
  38886. const a = this.values;
  38887. const v = uniform.getValue();
  38888. const offset = uniform.offset;
  38889. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38890. const b = this.buffer;
  38891. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38892. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38893. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38894. updated = true;
  38895. }
  38896. return updated;
  38897. }
  38898. updateVector4( uniform ) {
  38899. let updated = false;
  38900. const a = this.values;
  38901. const v = uniform.getValue();
  38902. const offset = uniform.offset;
  38903. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38904. const b = this.buffer;
  38905. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38906. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38907. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38908. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38909. updated = true;
  38910. }
  38911. return updated;
  38912. }
  38913. updateColor( uniform ) {
  38914. let updated = false;
  38915. const a = this.values;
  38916. const c = uniform.getValue();
  38917. const offset = uniform.offset;
  38918. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38919. const b = this.buffer;
  38920. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38921. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38922. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38923. updated = true;
  38924. }
  38925. return updated;
  38926. }
  38927. updateMatrix3( uniform ) {
  38928. let updated = false;
  38929. const a = this.values;
  38930. const e = uniform.getValue().elements;
  38931. const offset = uniform.offset;
  38932. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38933. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38934. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38935. const b = this.buffer;
  38936. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38937. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38938. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38939. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38940. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38941. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38942. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38943. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38944. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38945. updated = true;
  38946. }
  38947. return updated;
  38948. }
  38949. updateMatrix4( uniform ) {
  38950. let updated = false;
  38951. const a = this.values;
  38952. const e = uniform.getValue().elements;
  38953. const offset = uniform.offset;
  38954. if ( arraysEqual( a, e, offset ) === false ) {
  38955. const b = this.buffer;
  38956. b.set( e, offset );
  38957. setArray( a, e, offset );
  38958. updated = true;
  38959. }
  38960. return updated;
  38961. }
  38962. }
  38963. function setArray( a, b, offset ) {
  38964. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38965. a[ offset + i ] = b[ i ];
  38966. }
  38967. }
  38968. function arraysEqual( a, b, offset ) {
  38969. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38970. if ( a[ offset + i ] !== b[ i ] ) return false;
  38971. }
  38972. return true;
  38973. }
  38974. let _id$3 = 0;
  38975. class NodeUniformsGroup extends UniformsGroup {
  38976. constructor( name, groupNode ) {
  38977. super( name );
  38978. this.id = _id$3 ++;
  38979. this.groupNode = groupNode;
  38980. this.isNodeUniformsGroup = true;
  38981. }
  38982. getNodes() {
  38983. const nodes = [];
  38984. for ( const uniform of this.uniforms ) {
  38985. const node = uniform.nodeUniform.node;
  38986. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38987. nodes.push( node );
  38988. }
  38989. return nodes;
  38990. }
  38991. }
  38992. let _id$2 = 0;
  38993. class SampledTexture extends Binding {
  38994. constructor( name, texture ) {
  38995. super( name );
  38996. this.id = _id$2 ++;
  38997. this.texture = texture;
  38998. this.version = texture ? texture.version : 0;
  38999. this.store = false;
  39000. this.generation = null;
  39001. this.isSampledTexture = true;
  39002. }
  39003. needsBindingsUpdate( generation ) {
  39004. const { texture } = this;
  39005. if ( generation !== this.generation ) {
  39006. this.generation = generation;
  39007. return true;
  39008. }
  39009. return texture.isVideoTexture;
  39010. }
  39011. update() {
  39012. const { texture, version } = this;
  39013. if ( version !== texture.version ) {
  39014. this.version = texture.version;
  39015. return true;
  39016. }
  39017. return false;
  39018. }
  39019. }
  39020. class NodeSampledTexture extends SampledTexture {
  39021. constructor( name, textureNode, groupNode, access = null ) {
  39022. super( name, textureNode ? textureNode.value : null );
  39023. this.textureNode = textureNode;
  39024. this.groupNode = groupNode;
  39025. this.access = access;
  39026. }
  39027. needsBindingsUpdate( generation ) {
  39028. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39029. }
  39030. update() {
  39031. const { textureNode } = this;
  39032. if ( this.texture !== textureNode.value ) {
  39033. this.texture = textureNode.value;
  39034. return true;
  39035. }
  39036. return super.update();
  39037. }
  39038. }
  39039. class NodeSampledCubeTexture extends NodeSampledTexture {
  39040. constructor( name, textureNode, groupNode, access ) {
  39041. super( name, textureNode, groupNode, access );
  39042. this.isSampledCubeTexture = true;
  39043. }
  39044. }
  39045. class NodeSampledTexture3D extends NodeSampledTexture {
  39046. constructor( name, textureNode, groupNode, access ) {
  39047. super( name, textureNode, groupNode, access );
  39048. this.isSampledTexture3D = true;
  39049. }
  39050. }
  39051. const glslMethods = {
  39052. atan2: 'atan',
  39053. textureDimensions: 'textureSize',
  39054. equals: 'equal'
  39055. };
  39056. const precisionLib = {
  39057. low: 'lowp',
  39058. medium: 'mediump',
  39059. high: 'highp'
  39060. };
  39061. const supports$1 = {
  39062. swizzleAssign: true,
  39063. storageBuffer: false
  39064. };
  39065. const defaultPrecisions = `
  39066. precision highp float;
  39067. precision highp int;
  39068. precision highp sampler2D;
  39069. precision highp sampler3D;
  39070. precision highp samplerCube;
  39071. precision highp sampler2DArray;
  39072. precision highp usampler2D;
  39073. precision highp usampler3D;
  39074. precision highp usamplerCube;
  39075. precision highp usampler2DArray;
  39076. precision highp isampler2D;
  39077. precision highp isampler3D;
  39078. precision highp isamplerCube;
  39079. precision highp isampler2DArray;
  39080. precision lowp sampler2DShadow;
  39081. `;
  39082. class GLSLNodeBuilder extends NodeBuilder {
  39083. constructor( object, renderer ) {
  39084. super( object, renderer, new GLSLNodeParser() );
  39085. this.uniformGroups = {};
  39086. this.transforms = [];
  39087. this.extensions = {};
  39088. this.instanceBindGroups = false;
  39089. this.useComparisonMethod = true;
  39090. }
  39091. needsColorSpaceToLinearSRGB( texture ) {
  39092. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39093. }
  39094. getMethod( method ) {
  39095. return glslMethods[ method ] || method;
  39096. }
  39097. getOutputStructName() {
  39098. return '';
  39099. }
  39100. buildFunctionCode( shaderNode ) {
  39101. const layout = shaderNode.layout;
  39102. const flowData = this.flowShaderNode( shaderNode );
  39103. const parameters = [];
  39104. for ( const input of layout.inputs ) {
  39105. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39106. }
  39107. //
  39108. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39109. ${ flowData.vars }
  39110. ${ flowData.code }
  39111. return ${ flowData.result };
  39112. }`;
  39113. //
  39114. return code;
  39115. }
  39116. setupPBO( storageBufferNode ) {
  39117. const attribute = storageBufferNode.value;
  39118. if ( attribute.pbo === undefined ) {
  39119. const originalArray = attribute.array;
  39120. const numElements = attribute.count * attribute.itemSize;
  39121. const { itemSize } = attribute;
  39122. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39123. let format = isInteger ? RedIntegerFormat : RedFormat;
  39124. if ( itemSize === 2 ) {
  39125. format = isInteger ? RGIntegerFormat : RGFormat;
  39126. } else if ( itemSize === 3 ) {
  39127. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39128. } else if ( itemSize === 4 ) {
  39129. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39130. }
  39131. const typeMap = {
  39132. Float32Array: FloatType,
  39133. Uint8Array: UnsignedByteType,
  39134. Uint16Array: UnsignedShortType,
  39135. Uint32Array: UnsignedIntType,
  39136. Int8Array: ByteType,
  39137. Int16Array: ShortType,
  39138. Int32Array: IntType,
  39139. Uint8ClampedArray: UnsignedByteType,
  39140. };
  39141. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39142. let height = Math.ceil( ( numElements / itemSize ) / width );
  39143. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39144. const newSize = width * height * itemSize;
  39145. const newArray = new originalArray.constructor( newSize );
  39146. newArray.set( originalArray, 0 );
  39147. attribute.array = newArray;
  39148. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39149. pboTexture.needsUpdate = true;
  39150. pboTexture.isPBOTexture = true;
  39151. const pbo = new TextureNode( pboTexture, null, null );
  39152. pbo.setPrecision( 'high' );
  39153. attribute.pboNode = pbo;
  39154. attribute.pbo = pbo.value;
  39155. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39156. }
  39157. }
  39158. getPropertyName( node, shaderStage = this.shaderStage ) {
  39159. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39160. return shaderStage.charAt( 0 ) + '_' + node.name;
  39161. }
  39162. return super.getPropertyName( node, shaderStage );
  39163. }
  39164. generatePBO( storageArrayElementNode ) {
  39165. const { node, indexNode } = storageArrayElementNode;
  39166. const attribute = node.value;
  39167. if ( this.renderer.backend.has( attribute ) ) {
  39168. const attributeData = this.renderer.backend.get( attribute );
  39169. attributeData.pbo = attribute.pbo;
  39170. }
  39171. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39172. const textureName = this.getPropertyName( nodeUniform );
  39173. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39174. const indexSnippet = indexNode.build( this, 'uint' );
  39175. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39176. let propertyName = elementNodeData.propertyName;
  39177. if ( propertyName === undefined ) {
  39178. // property element
  39179. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39180. propertyName = this.getPropertyName( nodeVar );
  39181. // property size
  39182. const bufferNodeData = this.getDataFromNode( node );
  39183. let propertySizeName = bufferNodeData.propertySizeName;
  39184. if ( propertySizeName === undefined ) {
  39185. propertySizeName = propertyName + 'Size';
  39186. this.getVarFromNode( node, propertySizeName, 'uint' );
  39187. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  39188. bufferNodeData.propertySizeName = propertySizeName;
  39189. }
  39190. //
  39191. const { itemSize } = attribute;
  39192. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  39193. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  39194. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  39195. //
  39196. let prefix = 'vec4';
  39197. if ( attribute.pbo.type === UnsignedIntType ) {
  39198. prefix = 'uvec4';
  39199. } else if ( attribute.pbo.type === IntType ) {
  39200. prefix = 'ivec4';
  39201. }
  39202. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  39203. elementNodeData.propertyName = propertyName;
  39204. }
  39205. return propertyName;
  39206. }
  39207. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  39208. if ( depthSnippet ) {
  39209. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  39210. } else {
  39211. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  39212. }
  39213. }
  39214. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  39215. if ( texture.isDepthTexture ) {
  39216. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  39217. } else {
  39218. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  39219. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  39220. }
  39221. }
  39222. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  39223. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  39224. }
  39225. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  39226. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  39227. }
  39228. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  39229. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  39230. }
  39231. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  39232. if ( shaderStage === 'fragment' ) {
  39233. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  39234. } else {
  39235. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  39236. }
  39237. }
  39238. getVars( shaderStage ) {
  39239. const snippets = [];
  39240. const vars = this.vars[ shaderStage ];
  39241. if ( vars !== undefined ) {
  39242. for ( const variable of vars ) {
  39243. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  39244. }
  39245. }
  39246. return snippets.join( '\n\t' );
  39247. }
  39248. getUniforms( shaderStage ) {
  39249. const uniforms = this.uniforms[ shaderStage ];
  39250. const bindingSnippets = [];
  39251. const uniformGroups = {};
  39252. for ( const uniform of uniforms ) {
  39253. let snippet = null;
  39254. let group = false;
  39255. if ( uniform.type === 'texture' ) {
  39256. const texture = uniform.node.value;
  39257. let typePrefix = '';
  39258. if ( texture.isDataTexture === true ) {
  39259. if ( texture.type === UnsignedIntType ) {
  39260. typePrefix = 'u';
  39261. } else if ( texture.type === IntType ) {
  39262. typePrefix = 'i';
  39263. }
  39264. }
  39265. if ( texture.compareFunction ) {
  39266. snippet = `sampler2DShadow ${ uniform.name };`;
  39267. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39268. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39269. } else {
  39270. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39271. }
  39272. } else if ( uniform.type === 'cubeTexture' ) {
  39273. snippet = `samplerCube ${ uniform.name };`;
  39274. } else if ( uniform.type === 'texture3D' ) {
  39275. snippet = `sampler3D ${ uniform.name };`;
  39276. } else if ( uniform.type === 'buffer' ) {
  39277. const bufferNode = uniform.node;
  39278. const bufferType = this.getType( bufferNode.bufferType );
  39279. const bufferCount = bufferNode.bufferCount;
  39280. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39281. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39282. } else {
  39283. const vectorType = this.getVectorType( uniform.type );
  39284. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39285. group = true;
  39286. }
  39287. const precision = uniform.node.precision;
  39288. if ( precision !== null ) {
  39289. snippet = precisionLib[ precision ] + ' ' + snippet;
  39290. }
  39291. if ( group ) {
  39292. snippet = '\t' + snippet;
  39293. const groupName = uniform.groupNode.name;
  39294. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39295. groupSnippets.push( snippet );
  39296. } else {
  39297. snippet = 'uniform ' + snippet;
  39298. bindingSnippets.push( snippet );
  39299. }
  39300. }
  39301. let output = '';
  39302. for ( const name in uniformGroups ) {
  39303. const groupSnippets = uniformGroups[ name ];
  39304. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39305. }
  39306. output += bindingSnippets.join( '\n' );
  39307. return output;
  39308. }
  39309. getTypeFromAttribute( attribute ) {
  39310. let nodeType = super.getTypeFromAttribute( attribute );
  39311. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39312. let dataAttribute = attribute;
  39313. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39314. const array = dataAttribute.array;
  39315. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  39316. nodeType = nodeType.slice( 1 );
  39317. }
  39318. }
  39319. return nodeType;
  39320. }
  39321. getAttributes( shaderStage ) {
  39322. let snippet = '';
  39323. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39324. const attributes = this.getAttributesArray();
  39325. let location = 0;
  39326. for ( const attribute of attributes ) {
  39327. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39328. }
  39329. }
  39330. return snippet;
  39331. }
  39332. getStructMembers( struct ) {
  39333. const snippets = [];
  39334. const members = struct.getMemberTypes();
  39335. for ( let i = 0; i < members.length; i ++ ) {
  39336. const member = members[ i ];
  39337. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  39338. }
  39339. return snippets.join( '\n' );
  39340. }
  39341. getStructs( shaderStage ) {
  39342. const snippets = [];
  39343. const structs = this.structs[ shaderStage ];
  39344. if ( structs.length === 0 ) {
  39345. return 'layout( location = 0 ) out vec4 fragColor;\n';
  39346. }
  39347. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  39348. const struct = structs[ index ];
  39349. let snippet = '\n';
  39350. snippet += this.getStructMembers( struct );
  39351. snippet += '\n';
  39352. snippets.push( snippet );
  39353. }
  39354. return snippets.join( '\n\n' );
  39355. }
  39356. getVaryings( shaderStage ) {
  39357. let snippet = '';
  39358. const varyings = this.varyings;
  39359. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39360. for ( const varying of varyings ) {
  39361. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  39362. const type = varying.type;
  39363. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39364. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  39365. }
  39366. } else if ( shaderStage === 'fragment' ) {
  39367. for ( const varying of varyings ) {
  39368. if ( varying.needsInterpolation ) {
  39369. const type = varying.type;
  39370. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39371. snippet += `${flat}in ${type} ${varying.name};\n`;
  39372. }
  39373. }
  39374. }
  39375. return snippet;
  39376. }
  39377. getVertexIndex() {
  39378. return 'uint( gl_VertexID )';
  39379. }
  39380. getInstanceIndex() {
  39381. return 'uint( gl_InstanceID )';
  39382. }
  39383. getInvocationLocalIndex() {
  39384. const workgroupSize = this.object.workgroupSize;
  39385. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  39386. return `uint( gl_InstanceID ) % ${size}u`;
  39387. }
  39388. getDrawIndex() {
  39389. const extensions = this.renderer.backend.extensions;
  39390. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  39391. return 'uint( gl_DrawID )';
  39392. }
  39393. return null;
  39394. }
  39395. getFrontFacing() {
  39396. return 'gl_FrontFacing';
  39397. }
  39398. getFragCoord() {
  39399. return 'gl_FragCoord.xy';
  39400. }
  39401. getFragDepth() {
  39402. return 'gl_FragDepth';
  39403. }
  39404. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  39405. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  39406. if ( map.has( name ) === false ) {
  39407. map.set( name, {
  39408. name,
  39409. behavior
  39410. } );
  39411. }
  39412. }
  39413. getExtensions( shaderStage ) {
  39414. const snippets = [];
  39415. if ( shaderStage === 'vertex' ) {
  39416. const ext = this.renderer.backend.extensions;
  39417. const isBatchedMesh = this.object.isBatchedMesh;
  39418. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  39419. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  39420. }
  39421. }
  39422. const extensions = this.extensions[ shaderStage ];
  39423. if ( extensions !== undefined ) {
  39424. for ( const { name, behavior } of extensions.values() ) {
  39425. snippets.push( `#extension ${name} : ${behavior}` );
  39426. }
  39427. }
  39428. return snippets.join( '\n' );
  39429. }
  39430. isAvailable( name ) {
  39431. let result = supports$1[ name ];
  39432. if ( result === undefined ) {
  39433. if ( name === 'float32Filterable' ) {
  39434. const extensions = this.renderer.backend.extensions;
  39435. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  39436. extensions.get( 'OES_texture_float_linear' );
  39437. result = true;
  39438. } else {
  39439. result = false;
  39440. }
  39441. }
  39442. supports$1[ name ] = result;
  39443. }
  39444. return result;
  39445. }
  39446. isFlipY() {
  39447. return true;
  39448. }
  39449. registerTransform( varyingName, attributeNode ) {
  39450. this.transforms.push( { varyingName, attributeNode } );
  39451. }
  39452. getTransforms( /* shaderStage */ ) {
  39453. const transforms = this.transforms;
  39454. let snippet = '';
  39455. for ( let i = 0; i < transforms.length; i ++ ) {
  39456. const transform = transforms[ i ];
  39457. const attributeName = this.getPropertyName( transform.attributeNode );
  39458. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  39459. }
  39460. return snippet;
  39461. }
  39462. _getGLSLUniformStruct( name, vars ) {
  39463. return `
  39464. layout( std140 ) uniform ${name} {
  39465. ${vars}
  39466. };`;
  39467. }
  39468. _getGLSLVertexCode( shaderData ) {
  39469. return `#version 300 es
  39470. ${ this.getSignature() }
  39471. // extensions
  39472. ${shaderData.extensions}
  39473. // precision
  39474. ${ defaultPrecisions }
  39475. // uniforms
  39476. ${shaderData.uniforms}
  39477. // varyings
  39478. ${shaderData.varyings}
  39479. // attributes
  39480. ${shaderData.attributes}
  39481. // codes
  39482. ${shaderData.codes}
  39483. void main() {
  39484. // vars
  39485. ${shaderData.vars}
  39486. // transforms
  39487. ${shaderData.transforms}
  39488. // flow
  39489. ${shaderData.flow}
  39490. gl_PointSize = 1.0;
  39491. }
  39492. `;
  39493. }
  39494. _getGLSLFragmentCode( shaderData ) {
  39495. return `#version 300 es
  39496. ${ this.getSignature() }
  39497. // precision
  39498. ${ defaultPrecisions }
  39499. // uniforms
  39500. ${shaderData.uniforms}
  39501. // varyings
  39502. ${shaderData.varyings}
  39503. // codes
  39504. ${shaderData.codes}
  39505. ${shaderData.structs}
  39506. void main() {
  39507. // vars
  39508. ${shaderData.vars}
  39509. // flow
  39510. ${shaderData.flow}
  39511. }
  39512. `;
  39513. }
  39514. buildCode() {
  39515. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39516. for ( const shaderStage in shadersData ) {
  39517. let flow = '// code\n\n';
  39518. flow += this.flowCode[ shaderStage ];
  39519. const flowNodes = this.flowNodes[ shaderStage ];
  39520. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39521. for ( const node of flowNodes ) {
  39522. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39523. const slotName = node.name;
  39524. if ( slotName ) {
  39525. if ( flow.length > 0 ) flow += '\n';
  39526. flow += `\t// flow -> ${ slotName }\n\t`;
  39527. }
  39528. flow += `${ flowSlotData.code }\n\t`;
  39529. if ( node === mainNode && shaderStage !== 'compute' ) {
  39530. flow += '// result\n\t';
  39531. if ( shaderStage === 'vertex' ) {
  39532. flow += 'gl_Position = ';
  39533. flow += `${ flowSlotData.result };`;
  39534. } else if ( shaderStage === 'fragment' ) {
  39535. if ( ! node.outputNode.isOutputStructNode ) {
  39536. flow += 'fragColor = ';
  39537. flow += `${ flowSlotData.result };`;
  39538. }
  39539. }
  39540. }
  39541. }
  39542. const stageData = shadersData[ shaderStage ];
  39543. stageData.extensions = this.getExtensions( shaderStage );
  39544. stageData.uniforms = this.getUniforms( shaderStage );
  39545. stageData.attributes = this.getAttributes( shaderStage );
  39546. stageData.varyings = this.getVaryings( shaderStage );
  39547. stageData.vars = this.getVars( shaderStage );
  39548. stageData.structs = this.getStructs( shaderStage );
  39549. stageData.codes = this.getCodes( shaderStage );
  39550. stageData.transforms = this.getTransforms( shaderStage );
  39551. stageData.flow = flow;
  39552. }
  39553. if ( this.material !== null ) {
  39554. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39555. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39556. } else {
  39557. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39558. }
  39559. }
  39560. getUniformFromNode( node, type, shaderStage, name = null ) {
  39561. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39562. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39563. let uniformGPU = nodeData.uniformGPU;
  39564. if ( uniformGPU === undefined ) {
  39565. const group = node.groupNode;
  39566. const groupName = group.name;
  39567. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39568. if ( type === 'texture' ) {
  39569. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39570. bindings.push( uniformGPU );
  39571. } else if ( type === 'cubeTexture' ) {
  39572. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39573. bindings.push( uniformGPU );
  39574. } else if ( type === 'texture3D' ) {
  39575. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39576. bindings.push( uniformGPU );
  39577. } else if ( type === 'buffer' ) {
  39578. node.name = `NodeBuffer_${ node.id }`;
  39579. uniformNode.name = `buffer${ node.id }`;
  39580. const buffer = new NodeUniformBuffer( node, group );
  39581. buffer.name = node.name;
  39582. bindings.push( buffer );
  39583. uniformGPU = buffer;
  39584. } else {
  39585. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39586. let uniformsGroup = uniformsStage[ groupName ];
  39587. if ( uniformsGroup === undefined ) {
  39588. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39589. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39590. uniformsStage[ groupName ] = uniformsGroup;
  39591. bindings.push( uniformsGroup );
  39592. }
  39593. uniformGPU = this.getNodeUniform( uniformNode, type );
  39594. uniformsGroup.addUniform( uniformGPU );
  39595. }
  39596. nodeData.uniformGPU = uniformGPU;
  39597. }
  39598. return uniformNode;
  39599. }
  39600. }
  39601. let vector2 = null;
  39602. let vector4 = null;
  39603. let color4 = null;
  39604. class Backend {
  39605. constructor( parameters = {} ) {
  39606. this.parameters = Object.assign( {}, parameters );
  39607. this.data = new WeakMap();
  39608. this.renderer = null;
  39609. this.domElement = null;
  39610. }
  39611. async init( renderer ) {
  39612. this.renderer = renderer;
  39613. }
  39614. // render context
  39615. begin( /*renderContext*/ ) { }
  39616. finish( /*renderContext*/ ) { }
  39617. // render object
  39618. draw( /*renderObject, info*/ ) { }
  39619. // program
  39620. createProgram( /*program*/ ) { }
  39621. destroyProgram( /*program*/ ) { }
  39622. // bindings
  39623. createBindings( /*bingGroup, bindings*/ ) { }
  39624. updateBindings( /*bingGroup, bindings*/ ) { }
  39625. // pipeline
  39626. createRenderPipeline( /*renderObject*/ ) { }
  39627. createComputePipeline( /*computeNode, pipeline*/ ) { }
  39628. destroyPipeline( /*pipeline*/ ) { }
  39629. // cache key
  39630. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  39631. getRenderCacheKey( /*renderObject*/ ) { } // return String
  39632. // node builder
  39633. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  39634. // textures
  39635. createSampler( /*texture*/ ) { }
  39636. createDefaultTexture( /*texture*/ ) { }
  39637. createTexture( /*texture*/ ) { }
  39638. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  39639. // attributes
  39640. createAttribute( /*attribute*/ ) { }
  39641. createIndexAttribute( /*attribute*/ ) { }
  39642. updateAttribute( /*attribute*/ ) { }
  39643. destroyAttribute( /*attribute*/ ) { }
  39644. // canvas
  39645. getContext() { }
  39646. updateSize() { }
  39647. // utils
  39648. resolveTimestampAsync( /*renderContext, type*/ ) { }
  39649. hasFeatureAsync( /*name*/ ) { } // return Boolean
  39650. hasFeature( /*name*/ ) { } // return Boolean
  39651. getInstanceCount( renderObject ) {
  39652. const { object, geometry } = renderObject;
  39653. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  39654. }
  39655. getDrawingBufferSize() {
  39656. vector2 = vector2 || new Vector2();
  39657. return this.renderer.getDrawingBufferSize( vector2 );
  39658. }
  39659. getScissor() {
  39660. vector4 = vector4 || new Vector4();
  39661. return this.renderer.getScissor( vector4 );
  39662. }
  39663. setScissorTest( /*boolean*/ ) { }
  39664. getClearColor() {
  39665. const renderer = this.renderer;
  39666. color4 = color4 || new Color4();
  39667. renderer.getClearColor( color4 );
  39668. color4.getRGB( color4, this.renderer.currentColorSpace );
  39669. return color4;
  39670. }
  39671. getDomElement() {
  39672. let domElement = this.domElement;
  39673. if ( domElement === null ) {
  39674. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39675. // OffscreenCanvas does not have setAttribute, see #22811
  39676. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39677. this.domElement = domElement;
  39678. }
  39679. return domElement;
  39680. }
  39681. // resource properties
  39682. set( object, value ) {
  39683. this.data.set( object, value );
  39684. }
  39685. get( object ) {
  39686. let map = this.data.get( object );
  39687. if ( map === undefined ) {
  39688. map = {};
  39689. this.data.set( object, map );
  39690. }
  39691. return map;
  39692. }
  39693. has( object ) {
  39694. return this.data.has( object );
  39695. }
  39696. delete( object ) {
  39697. this.data.delete( object );
  39698. }
  39699. }
  39700. let _id$1 = 0;
  39701. class DualAttributeData {
  39702. constructor( attributeData, dualBuffer ) {
  39703. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39704. this.type = attributeData.type;
  39705. this.bufferType = attributeData.bufferType;
  39706. this.pbo = attributeData.pbo;
  39707. this.byteLength = attributeData.byteLength;
  39708. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39709. this.version = attributeData.version;
  39710. this.isInteger = attributeData.isInteger;
  39711. this.activeBufferIndex = 0;
  39712. this.baseId = attributeData.id;
  39713. }
  39714. get id() {
  39715. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39716. }
  39717. get bufferGPU() {
  39718. return this.buffers[ this.activeBufferIndex ];
  39719. }
  39720. get transformBuffer() {
  39721. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39722. }
  39723. switchBuffers() {
  39724. this.activeBufferIndex ^= 1;
  39725. }
  39726. }
  39727. class WebGLAttributeUtils {
  39728. constructor( backend ) {
  39729. this.backend = backend;
  39730. }
  39731. createAttribute( attribute, bufferType ) {
  39732. const backend = this.backend;
  39733. const { gl } = backend;
  39734. const array = attribute.array;
  39735. const usage = attribute.usage || gl.STATIC_DRAW;
  39736. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39737. const bufferData = backend.get( bufferAttribute );
  39738. let bufferGPU = bufferData.bufferGPU;
  39739. if ( bufferGPU === undefined ) {
  39740. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39741. bufferData.bufferGPU = bufferGPU;
  39742. bufferData.bufferType = bufferType;
  39743. bufferData.version = bufferAttribute.version;
  39744. }
  39745. //attribute.onUploadCallback();
  39746. let type;
  39747. if ( array instanceof Float32Array ) {
  39748. type = gl.FLOAT;
  39749. } else if ( array instanceof Uint16Array ) {
  39750. if ( attribute.isFloat16BufferAttribute ) {
  39751. type = gl.HALF_FLOAT;
  39752. } else {
  39753. type = gl.UNSIGNED_SHORT;
  39754. }
  39755. } else if ( array instanceof Int16Array ) {
  39756. type = gl.SHORT;
  39757. } else if ( array instanceof Uint32Array ) {
  39758. type = gl.UNSIGNED_INT;
  39759. } else if ( array instanceof Int32Array ) {
  39760. type = gl.INT;
  39761. } else if ( array instanceof Int8Array ) {
  39762. type = gl.BYTE;
  39763. } else if ( array instanceof Uint8Array ) {
  39764. type = gl.UNSIGNED_BYTE;
  39765. } else if ( array instanceof Uint8ClampedArray ) {
  39766. type = gl.UNSIGNED_BYTE;
  39767. } else {
  39768. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39769. }
  39770. let attributeData = {
  39771. bufferGPU,
  39772. bufferType,
  39773. type,
  39774. byteLength: array.byteLength,
  39775. bytesPerElement: array.BYTES_PER_ELEMENT,
  39776. version: attribute.version,
  39777. pbo: attribute.pbo,
  39778. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39779. id: _id$1 ++
  39780. };
  39781. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39782. // create buffer for tranform feedback use
  39783. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39784. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39785. }
  39786. backend.set( attribute, attributeData );
  39787. }
  39788. updateAttribute( attribute ) {
  39789. const backend = this.backend;
  39790. const { gl } = backend;
  39791. const array = attribute.array;
  39792. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39793. const bufferData = backend.get( bufferAttribute );
  39794. const bufferType = bufferData.bufferType;
  39795. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39796. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39797. if ( updateRanges.length === 0 ) {
  39798. // Not using update ranges
  39799. gl.bufferSubData( bufferType, 0, array );
  39800. } else {
  39801. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39802. const range = updateRanges[ i ];
  39803. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39804. array, range.start, range.count );
  39805. }
  39806. bufferAttribute.clearUpdateRanges();
  39807. }
  39808. gl.bindBuffer( bufferType, null );
  39809. bufferData.version = bufferAttribute.version;
  39810. }
  39811. destroyAttribute( attribute ) {
  39812. const backend = this.backend;
  39813. const { gl } = backend;
  39814. if ( attribute.isInterleavedBufferAttribute ) {
  39815. backend.delete( attribute.data );
  39816. }
  39817. const attributeData = backend.get( attribute );
  39818. gl.deleteBuffer( attributeData.bufferGPU );
  39819. backend.delete( attribute );
  39820. }
  39821. async getArrayBufferAsync( attribute ) {
  39822. const backend = this.backend;
  39823. const { gl } = backend;
  39824. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39825. const { bufferGPU } = backend.get( bufferAttribute );
  39826. const array = attribute.array;
  39827. const byteLength = array.byteLength;
  39828. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39829. const writeBuffer = gl.createBuffer();
  39830. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39831. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39832. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39833. await backend.utils._clientWaitAsync();
  39834. const dstBuffer = new attribute.array.constructor( array.length );
  39835. // Ensure the buffer is bound before reading
  39836. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39837. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39838. gl.deleteBuffer( writeBuffer );
  39839. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39840. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39841. return dstBuffer.buffer;
  39842. }
  39843. _createBuffer( gl, bufferType, array, usage ) {
  39844. const bufferGPU = gl.createBuffer();
  39845. gl.bindBuffer( bufferType, bufferGPU );
  39846. gl.bufferData( bufferType, array, usage );
  39847. gl.bindBuffer( bufferType, null );
  39848. return bufferGPU;
  39849. }
  39850. }
  39851. let initialized$1 = false, equationToGL, factorToGL;
  39852. class WebGLState {
  39853. constructor( backend ) {
  39854. this.backend = backend;
  39855. this.gl = this.backend.gl;
  39856. this.enabled = {};
  39857. this.currentFlipSided = null;
  39858. this.currentCullFace = null;
  39859. this.currentProgram = null;
  39860. this.currentBlendingEnabled = false;
  39861. this.currentBlending = null;
  39862. this.currentBlendSrc = null;
  39863. this.currentBlendDst = null;
  39864. this.currentBlendSrcAlpha = null;
  39865. this.currentBlendDstAlpha = null;
  39866. this.currentPremultipledAlpha = null;
  39867. this.currentPolygonOffsetFactor = null;
  39868. this.currentPolygonOffsetUnits = null;
  39869. this.currentColorMask = null;
  39870. this.currentDepthFunc = null;
  39871. this.currentDepthMask = null;
  39872. this.currentStencilFunc = null;
  39873. this.currentStencilRef = null;
  39874. this.currentStencilFuncMask = null;
  39875. this.currentStencilFail = null;
  39876. this.currentStencilZFail = null;
  39877. this.currentStencilZPass = null;
  39878. this.currentStencilMask = null;
  39879. this.currentLineWidth = null;
  39880. this.currentBoundFramebuffers = {};
  39881. this.currentDrawbuffers = new WeakMap();
  39882. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39883. this.currentTextureSlot = null;
  39884. this.currentBoundTextures = {};
  39885. this.currentBoundBufferBases = {};
  39886. if ( initialized$1 === false ) {
  39887. this._init( this.gl );
  39888. initialized$1 = true;
  39889. }
  39890. }
  39891. _init( gl ) {
  39892. // Store only WebGL constants here.
  39893. equationToGL = {
  39894. [ AddEquation ]: gl.FUNC_ADD,
  39895. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39896. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39897. };
  39898. factorToGL = {
  39899. [ ZeroFactor ]: gl.ZERO,
  39900. [ OneFactor ]: gl.ONE,
  39901. [ SrcColorFactor ]: gl.SRC_COLOR,
  39902. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39903. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39904. [ DstColorFactor ]: gl.DST_COLOR,
  39905. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39906. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39907. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39908. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39909. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39910. };
  39911. }
  39912. enable( id ) {
  39913. const { enabled } = this;
  39914. if ( enabled[ id ] !== true ) {
  39915. this.gl.enable( id );
  39916. enabled[ id ] = true;
  39917. }
  39918. }
  39919. disable( id ) {
  39920. const { enabled } = this;
  39921. if ( enabled[ id ] !== false ) {
  39922. this.gl.disable( id );
  39923. enabled[ id ] = false;
  39924. }
  39925. }
  39926. setFlipSided( flipSided ) {
  39927. if ( this.currentFlipSided !== flipSided ) {
  39928. const { gl } = this;
  39929. if ( flipSided ) {
  39930. gl.frontFace( gl.CW );
  39931. } else {
  39932. gl.frontFace( gl.CCW );
  39933. }
  39934. this.currentFlipSided = flipSided;
  39935. }
  39936. }
  39937. setCullFace( cullFace ) {
  39938. const { gl } = this;
  39939. if ( cullFace !== CullFaceNone ) {
  39940. this.enable( gl.CULL_FACE );
  39941. if ( cullFace !== this.currentCullFace ) {
  39942. if ( cullFace === CullFaceBack ) {
  39943. gl.cullFace( gl.BACK );
  39944. } else if ( cullFace === CullFaceFront ) {
  39945. gl.cullFace( gl.FRONT );
  39946. } else {
  39947. gl.cullFace( gl.FRONT_AND_BACK );
  39948. }
  39949. }
  39950. } else {
  39951. this.disable( gl.CULL_FACE );
  39952. }
  39953. this.currentCullFace = cullFace;
  39954. }
  39955. setLineWidth( width ) {
  39956. const { currentLineWidth, gl } = this;
  39957. if ( width !== currentLineWidth ) {
  39958. gl.lineWidth( width );
  39959. this.currentLineWidth = width;
  39960. }
  39961. }
  39962. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39963. const { gl } = this;
  39964. if ( blending === NoBlending ) {
  39965. if ( this.currentBlendingEnabled === true ) {
  39966. this.disable( gl.BLEND );
  39967. this.currentBlendingEnabled = false;
  39968. }
  39969. return;
  39970. }
  39971. if ( this.currentBlendingEnabled === false ) {
  39972. this.enable( gl.BLEND );
  39973. this.currentBlendingEnabled = true;
  39974. }
  39975. if ( blending !== CustomBlending ) {
  39976. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39977. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39978. gl.blendEquation( gl.FUNC_ADD );
  39979. this.currentBlendEquation = AddEquation;
  39980. this.currentBlendEquationAlpha = AddEquation;
  39981. }
  39982. if ( premultipliedAlpha ) {
  39983. switch ( blending ) {
  39984. case NormalBlending:
  39985. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39986. break;
  39987. case AdditiveBlending:
  39988. gl.blendFunc( gl.ONE, gl.ONE );
  39989. break;
  39990. case SubtractiveBlending:
  39991. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39992. break;
  39993. case MultiplyBlending:
  39994. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39995. break;
  39996. default:
  39997. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39998. break;
  39999. }
  40000. } else {
  40001. switch ( blending ) {
  40002. case NormalBlending:
  40003. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40004. break;
  40005. case AdditiveBlending:
  40006. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  40007. break;
  40008. case SubtractiveBlending:
  40009. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40010. break;
  40011. case MultiplyBlending:
  40012. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  40013. break;
  40014. default:
  40015. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40016. break;
  40017. }
  40018. }
  40019. this.currentBlendSrc = null;
  40020. this.currentBlendDst = null;
  40021. this.currentBlendSrcAlpha = null;
  40022. this.currentBlendDstAlpha = null;
  40023. this.currentBlending = blending;
  40024. this.currentPremultipledAlpha = premultipliedAlpha;
  40025. }
  40026. return;
  40027. }
  40028. // custom blending
  40029. blendEquationAlpha = blendEquationAlpha || blendEquation;
  40030. blendSrcAlpha = blendSrcAlpha || blendSrc;
  40031. blendDstAlpha = blendDstAlpha || blendDst;
  40032. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  40033. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  40034. this.currentBlendEquation = blendEquation;
  40035. this.currentBlendEquationAlpha = blendEquationAlpha;
  40036. }
  40037. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  40038. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  40039. this.currentBlendSrc = blendSrc;
  40040. this.currentBlendDst = blendDst;
  40041. this.currentBlendSrcAlpha = blendSrcAlpha;
  40042. this.currentBlendDstAlpha = blendDstAlpha;
  40043. }
  40044. this.currentBlending = blending;
  40045. this.currentPremultipledAlpha = false;
  40046. }
  40047. setColorMask( colorMask ) {
  40048. if ( this.currentColorMask !== colorMask ) {
  40049. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  40050. this.currentColorMask = colorMask;
  40051. }
  40052. }
  40053. setDepthTest( depthTest ) {
  40054. const { gl } = this;
  40055. if ( depthTest ) {
  40056. this.enable( gl.DEPTH_TEST );
  40057. } else {
  40058. this.disable( gl.DEPTH_TEST );
  40059. }
  40060. }
  40061. setDepthMask( depthMask ) {
  40062. if ( this.currentDepthMask !== depthMask ) {
  40063. this.gl.depthMask( depthMask );
  40064. this.currentDepthMask = depthMask;
  40065. }
  40066. }
  40067. setDepthFunc( depthFunc ) {
  40068. if ( this.currentDepthFunc !== depthFunc ) {
  40069. const { gl } = this;
  40070. switch ( depthFunc ) {
  40071. case NeverDepth:
  40072. gl.depthFunc( gl.NEVER );
  40073. break;
  40074. case AlwaysDepth:
  40075. gl.depthFunc( gl.ALWAYS );
  40076. break;
  40077. case LessDepth:
  40078. gl.depthFunc( gl.LESS );
  40079. break;
  40080. case LessEqualDepth:
  40081. gl.depthFunc( gl.LEQUAL );
  40082. break;
  40083. case EqualDepth:
  40084. gl.depthFunc( gl.EQUAL );
  40085. break;
  40086. case GreaterEqualDepth:
  40087. gl.depthFunc( gl.GEQUAL );
  40088. break;
  40089. case GreaterDepth:
  40090. gl.depthFunc( gl.GREATER );
  40091. break;
  40092. case NotEqualDepth:
  40093. gl.depthFunc( gl.NOTEQUAL );
  40094. break;
  40095. default:
  40096. gl.depthFunc( gl.LEQUAL );
  40097. }
  40098. this.currentDepthFunc = depthFunc;
  40099. }
  40100. }
  40101. setStencilTest( stencilTest ) {
  40102. const { gl } = this;
  40103. if ( stencilTest ) {
  40104. this.enable( gl.STENCIL_TEST );
  40105. } else {
  40106. this.disable( gl.STENCIL_TEST );
  40107. }
  40108. }
  40109. setStencilMask( stencilMask ) {
  40110. if ( this.currentStencilMask !== stencilMask ) {
  40111. this.gl.stencilMask( stencilMask );
  40112. this.currentStencilMask = stencilMask;
  40113. }
  40114. }
  40115. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  40116. if ( this.currentStencilFunc !== stencilFunc ||
  40117. this.currentStencilRef !== stencilRef ||
  40118. this.currentStencilFuncMask !== stencilMask ) {
  40119. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  40120. this.currentStencilFunc = stencilFunc;
  40121. this.currentStencilRef = stencilRef;
  40122. this.currentStencilFuncMask = stencilMask;
  40123. }
  40124. }
  40125. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  40126. if ( this.currentStencilFail !== stencilFail ||
  40127. this.currentStencilZFail !== stencilZFail ||
  40128. this.currentStencilZPass !== stencilZPass ) {
  40129. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  40130. this.currentStencilFail = stencilFail;
  40131. this.currentStencilZFail = stencilZFail;
  40132. this.currentStencilZPass = stencilZPass;
  40133. }
  40134. }
  40135. setMaterial( material, frontFaceCW ) {
  40136. const { gl } = this;
  40137. material.side === DoubleSide
  40138. ? this.disable( gl.CULL_FACE )
  40139. : this.enable( gl.CULL_FACE );
  40140. let flipSided = ( material.side === BackSide );
  40141. if ( frontFaceCW ) flipSided = ! flipSided;
  40142. this.setFlipSided( flipSided );
  40143. ( material.blending === NormalBlending && material.transparent === false )
  40144. ? this.setBlending( NoBlending )
  40145. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  40146. this.setDepthFunc( material.depthFunc );
  40147. this.setDepthTest( material.depthTest );
  40148. this.setDepthMask( material.depthWrite );
  40149. this.setColorMask( material.colorWrite );
  40150. const stencilWrite = material.stencilWrite;
  40151. this.setStencilTest( stencilWrite );
  40152. if ( stencilWrite ) {
  40153. this.setStencilMask( material.stencilWriteMask );
  40154. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  40155. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  40156. }
  40157. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  40158. material.alphaToCoverage === true
  40159. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  40160. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  40161. }
  40162. setPolygonOffset( polygonOffset, factor, units ) {
  40163. const { gl } = this;
  40164. if ( polygonOffset ) {
  40165. this.enable( gl.POLYGON_OFFSET_FILL );
  40166. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  40167. gl.polygonOffset( factor, units );
  40168. this.currentPolygonOffsetFactor = factor;
  40169. this.currentPolygonOffsetUnits = units;
  40170. }
  40171. } else {
  40172. this.disable( gl.POLYGON_OFFSET_FILL );
  40173. }
  40174. }
  40175. useProgram( program ) {
  40176. if ( this.currentProgram !== program ) {
  40177. this.gl.useProgram( program );
  40178. this.currentProgram = program;
  40179. return true;
  40180. }
  40181. return false;
  40182. }
  40183. // framebuffer
  40184. bindFramebuffer( target, framebuffer ) {
  40185. const { gl, currentBoundFramebuffers } = this;
  40186. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  40187. gl.bindFramebuffer( target, framebuffer );
  40188. currentBoundFramebuffers[ target ] = framebuffer;
  40189. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  40190. if ( target === gl.DRAW_FRAMEBUFFER ) {
  40191. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  40192. }
  40193. if ( target === gl.FRAMEBUFFER ) {
  40194. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  40195. }
  40196. return true;
  40197. }
  40198. return false;
  40199. }
  40200. drawBuffers( renderContext, framebuffer ) {
  40201. const { gl } = this;
  40202. let drawBuffers = [];
  40203. let needsUpdate = false;
  40204. if ( renderContext.textures !== null ) {
  40205. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  40206. if ( drawBuffers === undefined ) {
  40207. drawBuffers = [];
  40208. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  40209. }
  40210. const textures = renderContext.textures;
  40211. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  40212. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  40213. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  40214. }
  40215. drawBuffers.length = textures.length;
  40216. needsUpdate = true;
  40217. }
  40218. } else {
  40219. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  40220. drawBuffers[ 0 ] = gl.BACK;
  40221. needsUpdate = true;
  40222. }
  40223. }
  40224. if ( needsUpdate ) {
  40225. gl.drawBuffers( drawBuffers );
  40226. }
  40227. }
  40228. // texture
  40229. activeTexture( webglSlot ) {
  40230. const { gl, currentTextureSlot, maxTextures } = this;
  40231. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40232. if ( currentTextureSlot !== webglSlot ) {
  40233. gl.activeTexture( webglSlot );
  40234. this.currentTextureSlot = webglSlot;
  40235. }
  40236. }
  40237. bindTexture( webglType, webglTexture, webglSlot ) {
  40238. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  40239. if ( webglSlot === undefined ) {
  40240. if ( currentTextureSlot === null ) {
  40241. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40242. } else {
  40243. webglSlot = currentTextureSlot;
  40244. }
  40245. }
  40246. let boundTexture = currentBoundTextures[ webglSlot ];
  40247. if ( boundTexture === undefined ) {
  40248. boundTexture = { type: undefined, texture: undefined };
  40249. currentBoundTextures[ webglSlot ] = boundTexture;
  40250. }
  40251. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  40252. if ( currentTextureSlot !== webglSlot ) {
  40253. gl.activeTexture( webglSlot );
  40254. this.currentTextureSlot = webglSlot;
  40255. }
  40256. gl.bindTexture( webglType, webglTexture );
  40257. boundTexture.type = webglType;
  40258. boundTexture.texture = webglTexture;
  40259. }
  40260. }
  40261. bindBufferBase( target, index, buffer ) {
  40262. const { gl } = this;
  40263. const key = `${target}-${index}`;
  40264. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  40265. gl.bindBufferBase( target, index, buffer );
  40266. this.currentBoundBufferBases[ key ] = buffer;
  40267. return true;
  40268. }
  40269. return false;
  40270. }
  40271. unbindTexture() {
  40272. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40273. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40274. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40275. gl.bindTexture( boundTexture.type, null );
  40276. boundTexture.type = undefined;
  40277. boundTexture.texture = undefined;
  40278. }
  40279. }
  40280. }
  40281. class WebGLUtils {
  40282. constructor( backend ) {
  40283. this.backend = backend;
  40284. this.gl = this.backend.gl;
  40285. this.extensions = backend.extensions;
  40286. }
  40287. convert( p, colorSpace = NoColorSpace ) {
  40288. const { gl, extensions } = this;
  40289. let extension;
  40290. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40291. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40292. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40293. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40294. if ( p === ByteType ) return gl.BYTE;
  40295. if ( p === ShortType ) return gl.SHORT;
  40296. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40297. if ( p === IntType ) return gl.INT;
  40298. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40299. if ( p === FloatType ) return gl.FLOAT;
  40300. if ( p === HalfFloatType ) {
  40301. return gl.HALF_FLOAT;
  40302. }
  40303. if ( p === AlphaFormat ) return gl.ALPHA;
  40304. if ( p === RGBFormat ) return gl.RGB;
  40305. if ( p === RGBAFormat ) return gl.RGBA;
  40306. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40307. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40308. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40309. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40310. // WebGL2 formats.
  40311. if ( p === RedFormat ) return gl.RED;
  40312. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40313. if ( p === RGFormat ) return gl.RG;
  40314. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40315. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40316. // S3TC
  40317. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40318. if ( colorSpace === SRGBColorSpace ) {
  40319. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40320. if ( extension !== null ) {
  40321. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40322. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40323. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40324. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40325. } else {
  40326. return null;
  40327. }
  40328. } else {
  40329. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40330. if ( extension !== null ) {
  40331. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40332. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40333. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40334. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40335. } else {
  40336. return null;
  40337. }
  40338. }
  40339. }
  40340. // PVRTC
  40341. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40342. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40343. if ( extension !== null ) {
  40344. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40345. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40346. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40347. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40348. } else {
  40349. return null;
  40350. }
  40351. }
  40352. // ETC
  40353. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40354. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40355. if ( extension !== null ) {
  40356. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40357. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40358. } else {
  40359. return null;
  40360. }
  40361. }
  40362. // ASTC
  40363. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40364. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40365. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40366. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40367. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40368. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40369. if ( extension !== null ) {
  40370. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40371. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40372. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40373. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40374. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40375. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40376. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40377. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40378. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40379. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40380. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40381. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40382. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40383. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40384. } else {
  40385. return null;
  40386. }
  40387. }
  40388. // BPTC
  40389. if ( p === RGBA_BPTC_Format ) {
  40390. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40391. if ( extension !== null ) {
  40392. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40393. } else {
  40394. return null;
  40395. }
  40396. }
  40397. // RGTC
  40398. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40399. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40400. if ( extension !== null ) {
  40401. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40402. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40403. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40404. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40405. } else {
  40406. return null;
  40407. }
  40408. }
  40409. //
  40410. if ( p === UnsignedInt248Type ) {
  40411. return gl.UNSIGNED_INT_24_8;
  40412. }
  40413. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40414. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40415. }
  40416. _clientWaitAsync() {
  40417. const { gl } = this;
  40418. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40419. gl.flush();
  40420. return new Promise( ( resolve, reject ) => {
  40421. function test() {
  40422. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40423. if ( res === gl.WAIT_FAILED ) {
  40424. gl.deleteSync( sync );
  40425. reject();
  40426. return;
  40427. }
  40428. if ( res === gl.TIMEOUT_EXPIRED ) {
  40429. requestAnimationFrame( test );
  40430. return;
  40431. }
  40432. gl.deleteSync( sync );
  40433. resolve();
  40434. }
  40435. test();
  40436. } );
  40437. }
  40438. }
  40439. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40440. class WebGLTextureUtils {
  40441. constructor( backend ) {
  40442. this.backend = backend;
  40443. this.gl = backend.gl;
  40444. this.extensions = backend.extensions;
  40445. this.defaultTextures = {};
  40446. if ( initialized === false ) {
  40447. this._init( this.gl );
  40448. initialized = true;
  40449. }
  40450. }
  40451. _init( gl ) {
  40452. // Store only WebGL constants here.
  40453. wrappingToGL = {
  40454. [ RepeatWrapping ]: gl.REPEAT,
  40455. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40456. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40457. };
  40458. filterToGL = {
  40459. [ NearestFilter ]: gl.NEAREST,
  40460. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40461. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40462. [ LinearFilter ]: gl.LINEAR,
  40463. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40464. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40465. };
  40466. compareToGL = {
  40467. [ NeverCompare ]: gl.NEVER,
  40468. [ AlwaysCompare ]: gl.ALWAYS,
  40469. [ LessCompare ]: gl.LESS,
  40470. [ LessEqualCompare ]: gl.LEQUAL,
  40471. [ EqualCompare ]: gl.EQUAL,
  40472. [ GreaterEqualCompare ]: gl.GEQUAL,
  40473. [ GreaterCompare ]: gl.GREATER,
  40474. [ NotEqualCompare ]: gl.NOTEQUAL
  40475. };
  40476. }
  40477. filterFallback( f ) {
  40478. const { gl } = this;
  40479. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  40480. return gl.NEAREST;
  40481. }
  40482. return gl.LINEAR;
  40483. }
  40484. getGLTextureType( texture ) {
  40485. const { gl } = this;
  40486. let glTextureType;
  40487. if ( texture.isCubeTexture === true ) {
  40488. glTextureType = gl.TEXTURE_CUBE_MAP;
  40489. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40490. glTextureType = gl.TEXTURE_2D_ARRAY;
  40491. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40492. glTextureType = gl.TEXTURE_3D;
  40493. } else {
  40494. glTextureType = gl.TEXTURE_2D;
  40495. }
  40496. return glTextureType;
  40497. }
  40498. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40499. const { gl, extensions } = this;
  40500. if ( internalFormatName !== null ) {
  40501. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40502. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40503. }
  40504. let internalFormat = glFormat;
  40505. if ( glFormat === gl.RED ) {
  40506. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40507. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40508. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40509. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40510. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40511. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40512. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40513. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40514. }
  40515. if ( glFormat === gl.RED_INTEGER ) {
  40516. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40517. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40518. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40519. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40520. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40521. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40522. }
  40523. if ( glFormat === gl.RG ) {
  40524. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40525. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40526. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40527. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40528. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40529. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40530. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40531. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40532. }
  40533. if ( glFormat === gl.RG_INTEGER ) {
  40534. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40535. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40536. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40537. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40538. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40539. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40540. }
  40541. if ( glFormat === gl.RGB ) {
  40542. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40543. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40544. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40545. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40546. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40547. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40548. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40549. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40550. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40551. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40552. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40553. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40554. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40555. }
  40556. if ( glFormat === gl.RGB_INTEGER ) {
  40557. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40558. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40559. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40560. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40561. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40562. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40563. }
  40564. if ( glFormat === gl.RGBA ) {
  40565. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40566. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40567. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40568. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40569. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40570. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40571. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40572. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40573. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40574. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40575. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40576. }
  40577. if ( glFormat === gl.RGBA_INTEGER ) {
  40578. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40579. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40580. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40581. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40582. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40583. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40584. }
  40585. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40586. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  40587. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40588. }
  40589. if ( glFormat === gl.DEPTH_STENCIL ) {
  40590. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40591. }
  40592. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40593. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40594. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40595. extensions.get( 'EXT_color_buffer_float' );
  40596. }
  40597. return internalFormat;
  40598. }
  40599. setTextureParameters( textureType, texture ) {
  40600. const { gl, extensions, backend } = this;
  40601. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40602. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40603. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40604. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40605. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40606. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40607. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40608. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40609. }
  40610. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40611. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40612. // follow WebGPU backend mapping for texture filtering
  40613. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40614. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40615. if ( texture.compareFunction ) {
  40616. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40617. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40618. }
  40619. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40620. if ( texture.magFilter === NearestFilter ) return;
  40621. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40622. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40623. if ( texture.anisotropy > 1 ) {
  40624. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40625. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40626. }
  40627. }
  40628. }
  40629. createDefaultTexture( texture ) {
  40630. const { gl, backend, defaultTextures } = this;
  40631. const glTextureType = this.getGLTextureType( texture );
  40632. let textureGPU = defaultTextures[ glTextureType ];
  40633. if ( textureGPU === undefined ) {
  40634. textureGPU = gl.createTexture();
  40635. backend.state.bindTexture( glTextureType, textureGPU );
  40636. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40637. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40638. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40639. defaultTextures[ glTextureType ] = textureGPU;
  40640. }
  40641. backend.set( texture, {
  40642. textureGPU,
  40643. glTextureType,
  40644. isDefault: true
  40645. } );
  40646. }
  40647. createTexture( texture, options ) {
  40648. const { gl, backend } = this;
  40649. const { levels, width, height, depth } = options;
  40650. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40651. const glType = backend.utils.convert( texture.type );
  40652. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40653. const textureGPU = gl.createTexture();
  40654. const glTextureType = this.getGLTextureType( texture );
  40655. backend.state.bindTexture( glTextureType, textureGPU );
  40656. this.setTextureParameters( glTextureType, texture );
  40657. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40658. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40659. } else if ( texture.isData3DTexture ) {
  40660. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40661. } else if ( ! texture.isVideoTexture ) {
  40662. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40663. }
  40664. backend.set( texture, {
  40665. textureGPU,
  40666. glTextureType,
  40667. glFormat,
  40668. glType,
  40669. glInternalFormat
  40670. } );
  40671. }
  40672. copyBufferToTexture( buffer, texture ) {
  40673. const { gl, backend } = this;
  40674. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40675. const { width, height } = texture.source.data;
  40676. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40677. backend.state.bindTexture( glTextureType, textureGPU );
  40678. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40679. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40680. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40681. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40682. backend.state.unbindTexture();
  40683. // debug
  40684. // const framebuffer = gl.createFramebuffer();
  40685. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40686. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40687. // const readout = new Float32Array( width * height * 4 );
  40688. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40689. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40690. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40691. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40692. // console.log( readout );
  40693. }
  40694. updateTexture( texture, options ) {
  40695. const { gl } = this;
  40696. const { width, height } = options;
  40697. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40698. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40699. return;
  40700. const getImage = ( source ) => {
  40701. if ( source.isDataTexture ) {
  40702. return source.image.data;
  40703. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  40704. return source;
  40705. }
  40706. return source.data;
  40707. };
  40708. this.backend.state.bindTexture( glTextureType, textureGPU );
  40709. this.setTextureParameters( glTextureType, texture );
  40710. if ( texture.isCompressedTexture ) {
  40711. const mipmaps = texture.mipmaps;
  40712. const image = options.image;
  40713. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40714. const mipmap = mipmaps[ i ];
  40715. if ( texture.isCompressedArrayTexture ) {
  40716. if ( texture.format !== gl.RGBA ) {
  40717. if ( glFormat !== null ) {
  40718. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  40719. } else {
  40720. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40721. }
  40722. } else {
  40723. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40724. }
  40725. } else {
  40726. if ( glFormat !== null ) {
  40727. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40728. } else {
  40729. console.warn( 'Unsupported compressed texture format' );
  40730. }
  40731. }
  40732. }
  40733. } else if ( texture.isCubeTexture ) {
  40734. const images = options.images;
  40735. for ( let i = 0; i < 6; i ++ ) {
  40736. const image = getImage( images[ i ] );
  40737. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40738. }
  40739. } else if ( texture.isDataArrayTexture ) {
  40740. const image = options.image;
  40741. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40742. } else if ( texture.isData3DTexture ) {
  40743. const image = options.image;
  40744. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40745. } else if ( texture.isVideoTexture ) {
  40746. texture.update();
  40747. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40748. } else {
  40749. const image = getImage( options.image );
  40750. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40751. }
  40752. }
  40753. generateMipmaps( texture ) {
  40754. const { gl, backend } = this;
  40755. const { textureGPU, glTextureType } = backend.get( texture );
  40756. backend.state.bindTexture( glTextureType, textureGPU );
  40757. gl.generateMipmap( glTextureType );
  40758. }
  40759. deallocateRenderBuffers( renderTarget ) {
  40760. const { gl, backend } = this;
  40761. // remove framebuffer reference
  40762. if ( renderTarget ) {
  40763. const renderContextData = backend.get( renderTarget );
  40764. renderContextData.renderBufferStorageSetup = undefined;
  40765. if ( renderContextData.framebuffers ) {
  40766. for ( const cacheKey in renderContextData.framebuffers ) {
  40767. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40768. }
  40769. delete renderContextData.framebuffers;
  40770. }
  40771. if ( renderContextData.depthRenderbuffer ) {
  40772. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40773. delete renderContextData.depthRenderbuffer;
  40774. }
  40775. if ( renderContextData.stencilRenderbuffer ) {
  40776. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40777. delete renderContextData.stencilRenderbuffer;
  40778. }
  40779. if ( renderContextData.msaaFrameBuffer ) {
  40780. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40781. delete renderContextData.msaaFrameBuffer;
  40782. }
  40783. if ( renderContextData.msaaRenderbuffers ) {
  40784. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40785. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40786. }
  40787. delete renderContextData.msaaRenderbuffers;
  40788. }
  40789. }
  40790. }
  40791. destroyTexture( texture ) {
  40792. const { gl, backend } = this;
  40793. const { textureGPU, renderTarget } = backend.get( texture );
  40794. this.deallocateRenderBuffers( renderTarget );
  40795. gl.deleteTexture( textureGPU );
  40796. backend.delete( texture );
  40797. }
  40798. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40799. const { gl, backend } = this;
  40800. const { state } = this.backend;
  40801. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40802. let width, height, minX, minY;
  40803. let dstX, dstY;
  40804. if ( srcRegion !== null ) {
  40805. width = srcRegion.max.x - srcRegion.min.x;
  40806. height = srcRegion.max.y - srcRegion.min.y;
  40807. minX = srcRegion.min.x;
  40808. minY = srcRegion.min.y;
  40809. } else {
  40810. width = srcTexture.image.width;
  40811. height = srcTexture.image.height;
  40812. minX = 0;
  40813. minY = 0;
  40814. }
  40815. if ( dstPosition !== null ) {
  40816. dstX = dstPosition.x;
  40817. dstY = dstPosition.y;
  40818. } else {
  40819. dstX = 0;
  40820. dstY = 0;
  40821. }
  40822. state.bindTexture( glTextureType, dstTextureGPU );
  40823. // As another texture upload may have changed pixelStorei
  40824. // parameters, make sure they are correct for the dstTexture
  40825. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40826. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40827. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40828. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40829. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40830. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40831. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40832. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40833. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40834. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40835. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40836. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40837. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40838. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40839. if ( srcTexture.isDataTexture ) {
  40840. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40841. } else {
  40842. if ( srcTexture.isCompressedTexture ) {
  40843. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40844. } else {
  40845. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40846. }
  40847. }
  40848. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40849. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40850. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40851. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40852. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40853. // Generate mipmaps only when copying level 0
  40854. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40855. state.unbindTexture();
  40856. }
  40857. copyFramebufferToTexture( texture, renderContext ) {
  40858. const { gl } = this;
  40859. const { state } = this.backend;
  40860. const { textureGPU } = this.backend.get( texture );
  40861. const width = texture.image.width;
  40862. const height = texture.image.height;
  40863. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40864. if ( requireDrawFrameBuffer ) {
  40865. let mask;
  40866. let attachment;
  40867. if ( texture.isDepthTexture === true ) {
  40868. mask = gl.DEPTH_BUFFER_BIT;
  40869. attachment = gl.DEPTH_ATTACHMENT;
  40870. if ( renderContext.stencil ) {
  40871. mask |= gl.STENCIL_BUFFER_BIT;
  40872. }
  40873. } else {
  40874. mask = gl.COLOR_BUFFER_BIT;
  40875. attachment = gl.COLOR_ATTACHMENT0;
  40876. }
  40877. const fb = gl.createFramebuffer();
  40878. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40879. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40880. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40881. gl.deleteFramebuffer( fb );
  40882. } else {
  40883. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40884. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  40885. state.unbindTexture();
  40886. }
  40887. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40888. this.backend._setFramebuffer( renderContext );
  40889. }
  40890. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40891. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40892. const { gl } = this;
  40893. const renderTarget = renderContext.renderTarget;
  40894. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40895. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40896. if ( depthBuffer && ! stencilBuffer ) {
  40897. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40898. if ( samples > 0 ) {
  40899. if ( depthTexture && depthTexture.isDepthTexture ) {
  40900. if ( depthTexture.type === gl.FLOAT ) {
  40901. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40902. }
  40903. }
  40904. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40905. } else {
  40906. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40907. }
  40908. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40909. } else if ( depthBuffer && stencilBuffer ) {
  40910. if ( samples > 0 ) {
  40911. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40912. } else {
  40913. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40914. }
  40915. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40916. }
  40917. }
  40918. async copyTextureToBuffer( texture, x, y, width, height ) {
  40919. const { backend, gl } = this;
  40920. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40921. const fb = gl.createFramebuffer();
  40922. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40923. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  40924. const typedArrayType = this._getTypedArrayType( glType );
  40925. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  40926. const elementCount = width * height;
  40927. const byteLength = elementCount * bytesPerTexel;
  40928. const buffer = gl.createBuffer();
  40929. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40930. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40931. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40932. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40933. await backend.utils._clientWaitAsync();
  40934. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40935. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40936. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40937. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40938. gl.deleteFramebuffer( fb );
  40939. return dstBuffer;
  40940. }
  40941. _getTypedArrayType( glType ) {
  40942. const { gl } = this;
  40943. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40944. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40945. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40946. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40947. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40948. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40949. if ( glType === gl.FLOAT ) return Float32Array;
  40950. throw new Error( `Unsupported WebGL type: ${glType}` );
  40951. }
  40952. _getBytesPerTexel( glFormat ) {
  40953. const { gl } = this;
  40954. if ( glFormat === gl.RGBA ) return 4;
  40955. if ( glFormat === gl.RGB ) return 3;
  40956. if ( glFormat === gl.ALPHA ) return 1;
  40957. }
  40958. }
  40959. class WebGLExtensions {
  40960. constructor( backend ) {
  40961. this.backend = backend;
  40962. this.gl = this.backend.gl;
  40963. this.availableExtensions = this.gl.getSupportedExtensions();
  40964. this.extensions = {};
  40965. }
  40966. get( name ) {
  40967. let extension = this.extensions[ name ];
  40968. if ( extension === undefined ) {
  40969. extension = this.gl.getExtension( name );
  40970. this.extensions[ name ] = extension;
  40971. }
  40972. return extension;
  40973. }
  40974. has( name ) {
  40975. return this.availableExtensions.includes( name );
  40976. }
  40977. }
  40978. class WebGLCapabilities {
  40979. constructor( backend ) {
  40980. this.backend = backend;
  40981. this.maxAnisotropy = null;
  40982. }
  40983. getMaxAnisotropy() {
  40984. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40985. const gl = this.backend.gl;
  40986. const extensions = this.backend.extensions;
  40987. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40988. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40989. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40990. } else {
  40991. this.maxAnisotropy = 0;
  40992. }
  40993. return this.maxAnisotropy;
  40994. }
  40995. }
  40996. const GLFeatureName = {
  40997. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40998. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40999. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  41000. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  41001. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41002. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41003. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  41004. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  41005. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  41006. };
  41007. class WebGLBufferRenderer {
  41008. constructor( backend ) {
  41009. this.gl = backend.gl;
  41010. this.extensions = backend.extensions;
  41011. this.info = backend.renderer.info;
  41012. this.mode = null;
  41013. this.index = 0;
  41014. this.type = null;
  41015. this.object = null;
  41016. }
  41017. render( start, count ) {
  41018. const { gl, mode, object, type, info, index } = this;
  41019. if ( index !== 0 ) {
  41020. gl.drawElements( mode, count, type, start );
  41021. } else {
  41022. gl.drawArrays( mode, start, count );
  41023. }
  41024. info.update( object, count, mode, 1 );
  41025. }
  41026. renderInstances( start, count, primcount ) {
  41027. const { gl, mode, type, index, object, info } = this;
  41028. if ( primcount === 0 ) return;
  41029. if ( index !== 0 ) {
  41030. gl.drawElementsInstanced( mode, count, type, start, primcount );
  41031. } else {
  41032. gl.drawArraysInstanced( mode, start, count, primcount );
  41033. }
  41034. info.update( object, count, mode, primcount );
  41035. }
  41036. renderMultiDraw( starts, counts, drawCount ) {
  41037. const { extensions, mode, object, info } = this;
  41038. if ( drawCount === 0 ) return;
  41039. const extension = extensions.get( 'WEBGL_multi_draw' );
  41040. if ( extension === null ) {
  41041. for ( let i = 0; i < drawCount; i ++ ) {
  41042. this.render( starts[ i ], counts[ i ] );
  41043. }
  41044. } else {
  41045. if ( this.index !== 0 ) {
  41046. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  41047. } else {
  41048. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  41049. }
  41050. let elementCount = 0;
  41051. for ( let i = 0; i < drawCount; i ++ ) {
  41052. elementCount += counts[ i ];
  41053. }
  41054. info.update( object, elementCount, mode, 1 );
  41055. }
  41056. }
  41057. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  41058. const { extensions, mode, object, info } = this;
  41059. if ( drawCount === 0 ) return;
  41060. const extension = extensions.get( 'WEBGL_multi_draw' );
  41061. if ( extension === null ) {
  41062. for ( let i = 0; i < drawCount; i ++ ) {
  41063. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  41064. }
  41065. } else {
  41066. if ( this.index !== 0 ) {
  41067. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  41068. } else {
  41069. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  41070. }
  41071. let elementCount = 0;
  41072. for ( let i = 0; i < drawCount; i ++ ) {
  41073. elementCount += counts[ i ];
  41074. }
  41075. for ( let i = 0; i < primcount.length; i ++ ) {
  41076. info.update( object, elementCount, mode, primcount[ i ] );
  41077. }
  41078. }
  41079. }
  41080. //
  41081. }
  41082. //
  41083. class WebGLBackend extends Backend {
  41084. constructor( parameters = {} ) {
  41085. super( parameters );
  41086. this.isWebGLBackend = true;
  41087. }
  41088. init( renderer ) {
  41089. super.init( renderer );
  41090. //
  41091. const parameters = this.parameters;
  41092. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  41093. this.gl = glContext;
  41094. this.extensions = new WebGLExtensions( this );
  41095. this.capabilities = new WebGLCapabilities( this );
  41096. this.attributeUtils = new WebGLAttributeUtils( this );
  41097. this.textureUtils = new WebGLTextureUtils( this );
  41098. this.bufferRenderer = new WebGLBufferRenderer( this );
  41099. this.state = new WebGLState( this );
  41100. this.utils = new WebGLUtils( this );
  41101. this.vaoCache = {};
  41102. this.transformFeedbackCache = {};
  41103. this.discard = false;
  41104. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41105. this.extensions.get( 'EXT_color_buffer_float' );
  41106. this.extensions.get( 'WEBGL_clip_cull_distance' );
  41107. this.extensions.get( 'OES_texture_float_linear' );
  41108. this.extensions.get( 'EXT_color_buffer_half_float' );
  41109. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41110. this.extensions.get( 'WEBGL_render_shared_exponent' );
  41111. this.extensions.get( 'WEBGL_multi_draw' );
  41112. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  41113. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  41114. this._currentContext = null;
  41115. }
  41116. get coordinateSystem() {
  41117. return WebGLCoordinateSystem;
  41118. }
  41119. async getArrayBufferAsync( attribute ) {
  41120. return await this.attributeUtils.getArrayBufferAsync( attribute );
  41121. }
  41122. initTimestampQuery( renderContext ) {
  41123. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41124. const renderContextData = this.get( renderContext );
  41125. if ( this.queryRunning ) {
  41126. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  41127. renderContextData.queryQueue.push( renderContext );
  41128. return;
  41129. }
  41130. if ( renderContextData.activeQuery ) {
  41131. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  41132. renderContextData.activeQuery = null;
  41133. }
  41134. renderContextData.activeQuery = this.gl.createQuery();
  41135. if ( renderContextData.activeQuery !== null ) {
  41136. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  41137. this.queryRunning = true;
  41138. }
  41139. }
  41140. // timestamp utils
  41141. prepareTimestampBuffer( renderContext ) {
  41142. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41143. const renderContextData = this.get( renderContext );
  41144. if ( renderContextData.activeQuery ) {
  41145. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  41146. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  41147. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  41148. renderContextData.activeQuery = null;
  41149. this.queryRunning = false;
  41150. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  41151. const nextRenderContext = renderContextData.queryQueue.shift();
  41152. this.initTimestampQuery( nextRenderContext );
  41153. }
  41154. }
  41155. }
  41156. async resolveTimestampAsync( renderContext, type = 'render' ) {
  41157. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41158. const renderContextData = this.get( renderContext );
  41159. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  41160. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  41161. const queryInfo = renderContextData.gpuQueries[ i ];
  41162. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  41163. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  41164. if ( available && ! disjoint ) {
  41165. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  41166. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  41167. this.gl.deleteQuery( queryInfo.query );
  41168. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  41169. i --;
  41170. this.renderer.info.updateTimestamp( type, duration );
  41171. }
  41172. }
  41173. }
  41174. getContext() {
  41175. return this.gl;
  41176. }
  41177. beginRender( renderContext ) {
  41178. const { gl } = this;
  41179. const renderContextData = this.get( renderContext );
  41180. //
  41181. //
  41182. this.initTimestampQuery( renderContext );
  41183. renderContextData.previousContext = this._currentContext;
  41184. this._currentContext = renderContext;
  41185. this._setFramebuffer( renderContext );
  41186. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41187. //
  41188. if ( renderContext.viewport ) {
  41189. this.updateViewport( renderContext );
  41190. } else {
  41191. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41192. }
  41193. if ( renderContext.scissor ) {
  41194. const { x, y, width, height } = renderContext.scissorValue;
  41195. gl.scissor( x, renderContext.height - height - y, width, height );
  41196. }
  41197. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41198. if ( occlusionQueryCount > 0 ) {
  41199. // Get a reference to the array of objects with queries. The renderContextData property
  41200. // can be changed by another render pass before the async reading of all previous queries complete
  41201. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41202. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41203. renderContextData.lastOcclusionObject = null;
  41204. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41205. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41206. renderContextData.occlusionQueryIndex = 0;
  41207. }
  41208. }
  41209. finishRender( renderContext ) {
  41210. const { gl, state } = this;
  41211. const renderContextData = this.get( renderContext );
  41212. const previousContext = renderContextData.previousContext;
  41213. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41214. if ( occlusionQueryCount > 0 ) {
  41215. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41216. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41217. }
  41218. this.resolveOccludedAsync( renderContext );
  41219. }
  41220. const textures = renderContext.textures;
  41221. if ( textures !== null ) {
  41222. for ( let i = 0; i < textures.length; i ++ ) {
  41223. const texture = textures[ i ];
  41224. if ( texture.generateMipmaps ) {
  41225. this.generateMipmaps( texture );
  41226. }
  41227. }
  41228. }
  41229. this._currentContext = previousContext;
  41230. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41231. const renderTargetContextData = this.get( renderContext.renderTarget );
  41232. const { samples } = renderContext.renderTarget;
  41233. if ( samples > 0 ) {
  41234. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41235. const mask = gl.COLOR_BUFFER_BIT;
  41236. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41237. const textures = renderContext.textures;
  41238. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41239. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41240. for ( let i = 0; i < textures.length; i ++ ) {
  41241. // TODO Add support for MRT
  41242. if ( renderContext.scissor ) {
  41243. const { x, y, width, height } = renderContext.scissorValue;
  41244. const viewY = renderContext.height - height - y;
  41245. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41246. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41247. } else {
  41248. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41249. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41250. }
  41251. }
  41252. }
  41253. }
  41254. if ( previousContext !== null ) {
  41255. this._setFramebuffer( previousContext );
  41256. if ( previousContext.viewport ) {
  41257. this.updateViewport( previousContext );
  41258. } else {
  41259. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41260. }
  41261. }
  41262. this.prepareTimestampBuffer( renderContext );
  41263. }
  41264. resolveOccludedAsync( renderContext ) {
  41265. const renderContextData = this.get( renderContext );
  41266. // handle occlusion query results
  41267. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41268. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41269. const occluded = new WeakSet();
  41270. const { gl } = this;
  41271. renderContextData.currentOcclusionQueryObjects = null;
  41272. renderContextData.currentOcclusionQueries = null;
  41273. const check = () => {
  41274. let completed = 0;
  41275. // check all queries and requeue as appropriate
  41276. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41277. const query = currentOcclusionQueries[ i ];
  41278. if ( query === null ) continue;
  41279. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41280. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41281. currentOcclusionQueries[ i ] = null;
  41282. gl.deleteQuery( query );
  41283. completed ++;
  41284. }
  41285. }
  41286. if ( completed < currentOcclusionQueries.length ) {
  41287. requestAnimationFrame( check );
  41288. } else {
  41289. renderContextData.occluded = occluded;
  41290. }
  41291. };
  41292. check();
  41293. }
  41294. }
  41295. isOccluded( renderContext, object ) {
  41296. const renderContextData = this.get( renderContext );
  41297. return renderContextData.occluded && renderContextData.occluded.has( object );
  41298. }
  41299. updateViewport( renderContext ) {
  41300. const gl = this.gl;
  41301. const { x, y, width, height } = renderContext.viewportValue;
  41302. gl.viewport( x, renderContext.height - height - y, width, height );
  41303. }
  41304. setScissorTest( boolean ) {
  41305. const gl = this.gl;
  41306. if ( boolean ) {
  41307. gl.enable( gl.SCISSOR_TEST );
  41308. } else {
  41309. gl.disable( gl.SCISSOR_TEST );
  41310. }
  41311. }
  41312. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41313. const { gl } = this;
  41314. if ( descriptor === null ) {
  41315. descriptor = {
  41316. textures: null,
  41317. clearColorValue: this.getClearColor()
  41318. };
  41319. }
  41320. //
  41321. let clear = 0;
  41322. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41323. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41324. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41325. if ( clear !== 0 ) {
  41326. const clearColor = descriptor.clearColorValue || this.getClearColor();
  41327. // premultiply alpha
  41328. clearColor.r *= clearColor.a;
  41329. clearColor.g *= clearColor.a;
  41330. clearColor.b *= clearColor.a;
  41331. if ( depth ) this.state.setDepthMask( true );
  41332. if ( descriptor.textures === null ) {
  41333. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41334. gl.clear( clear );
  41335. } else {
  41336. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41337. if ( color ) {
  41338. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41339. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41340. }
  41341. }
  41342. if ( depth && stencil ) {
  41343. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41344. } else if ( depth ) {
  41345. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41346. } else if ( stencil ) {
  41347. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41348. }
  41349. }
  41350. }
  41351. }
  41352. beginCompute( computeGroup ) {
  41353. const { state, gl } = this;
  41354. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41355. this.initTimestampQuery( computeGroup );
  41356. }
  41357. compute( computeGroup, computeNode, bindings, pipeline ) {
  41358. const { state, gl } = this;
  41359. if ( ! this.discard ) {
  41360. // required here to handle async behaviour of render.compute()
  41361. gl.enable( gl.RASTERIZER_DISCARD );
  41362. this.discard = true;
  41363. }
  41364. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41365. const vaoKey = this._getVaoKey( null, attributes );
  41366. const vaoGPU = this.vaoCache[ vaoKey ];
  41367. if ( vaoGPU === undefined ) {
  41368. this._createVao( null, attributes );
  41369. } else {
  41370. gl.bindVertexArray( vaoGPU );
  41371. }
  41372. state.useProgram( programGPU );
  41373. this._bindUniforms( bindings );
  41374. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41375. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41376. gl.beginTransformFeedback( gl.POINTS );
  41377. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41378. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41379. } else {
  41380. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41381. }
  41382. gl.endTransformFeedback();
  41383. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41384. // switch active buffers
  41385. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41386. const dualAttributeData = transformBuffers[ i ];
  41387. if ( dualAttributeData.pbo ) {
  41388. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41389. }
  41390. dualAttributeData.switchBuffers();
  41391. }
  41392. }
  41393. finishCompute( computeGroup ) {
  41394. const gl = this.gl;
  41395. this.discard = false;
  41396. gl.disable( gl.RASTERIZER_DISCARD );
  41397. this.prepareTimestampBuffer( computeGroup );
  41398. }
  41399. draw( renderObject/*, info*/ ) {
  41400. const { object, pipeline, material, context } = renderObject;
  41401. const { programGPU } = this.get( pipeline );
  41402. const { gl, state } = this;
  41403. const contextData = this.get( context );
  41404. //
  41405. this._bindUniforms( renderObject.getBindings() );
  41406. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  41407. state.setMaterial( material, frontFaceCW );
  41408. state.useProgram( programGPU );
  41409. //
  41410. let vaoGPU = renderObject.staticVao;
  41411. if ( vaoGPU === undefined ) {
  41412. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  41413. vaoGPU = this.vaoCache[ vaoKey ];
  41414. if ( vaoGPU === undefined ) {
  41415. let staticVao;
  41416. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41417. if ( staticVao ) renderObject.staticVao = vaoGPU;
  41418. }
  41419. }
  41420. gl.bindVertexArray( vaoGPU );
  41421. //
  41422. const index = renderObject.getIndex();
  41423. const geometry = renderObject.geometry;
  41424. const drawRange = renderObject.drawRange;
  41425. //
  41426. const lastObject = contextData.lastOcclusionObject;
  41427. if ( lastObject !== object && lastObject !== undefined ) {
  41428. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41429. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41430. contextData.occlusionQueryIndex ++;
  41431. }
  41432. if ( object.occlusionTest === true ) {
  41433. const query = gl.createQuery();
  41434. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41435. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41436. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41437. }
  41438. contextData.lastOcclusionObject = object;
  41439. }
  41440. //
  41441. let rangeFactor = 1;
  41442. const renderer = this.bufferRenderer;
  41443. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41444. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41445. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41446. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41447. else {
  41448. if ( material.wireframe === true ) {
  41449. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41450. renderer.mode = gl.LINES;
  41451. rangeFactor = 2;
  41452. } else {
  41453. renderer.mode = gl.TRIANGLES;
  41454. }
  41455. }
  41456. //
  41457. const group = renderObject.group;
  41458. renderer.object = object;
  41459. let firstVertex = drawRange.start * rangeFactor;
  41460. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  41461. if ( group !== null ) {
  41462. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  41463. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  41464. }
  41465. if ( index !== null ) {
  41466. const indexData = this.get( index );
  41467. const indexCount = index.count;
  41468. renderer.index = index.count;
  41469. renderer.type = indexData.type;
  41470. firstVertex = Math.max( firstVertex, 0 );
  41471. lastVertex = Math.min( lastVertex, indexCount );
  41472. } else {
  41473. renderer.index = 0;
  41474. const vertexCount = geometry.attributes.position.count;
  41475. firstVertex = Math.max( firstVertex, 0 );
  41476. lastVertex = Math.min( lastVertex, vertexCount );
  41477. }
  41478. const count = lastVertex - firstVertex;
  41479. if ( count < 0 || count === Infinity ) return;
  41480. if ( index !== null ) {
  41481. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41482. }
  41483. const instanceCount = this.getInstanceCount( renderObject );
  41484. if ( object.isBatchedMesh ) {
  41485. if ( object._multiDrawInstances !== null ) {
  41486. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41487. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41488. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41489. } else {
  41490. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41491. }
  41492. } else if ( instanceCount > 1 ) {
  41493. renderer.renderInstances( firstVertex, count, instanceCount );
  41494. } else {
  41495. renderer.render( firstVertex, count );
  41496. }
  41497. //
  41498. gl.bindVertexArray( null );
  41499. }
  41500. needsRenderUpdate( /*renderObject*/ ) {
  41501. return false;
  41502. }
  41503. getRenderCacheKey( /*renderObject*/ ) {
  41504. return '';
  41505. }
  41506. // textures
  41507. createDefaultTexture( texture ) {
  41508. this.textureUtils.createDefaultTexture( texture );
  41509. }
  41510. createTexture( texture, options ) {
  41511. this.textureUtils.createTexture( texture, options );
  41512. }
  41513. updateTexture( texture, options ) {
  41514. this.textureUtils.updateTexture( texture, options );
  41515. }
  41516. generateMipmaps( texture ) {
  41517. this.textureUtils.generateMipmaps( texture );
  41518. }
  41519. destroyTexture( texture ) {
  41520. this.textureUtils.destroyTexture( texture );
  41521. }
  41522. copyTextureToBuffer( texture, x, y, width, height ) {
  41523. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  41524. }
  41525. createSampler( /*texture*/ ) {
  41526. //console.warn( 'Abstract class.' );
  41527. }
  41528. destroySampler() {}
  41529. // node builder
  41530. createNodeBuilder( object, renderer ) {
  41531. return new GLSLNodeBuilder( object, renderer );
  41532. }
  41533. // program
  41534. createProgram( program ) {
  41535. const gl = this.gl;
  41536. const { stage, code } = program;
  41537. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41538. gl.shaderSource( shader, code );
  41539. gl.compileShader( shader );
  41540. this.set( program, {
  41541. shaderGPU: shader
  41542. } );
  41543. }
  41544. destroyProgram( /*program*/ ) {
  41545. console.warn( 'Abstract class.' );
  41546. }
  41547. createRenderPipeline( renderObject, promises ) {
  41548. const gl = this.gl;
  41549. const pipeline = renderObject.pipeline;
  41550. // Program
  41551. const { fragmentProgram, vertexProgram } = pipeline;
  41552. const programGPU = gl.createProgram();
  41553. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41554. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41555. gl.attachShader( programGPU, fragmentShader );
  41556. gl.attachShader( programGPU, vertexShader );
  41557. gl.linkProgram( programGPU );
  41558. this.set( pipeline, {
  41559. programGPU,
  41560. fragmentShader,
  41561. vertexShader
  41562. } );
  41563. if ( promises !== null && this.parallel ) {
  41564. const p = new Promise( ( resolve /*, reject*/ ) => {
  41565. const parallel = this.parallel;
  41566. const checkStatus = () => {
  41567. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41568. this._completeCompile( renderObject, pipeline );
  41569. resolve();
  41570. } else {
  41571. requestAnimationFrame( checkStatus );
  41572. }
  41573. };
  41574. checkStatus();
  41575. } );
  41576. promises.push( p );
  41577. return;
  41578. }
  41579. this._completeCompile( renderObject, pipeline );
  41580. }
  41581. _handleSource( string, errorLine ) {
  41582. const lines = string.split( '\n' );
  41583. const lines2 = [];
  41584. const from = Math.max( errorLine - 6, 0 );
  41585. const to = Math.min( errorLine + 6, lines.length );
  41586. for ( let i = from; i < to; i ++ ) {
  41587. const line = i + 1;
  41588. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41589. }
  41590. return lines2.join( '\n' );
  41591. }
  41592. _getShaderErrors( gl, shader, type ) {
  41593. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41594. const errors = gl.getShaderInfoLog( shader ).trim();
  41595. if ( status && errors === '' ) return '';
  41596. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41597. if ( errorMatches ) {
  41598. const errorLine = parseInt( errorMatches[ 1 ] );
  41599. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41600. } else {
  41601. return errors;
  41602. }
  41603. }
  41604. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41605. if ( this.renderer.debug.checkShaderErrors ) {
  41606. const gl = this.gl;
  41607. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41608. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41609. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41610. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41611. } else {
  41612. // default error reporting
  41613. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41614. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41615. console.error(
  41616. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41617. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41618. 'Program Info Log: ' + programLog + '\n' +
  41619. vertexErrors + '\n' +
  41620. fragmentErrors
  41621. );
  41622. }
  41623. } else if ( programLog !== '' ) {
  41624. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41625. }
  41626. }
  41627. }
  41628. _completeCompile( renderObject, pipeline ) {
  41629. const { state, gl } = this;
  41630. const pipelineData = this.get( pipeline );
  41631. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41632. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41633. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41634. }
  41635. state.useProgram( programGPU );
  41636. // Bindings
  41637. const bindings = renderObject.getBindings();
  41638. this._setupBindings( bindings, programGPU );
  41639. //
  41640. this.set( pipeline, {
  41641. programGPU
  41642. } );
  41643. }
  41644. createComputePipeline( computePipeline, bindings ) {
  41645. const { state, gl } = this;
  41646. // Program
  41647. const fragmentProgram = {
  41648. stage: 'fragment',
  41649. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41650. };
  41651. this.createProgram( fragmentProgram );
  41652. const { computeProgram } = computePipeline;
  41653. const programGPU = gl.createProgram();
  41654. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41655. const vertexShader = this.get( computeProgram ).shaderGPU;
  41656. const transforms = computeProgram.transforms;
  41657. const transformVaryingNames = [];
  41658. const transformAttributeNodes = [];
  41659. for ( let i = 0; i < transforms.length; i ++ ) {
  41660. const transform = transforms[ i ];
  41661. transformVaryingNames.push( transform.varyingName );
  41662. transformAttributeNodes.push( transform.attributeNode );
  41663. }
  41664. gl.attachShader( programGPU, fragmentShader );
  41665. gl.attachShader( programGPU, vertexShader );
  41666. gl.transformFeedbackVaryings(
  41667. programGPU,
  41668. transformVaryingNames,
  41669. gl.SEPARATE_ATTRIBS
  41670. );
  41671. gl.linkProgram( programGPU );
  41672. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41673. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41674. }
  41675. state.useProgram( programGPU );
  41676. // Bindings
  41677. this.createBindings( null, bindings );
  41678. this._setupBindings( bindings, programGPU );
  41679. const attributeNodes = computeProgram.attributes;
  41680. const attributes = [];
  41681. const transformBuffers = [];
  41682. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41683. const attribute = attributeNodes[ i ].node.attribute;
  41684. attributes.push( attribute );
  41685. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41686. }
  41687. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41688. const attribute = transformAttributeNodes[ i ].attribute;
  41689. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41690. const attributeData = this.get( attribute );
  41691. transformBuffers.push( attributeData );
  41692. }
  41693. //
  41694. this.set( computePipeline, {
  41695. programGPU,
  41696. transformBuffers,
  41697. attributes
  41698. } );
  41699. }
  41700. createBindings( bindGroup, bindings ) {
  41701. this.updateBindings( bindGroup, bindings );
  41702. }
  41703. updateBindings( bindGroup, bindings ) {
  41704. const { state, gl } = this;
  41705. let groupIndex = 0;
  41706. let textureIndex = 0;
  41707. for ( const bindGroup of bindings ) {
  41708. for ( const binding of bindGroup.bindings ) {
  41709. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41710. const bufferGPU = gl.createBuffer();
  41711. const data = binding.buffer;
  41712. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41713. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41714. state.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  41715. this.set( binding, {
  41716. index: groupIndex ++,
  41717. bufferGPU
  41718. } );
  41719. } else if ( binding.isSampledTexture ) {
  41720. const { textureGPU, glTextureType } = this.get( binding.texture );
  41721. this.set( binding, {
  41722. index: textureIndex ++,
  41723. textureGPU,
  41724. glTextureType
  41725. } );
  41726. }
  41727. }
  41728. }
  41729. }
  41730. updateBinding( binding ) {
  41731. const gl = this.gl;
  41732. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41733. const bindingData = this.get( binding );
  41734. const bufferGPU = bindingData.bufferGPU;
  41735. const data = binding.buffer;
  41736. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41737. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41738. }
  41739. }
  41740. // attributes
  41741. createIndexAttribute( attribute ) {
  41742. const gl = this.gl;
  41743. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41744. }
  41745. createAttribute( attribute ) {
  41746. if ( this.has( attribute ) ) return;
  41747. const gl = this.gl;
  41748. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41749. }
  41750. createStorageAttribute( attribute ) {
  41751. if ( this.has( attribute ) ) return;
  41752. const gl = this.gl;
  41753. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41754. }
  41755. updateAttribute( attribute ) {
  41756. this.attributeUtils.updateAttribute( attribute );
  41757. }
  41758. destroyAttribute( attribute ) {
  41759. this.attributeUtils.destroyAttribute( attribute );
  41760. }
  41761. updateSize() {
  41762. //console.warn( 'Abstract class.' );
  41763. }
  41764. hasFeature( name ) {
  41765. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41766. const extensions = this.extensions;
  41767. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41768. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41769. }
  41770. return false;
  41771. }
  41772. getMaxAnisotropy() {
  41773. return this.capabilities.getMaxAnisotropy();
  41774. }
  41775. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  41776. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  41777. }
  41778. copyFramebufferToTexture( texture, renderContext ) {
  41779. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  41780. }
  41781. _setFramebuffer( descriptor ) {
  41782. const { gl, state } = this;
  41783. let currentFrameBuffer = null;
  41784. if ( descriptor.textures !== null ) {
  41785. const renderTarget = descriptor.renderTarget;
  41786. const renderTargetContextData = this.get( renderTarget );
  41787. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41788. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41789. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41790. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41791. const cacheKey = getCacheKey( descriptor );
  41792. let fb;
  41793. if ( isCube ) {
  41794. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41795. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41796. } else {
  41797. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41798. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41799. }
  41800. if ( fb === undefined ) {
  41801. fb = gl.createFramebuffer();
  41802. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41803. const textures = descriptor.textures;
  41804. if ( isCube ) {
  41805. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41806. const { textureGPU } = this.get( textures[ 0 ] );
  41807. const cubeFace = this.renderer._activeCubeFace;
  41808. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41809. } else {
  41810. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41811. for ( let i = 0; i < textures.length; i ++ ) {
  41812. const texture = textures[ i ];
  41813. const textureData = this.get( texture );
  41814. textureData.renderTarget = descriptor.renderTarget;
  41815. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41816. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41817. }
  41818. state.drawBuffers( descriptor, fb );
  41819. }
  41820. if ( descriptor.depthTexture !== null ) {
  41821. const textureData = this.get( descriptor.depthTexture );
  41822. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41823. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41824. }
  41825. }
  41826. if ( samples > 0 ) {
  41827. if ( msaaFb === undefined ) {
  41828. const invalidationArray = [];
  41829. msaaFb = gl.createFramebuffer();
  41830. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41831. const msaaRenderbuffers = [];
  41832. const textures = descriptor.textures;
  41833. for ( let i = 0; i < textures.length; i ++ ) {
  41834. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41835. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41836. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41837. if ( depthBuffer ) {
  41838. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41839. invalidationArray.push( depthStyle );
  41840. }
  41841. const texture = descriptor.textures[ i ];
  41842. const textureData = this.get( texture );
  41843. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41844. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41845. }
  41846. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41847. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41848. if ( depthRenderbuffer === undefined ) {
  41849. depthRenderbuffer = gl.createRenderbuffer();
  41850. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41851. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41852. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41853. invalidationArray.push( depthStyle );
  41854. }
  41855. renderTargetContextData.invalidationArray = invalidationArray;
  41856. }
  41857. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41858. } else {
  41859. currentFrameBuffer = fb;
  41860. }
  41861. }
  41862. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41863. }
  41864. _getVaoKey( index, attributes ) {
  41865. let key = [];
  41866. if ( index !== null ) {
  41867. const indexData = this.get( index );
  41868. key += ':' + indexData.id;
  41869. }
  41870. for ( let i = 0; i < attributes.length; i ++ ) {
  41871. const attributeData = this.get( attributes[ i ] );
  41872. key += ':' + attributeData.id;
  41873. }
  41874. return key;
  41875. }
  41876. _createVao( index, attributes ) {
  41877. const { gl } = this;
  41878. const vaoGPU = gl.createVertexArray();
  41879. let key = '';
  41880. let staticVao = true;
  41881. gl.bindVertexArray( vaoGPU );
  41882. if ( index !== null ) {
  41883. const indexData = this.get( index );
  41884. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41885. key += ':' + indexData.id;
  41886. }
  41887. for ( let i = 0; i < attributes.length; i ++ ) {
  41888. const attribute = attributes[ i ];
  41889. const attributeData = this.get( attribute );
  41890. key += ':' + attributeData.id;
  41891. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41892. gl.enableVertexAttribArray( i );
  41893. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41894. let stride, offset;
  41895. if ( attribute.isInterleavedBufferAttribute === true ) {
  41896. stride = attribute.data.stride * attributeData.bytesPerElement;
  41897. offset = attribute.offset * attributeData.bytesPerElement;
  41898. } else {
  41899. stride = 0;
  41900. offset = 0;
  41901. }
  41902. if ( attributeData.isInteger ) {
  41903. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41904. } else {
  41905. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41906. }
  41907. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41908. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41909. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41910. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41911. }
  41912. }
  41913. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41914. this.vaoCache[ key ] = vaoGPU;
  41915. return { vaoGPU, staticVao };
  41916. }
  41917. _getTransformFeedback( transformBuffers ) {
  41918. let key = '';
  41919. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41920. key += ':' + transformBuffers[ i ].id;
  41921. }
  41922. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41923. if ( transformFeedbackGPU !== undefined ) {
  41924. return transformFeedbackGPU;
  41925. }
  41926. const { gl } = this;
  41927. transformFeedbackGPU = gl.createTransformFeedback();
  41928. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41929. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41930. const attributeData = transformBuffers[ i ];
  41931. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41932. }
  41933. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41934. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41935. return transformFeedbackGPU;
  41936. }
  41937. _setupBindings( bindings, programGPU ) {
  41938. const gl = this.gl;
  41939. for ( const bindGroup of bindings ) {
  41940. for ( const binding of bindGroup.bindings ) {
  41941. const bindingData = this.get( binding );
  41942. const index = bindingData.index;
  41943. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41944. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41945. gl.uniformBlockBinding( programGPU, location, index );
  41946. } else if ( binding.isSampledTexture ) {
  41947. const location = gl.getUniformLocation( programGPU, binding.name );
  41948. gl.uniform1i( location, index );
  41949. }
  41950. }
  41951. }
  41952. }
  41953. _bindUniforms( bindings ) {
  41954. const { gl, state } = this;
  41955. for ( const bindGroup of bindings ) {
  41956. for ( const binding of bindGroup.bindings ) {
  41957. const bindingData = this.get( binding );
  41958. const index = bindingData.index;
  41959. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41960. // TODO USE bindBufferRange to group multiple uniform buffers
  41961. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41962. } else if ( binding.isSampledTexture ) {
  41963. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41964. }
  41965. }
  41966. }
  41967. }
  41968. }
  41969. class Sampler extends Binding {
  41970. constructor( name, texture ) {
  41971. super( name );
  41972. this.texture = texture;
  41973. this.version = texture ? texture.version : 0;
  41974. this.isSampler = true;
  41975. }
  41976. }
  41977. class NodeSampler extends Sampler {
  41978. constructor( name, textureNode, groupNode ) {
  41979. super( name, textureNode ? textureNode.value : null );
  41980. this.textureNode = textureNode;
  41981. this.groupNode = groupNode;
  41982. }
  41983. update() {
  41984. this.texture = this.textureNode.value;
  41985. }
  41986. }
  41987. class StorageBuffer extends Buffer {
  41988. constructor( name, attribute ) {
  41989. super( name, attribute ? attribute.array : null );
  41990. this.attribute = attribute;
  41991. this.isStorageBuffer = true;
  41992. }
  41993. }
  41994. let _id = 0;
  41995. class NodeStorageBuffer extends StorageBuffer {
  41996. constructor( nodeUniform, groupNode ) {
  41997. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41998. this.nodeUniform = nodeUniform;
  41999. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  42000. this.groupNode = groupNode;
  42001. }
  42002. get buffer() {
  42003. return this.nodeUniform.value;
  42004. }
  42005. }
  42006. class WebGPUTexturePassUtils extends DataMap {
  42007. constructor( device ) {
  42008. super();
  42009. this.device = device;
  42010. const mipmapVertexSource = `
  42011. struct VarysStruct {
  42012. @builtin( position ) Position: vec4<f32>,
  42013. @location( 0 ) vTex : vec2<f32>
  42014. };
  42015. @vertex
  42016. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  42017. var Varys : VarysStruct;
  42018. var pos = array< vec2<f32>, 4 >(
  42019. vec2<f32>( -1.0, 1.0 ),
  42020. vec2<f32>( 1.0, 1.0 ),
  42021. vec2<f32>( -1.0, -1.0 ),
  42022. vec2<f32>( 1.0, -1.0 )
  42023. );
  42024. var tex = array< vec2<f32>, 4 >(
  42025. vec2<f32>( 0.0, 0.0 ),
  42026. vec2<f32>( 1.0, 0.0 ),
  42027. vec2<f32>( 0.0, 1.0 ),
  42028. vec2<f32>( 1.0, 1.0 )
  42029. );
  42030. Varys.vTex = tex[ vertexIndex ];
  42031. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  42032. return Varys;
  42033. }
  42034. `;
  42035. const mipmapFragmentSource = `
  42036. @group( 0 ) @binding( 0 )
  42037. var imgSampler : sampler;
  42038. @group( 0 ) @binding( 1 )
  42039. var img : texture_2d<f32>;
  42040. @fragment
  42041. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42042. return textureSample( img, imgSampler, vTex );
  42043. }
  42044. `;
  42045. const flipYFragmentSource = `
  42046. @group( 0 ) @binding( 0 )
  42047. var imgSampler : sampler;
  42048. @group( 0 ) @binding( 1 )
  42049. var img : texture_2d<f32>;
  42050. @fragment
  42051. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42052. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  42053. }
  42054. `;
  42055. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  42056. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42057. // We'll need a new pipeline for every texture format used.
  42058. this.transferPipelines = {};
  42059. this.flipYPipelines = {};
  42060. this.mipmapVertexShaderModule = device.createShaderModule( {
  42061. label: 'mipmapVertex',
  42062. code: mipmapVertexSource
  42063. } );
  42064. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42065. label: 'mipmapFragment',
  42066. code: mipmapFragmentSource
  42067. } );
  42068. this.flipYFragmentShaderModule = device.createShaderModule( {
  42069. label: 'flipYFragment',
  42070. code: flipYFragmentSource
  42071. } );
  42072. }
  42073. getTransferPipeline( format ) {
  42074. let pipeline = this.transferPipelines[ format ];
  42075. if ( pipeline === undefined ) {
  42076. pipeline = this.device.createRenderPipeline( {
  42077. label: `mipmap-${ format }`,
  42078. vertex: {
  42079. module: this.mipmapVertexShaderModule,
  42080. entryPoint: 'main'
  42081. },
  42082. fragment: {
  42083. module: this.mipmapFragmentShaderModule,
  42084. entryPoint: 'main',
  42085. targets: [ { format } ]
  42086. },
  42087. primitive: {
  42088. topology: GPUPrimitiveTopology.TriangleStrip,
  42089. stripIndexFormat: GPUIndexFormat.Uint32
  42090. },
  42091. layout: 'auto'
  42092. } );
  42093. this.transferPipelines[ format ] = pipeline;
  42094. }
  42095. return pipeline;
  42096. }
  42097. getFlipYPipeline( format ) {
  42098. let pipeline = this.flipYPipelines[ format ];
  42099. if ( pipeline === undefined ) {
  42100. pipeline = this.device.createRenderPipeline( {
  42101. label: `flipY-${ format }`,
  42102. vertex: {
  42103. module: this.mipmapVertexShaderModule,
  42104. entryPoint: 'main'
  42105. },
  42106. fragment: {
  42107. module: this.flipYFragmentShaderModule,
  42108. entryPoint: 'main',
  42109. targets: [ { format } ]
  42110. },
  42111. primitive: {
  42112. topology: GPUPrimitiveTopology.TriangleStrip,
  42113. stripIndexFormat: GPUIndexFormat.Uint32
  42114. },
  42115. layout: 'auto'
  42116. } );
  42117. this.flipYPipelines[ format ] = pipeline;
  42118. }
  42119. return pipeline;
  42120. }
  42121. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42122. const format = textureGPUDescriptor.format;
  42123. const { width, height } = textureGPUDescriptor.size;
  42124. const transferPipeline = this.getTransferPipeline( format );
  42125. const flipYPipeline = this.getFlipYPipeline( format );
  42126. const tempTexture = this.device.createTexture( {
  42127. size: { width, height, depthOrArrayLayers: 1 },
  42128. format,
  42129. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42130. } );
  42131. const srcView = textureGPU.createView( {
  42132. baseMipLevel: 0,
  42133. mipLevelCount: 1,
  42134. dimension: GPUTextureViewDimension.TwoD,
  42135. baseArrayLayer
  42136. } );
  42137. const dstView = tempTexture.createView( {
  42138. baseMipLevel: 0,
  42139. mipLevelCount: 1,
  42140. dimension: GPUTextureViewDimension.TwoD,
  42141. baseArrayLayer: 0
  42142. } );
  42143. const commandEncoder = this.device.createCommandEncoder( {} );
  42144. const pass = ( pipeline, sourceView, destinationView ) => {
  42145. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42146. const bindGroup = this.device.createBindGroup( {
  42147. layout: bindGroupLayout,
  42148. entries: [ {
  42149. binding: 0,
  42150. resource: this.flipYSampler
  42151. }, {
  42152. binding: 1,
  42153. resource: sourceView
  42154. } ]
  42155. } );
  42156. const passEncoder = commandEncoder.beginRenderPass( {
  42157. colorAttachments: [ {
  42158. view: destinationView,
  42159. loadOp: GPULoadOp.Clear,
  42160. storeOp: GPUStoreOp.Store,
  42161. clearValue: [ 0, 0, 0, 0 ]
  42162. } ]
  42163. } );
  42164. passEncoder.setPipeline( pipeline );
  42165. passEncoder.setBindGroup( 0, bindGroup );
  42166. passEncoder.draw( 4, 1, 0, 0 );
  42167. passEncoder.end();
  42168. };
  42169. pass( transferPipeline, srcView, dstView );
  42170. pass( flipYPipeline, dstView, srcView );
  42171. this.device.queue.submit( [ commandEncoder.finish() ] );
  42172. tempTexture.destroy();
  42173. }
  42174. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42175. const textureData = this.get( textureGPU );
  42176. if ( textureData.useCount === undefined ) {
  42177. textureData.useCount = 0;
  42178. textureData.layers = [];
  42179. }
  42180. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42181. const commandEncoder = this.device.createCommandEncoder( {} );
  42182. this._mipmapRunBundles( commandEncoder, passes );
  42183. this.device.queue.submit( [ commandEncoder.finish() ] );
  42184. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42185. textureData.useCount ++;
  42186. }
  42187. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42188. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42189. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42190. let srcView = textureGPU.createView( {
  42191. baseMipLevel: 0,
  42192. mipLevelCount: 1,
  42193. dimension: GPUTextureViewDimension.TwoD,
  42194. baseArrayLayer
  42195. } );
  42196. const passes = [];
  42197. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42198. const bindGroup = this.device.createBindGroup( {
  42199. layout: bindGroupLayout,
  42200. entries: [ {
  42201. binding: 0,
  42202. resource: this.mipmapSampler
  42203. }, {
  42204. binding: 1,
  42205. resource: srcView
  42206. } ]
  42207. } );
  42208. const dstView = textureGPU.createView( {
  42209. baseMipLevel: i,
  42210. mipLevelCount: 1,
  42211. dimension: GPUTextureViewDimension.TwoD,
  42212. baseArrayLayer
  42213. } );
  42214. const passDescriptor = {
  42215. colorAttachments: [ {
  42216. view: dstView,
  42217. loadOp: GPULoadOp.Clear,
  42218. storeOp: GPUStoreOp.Store,
  42219. clearValue: [ 0, 0, 0, 0 ]
  42220. } ]
  42221. };
  42222. const passEncoder = this.device.createRenderBundleEncoder( {
  42223. colorFormats: [ textureGPUDescriptor.format ]
  42224. } );
  42225. passEncoder.setPipeline( pipeline );
  42226. passEncoder.setBindGroup( 0, bindGroup );
  42227. passEncoder.draw( 4, 1, 0, 0 );
  42228. passes.push( {
  42229. renderBundles: [ passEncoder.finish() ],
  42230. passDescriptor
  42231. } );
  42232. srcView = dstView;
  42233. }
  42234. return passes;
  42235. }
  42236. _mipmapRunBundles( commandEncoder, passes ) {
  42237. const levels = passes.length;
  42238. for ( let i = 0; i < levels; i ++ ) {
  42239. const pass = passes[ i ];
  42240. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42241. passEncoder.executeBundles( pass.renderBundles );
  42242. passEncoder.end();
  42243. }
  42244. }
  42245. }
  42246. const _compareToWebGPU = {
  42247. [ NeverCompare ]: 'never',
  42248. [ LessCompare ]: 'less',
  42249. [ EqualCompare ]: 'equal',
  42250. [ LessEqualCompare ]: 'less-equal',
  42251. [ GreaterCompare ]: 'greater',
  42252. [ GreaterEqualCompare ]: 'greater-equal',
  42253. [ AlwaysCompare ]: 'always',
  42254. [ NotEqualCompare ]: 'not-equal'
  42255. };
  42256. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42257. class WebGPUTextureUtils {
  42258. constructor( backend ) {
  42259. this.backend = backend;
  42260. this._passUtils = null;
  42261. this.defaultTexture = {};
  42262. this.defaultCubeTexture = {};
  42263. this.defaultVideoFrame = null;
  42264. this.colorBuffer = null;
  42265. this.depthTexture = new DepthTexture();
  42266. this.depthTexture.name = 'depthBuffer';
  42267. }
  42268. createSampler( texture ) {
  42269. const backend = this.backend;
  42270. const device = backend.device;
  42271. const textureGPU = backend.get( texture );
  42272. const samplerDescriptorGPU = {
  42273. addressModeU: this._convertAddressMode( texture.wrapS ),
  42274. addressModeV: this._convertAddressMode( texture.wrapT ),
  42275. addressModeW: this._convertAddressMode( texture.wrapR ),
  42276. magFilter: this._convertFilterMode( texture.magFilter ),
  42277. minFilter: this._convertFilterMode( texture.minFilter ),
  42278. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42279. maxAnisotropy: texture.anisotropy
  42280. };
  42281. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42282. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42283. }
  42284. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42285. }
  42286. createDefaultTexture( texture ) {
  42287. let textureGPU;
  42288. const format = getFormat( texture );
  42289. if ( texture.isCubeTexture ) {
  42290. textureGPU = this._getDefaultCubeTextureGPU( format );
  42291. } else if ( texture.isVideoTexture ) {
  42292. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42293. } else {
  42294. textureGPU = this._getDefaultTextureGPU( format );
  42295. }
  42296. this.backend.get( texture ).texture = textureGPU;
  42297. }
  42298. createTexture( texture, options = {} ) {
  42299. const backend = this.backend;
  42300. const textureData = backend.get( texture );
  42301. if ( textureData.initialized ) {
  42302. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42303. }
  42304. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42305. if ( options.levels === undefined ) options.levels = 1;
  42306. if ( options.depth === undefined ) options.depth = 1;
  42307. const { width, height, depth, levels } = options;
  42308. const dimension = this._getDimension( texture );
  42309. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42310. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  42311. sampleCount = backend.utils.getSampleCount( sampleCount );
  42312. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  42313. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42314. if ( texture.isStorageTexture === true ) {
  42315. usage |= GPUTextureUsage.STORAGE_BINDING;
  42316. }
  42317. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42318. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42319. }
  42320. const textureDescriptorGPU = {
  42321. label: texture.name,
  42322. size: {
  42323. width: width,
  42324. height: height,
  42325. depthOrArrayLayers: depth,
  42326. },
  42327. mipLevelCount: levels,
  42328. sampleCount: primarySampleCount,
  42329. dimension: dimension,
  42330. format: format,
  42331. usage: usage
  42332. };
  42333. // texture creation
  42334. if ( texture.isVideoTexture ) {
  42335. const video = texture.source.data;
  42336. const videoFrame = new VideoFrame( video );
  42337. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42338. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42339. videoFrame.close();
  42340. textureData.externalTexture = video;
  42341. } else {
  42342. if ( format === undefined ) {
  42343. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42344. return this.createDefaultTexture( texture );
  42345. }
  42346. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42347. }
  42348. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  42349. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42350. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42351. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  42352. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42353. }
  42354. textureData.initialized = true;
  42355. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42356. }
  42357. destroyTexture( texture ) {
  42358. const backend = this.backend;
  42359. const textureData = backend.get( texture );
  42360. textureData.texture.destroy();
  42361. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42362. backend.delete( texture );
  42363. }
  42364. destroySampler( texture ) {
  42365. const backend = this.backend;
  42366. const textureData = backend.get( texture );
  42367. delete textureData.sampler;
  42368. }
  42369. generateMipmaps( texture ) {
  42370. const textureData = this.backend.get( texture );
  42371. if ( texture.isCubeTexture ) {
  42372. for ( let i = 0; i < 6; i ++ ) {
  42373. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42374. }
  42375. } else {
  42376. const depth = texture.image.depth || 1;
  42377. for ( let i = 0; i < depth; i ++ ) {
  42378. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42379. }
  42380. }
  42381. }
  42382. getColorBuffer() {
  42383. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42384. const backend = this.backend;
  42385. const { width, height } = backend.getDrawingBufferSize();
  42386. this.colorBuffer = backend.device.createTexture( {
  42387. label: 'colorBuffer',
  42388. size: {
  42389. width: width,
  42390. height: height,
  42391. depthOrArrayLayers: 1
  42392. },
  42393. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42394. format: backend.utils.getPreferredCanvasFormat(),
  42395. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42396. } );
  42397. return this.colorBuffer;
  42398. }
  42399. getDepthBuffer( depth = true, stencil = false ) {
  42400. const backend = this.backend;
  42401. const { width, height } = backend.getDrawingBufferSize();
  42402. const depthTexture = this.depthTexture;
  42403. const depthTextureGPU = backend.get( depthTexture ).texture;
  42404. let format, type;
  42405. if ( stencil ) {
  42406. format = DepthStencilFormat;
  42407. type = UnsignedInt248Type;
  42408. } else if ( depth ) {
  42409. format = DepthFormat;
  42410. type = UnsignedIntType;
  42411. }
  42412. if ( depthTextureGPU !== undefined ) {
  42413. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  42414. return depthTextureGPU;
  42415. }
  42416. this.destroyTexture( depthTexture );
  42417. }
  42418. depthTexture.name = 'depthBuffer';
  42419. depthTexture.format = format;
  42420. depthTexture.type = type;
  42421. depthTexture.image.width = width;
  42422. depthTexture.image.height = height;
  42423. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  42424. return backend.get( depthTexture ).texture;
  42425. }
  42426. updateTexture( texture, options ) {
  42427. const textureData = this.backend.get( texture );
  42428. const { textureDescriptorGPU } = textureData;
  42429. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42430. return;
  42431. // transfer texture data
  42432. if ( texture.isDataTexture ) {
  42433. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42434. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42435. for ( let i = 0; i < options.image.depth; i ++ ) {
  42436. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42437. }
  42438. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42439. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42440. } else if ( texture.isCubeTexture ) {
  42441. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42442. } else if ( texture.isVideoTexture ) {
  42443. const video = texture.source.data;
  42444. textureData.externalTexture = video;
  42445. } else {
  42446. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42447. }
  42448. //
  42449. textureData.version = texture.version;
  42450. if ( texture.onUpdate ) texture.onUpdate( texture );
  42451. }
  42452. async copyTextureToBuffer( texture, x, y, width, height ) {
  42453. const device = this.backend.device;
  42454. const textureData = this.backend.get( texture );
  42455. const textureGPU = textureData.texture;
  42456. const format = textureData.textureDescriptorGPU.format;
  42457. const bytesPerTexel = this._getBytesPerTexel( format );
  42458. let bytesPerRow = width * bytesPerTexel;
  42459. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42460. const readBuffer = device.createBuffer(
  42461. {
  42462. size: width * height * bytesPerTexel,
  42463. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42464. }
  42465. );
  42466. const encoder = device.createCommandEncoder();
  42467. encoder.copyTextureToBuffer(
  42468. {
  42469. texture: textureGPU,
  42470. origin: { x, y },
  42471. },
  42472. {
  42473. buffer: readBuffer,
  42474. bytesPerRow: bytesPerRow
  42475. },
  42476. {
  42477. width: width,
  42478. height: height
  42479. }
  42480. );
  42481. const typedArrayType = this._getTypedArrayType( format );
  42482. device.queue.submit( [ encoder.finish() ] );
  42483. await readBuffer.mapAsync( GPUMapMode.READ );
  42484. const buffer = readBuffer.getMappedRange();
  42485. return new typedArrayType( buffer );
  42486. }
  42487. _isEnvironmentTexture( texture ) {
  42488. const mapping = texture.mapping;
  42489. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42490. }
  42491. _getDefaultTextureGPU( format ) {
  42492. let defaultTexture = this.defaultTexture[ format ];
  42493. if ( defaultTexture === undefined ) {
  42494. const texture = new Texture();
  42495. texture.minFilter = NearestFilter;
  42496. texture.magFilter = NearestFilter;
  42497. this.createTexture( texture, { width: 1, height: 1, format } );
  42498. this.defaultTexture[ format ] = defaultTexture = texture;
  42499. }
  42500. return this.backend.get( defaultTexture ).texture;
  42501. }
  42502. _getDefaultCubeTextureGPU( format ) {
  42503. let defaultCubeTexture = this.defaultTexture[ format ];
  42504. if ( defaultCubeTexture === undefined ) {
  42505. const texture = new CubeTexture();
  42506. texture.minFilter = NearestFilter;
  42507. texture.magFilter = NearestFilter;
  42508. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42509. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42510. }
  42511. return this.backend.get( defaultCubeTexture ).texture;
  42512. }
  42513. _getDefaultVideoFrame() {
  42514. let defaultVideoFrame = this.defaultVideoFrame;
  42515. if ( defaultVideoFrame === null ) {
  42516. const init = {
  42517. timestamp: 0,
  42518. codedWidth: 1,
  42519. codedHeight: 1,
  42520. format: 'RGBA',
  42521. };
  42522. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42523. }
  42524. return defaultVideoFrame;
  42525. }
  42526. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42527. for ( let i = 0; i < 6; i ++ ) {
  42528. const image = images[ i ];
  42529. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42530. if ( image.isDataTexture ) {
  42531. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42532. } else {
  42533. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42534. }
  42535. }
  42536. }
  42537. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42538. const device = this.backend.device;
  42539. device.queue.copyExternalImageToTexture(
  42540. {
  42541. source: image
  42542. }, {
  42543. texture: textureGPU,
  42544. mipLevel: 0,
  42545. origin: { x: 0, y: 0, z: originDepth }
  42546. }, {
  42547. width: image.width,
  42548. height: image.height,
  42549. depthOrArrayLayers: 1
  42550. }
  42551. );
  42552. if ( flipY === true ) {
  42553. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42554. }
  42555. }
  42556. _getPassUtils() {
  42557. let passUtils = this._passUtils;
  42558. if ( passUtils === null ) {
  42559. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42560. }
  42561. return passUtils;
  42562. }
  42563. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42564. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42565. }
  42566. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42567. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42568. }
  42569. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42570. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42571. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42572. const device = this.backend.device;
  42573. const data = image.data;
  42574. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42575. const bytesPerRow = image.width * bytesPerTexel;
  42576. device.queue.writeTexture(
  42577. {
  42578. texture: textureGPU,
  42579. mipLevel: 0,
  42580. origin: { x: 0, y: 0, z: originDepth }
  42581. },
  42582. data,
  42583. {
  42584. offset: image.width * image.height * bytesPerTexel * depth,
  42585. bytesPerRow
  42586. },
  42587. {
  42588. width: image.width,
  42589. height: image.height,
  42590. depthOrArrayLayers: 1
  42591. } );
  42592. if ( flipY === true ) {
  42593. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42594. }
  42595. }
  42596. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42597. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42598. const device = this.backend.device;
  42599. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42600. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42601. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42602. const mipmap = mipmaps[ i ];
  42603. const width = mipmap.width;
  42604. const height = mipmap.height;
  42605. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42606. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42607. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42608. for ( let j = 0; j < depth; j ++ ) {
  42609. device.queue.writeTexture(
  42610. {
  42611. texture: textureGPU,
  42612. mipLevel: i,
  42613. origin: { x: 0, y: 0, z: j }
  42614. },
  42615. mipmap.data,
  42616. {
  42617. offset: j * bytesPerImage,
  42618. bytesPerRow,
  42619. rowsPerImage: Math.ceil( height / blockData.height )
  42620. },
  42621. {
  42622. width: Math.ceil( width / blockData.width ) * blockData.width,
  42623. height: Math.ceil( height / blockData.height ) * blockData.height,
  42624. depthOrArrayLayers: 1
  42625. }
  42626. );
  42627. }
  42628. }
  42629. }
  42630. _getBlockData( format ) {
  42631. // this method is only relevant for compressed texture formats
  42632. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42633. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42634. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42635. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42636. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42637. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42638. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42639. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42640. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42641. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42642. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42643. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42644. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42645. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42646. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42647. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42648. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42649. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42650. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42651. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42652. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42653. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42654. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42655. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42656. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42657. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42658. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42659. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42660. }
  42661. _convertAddressMode( value ) {
  42662. let addressMode = GPUAddressMode.ClampToEdge;
  42663. if ( value === RepeatWrapping ) {
  42664. addressMode = GPUAddressMode.Repeat;
  42665. } else if ( value === MirroredRepeatWrapping ) {
  42666. addressMode = GPUAddressMode.MirrorRepeat;
  42667. }
  42668. return addressMode;
  42669. }
  42670. _convertFilterMode( value ) {
  42671. let filterMode = GPUFilterMode.Linear;
  42672. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42673. filterMode = GPUFilterMode.Nearest;
  42674. }
  42675. return filterMode;
  42676. }
  42677. _getBytesPerTexel( format ) {
  42678. // 8-bit formats
  42679. if ( format === GPUTextureFormat.R8Unorm ||
  42680. format === GPUTextureFormat.R8Snorm ||
  42681. format === GPUTextureFormat.R8Uint ||
  42682. format === GPUTextureFormat.R8Sint ) return 1;
  42683. // 16-bit formats
  42684. if ( format === GPUTextureFormat.R16Uint ||
  42685. format === GPUTextureFormat.R16Sint ||
  42686. format === GPUTextureFormat.R16Float ||
  42687. format === GPUTextureFormat.RG8Unorm ||
  42688. format === GPUTextureFormat.RG8Snorm ||
  42689. format === GPUTextureFormat.RG8Uint ||
  42690. format === GPUTextureFormat.RG8Sint ) return 2;
  42691. // 32-bit formats
  42692. if ( format === GPUTextureFormat.R32Uint ||
  42693. format === GPUTextureFormat.R32Sint ||
  42694. format === GPUTextureFormat.R32Float ||
  42695. format === GPUTextureFormat.RG16Uint ||
  42696. format === GPUTextureFormat.RG16Sint ||
  42697. format === GPUTextureFormat.RG16Float ||
  42698. format === GPUTextureFormat.RGBA8Unorm ||
  42699. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42700. format === GPUTextureFormat.RGBA8Snorm ||
  42701. format === GPUTextureFormat.RGBA8Uint ||
  42702. format === GPUTextureFormat.RGBA8Sint ||
  42703. format === GPUTextureFormat.BGRA8Unorm ||
  42704. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42705. // Packed 32-bit formats
  42706. format === GPUTextureFormat.RGB9E5UFloat ||
  42707. format === GPUTextureFormat.RGB10A2Unorm ||
  42708. format === GPUTextureFormat.RG11B10UFloat ||
  42709. format === GPUTextureFormat.Depth32Float ||
  42710. format === GPUTextureFormat.Depth24Plus ||
  42711. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42712. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42713. // 64-bit formats
  42714. if ( format === GPUTextureFormat.RG32Uint ||
  42715. format === GPUTextureFormat.RG32Sint ||
  42716. format === GPUTextureFormat.RG32Float ||
  42717. format === GPUTextureFormat.RGBA16Uint ||
  42718. format === GPUTextureFormat.RGBA16Sint ||
  42719. format === GPUTextureFormat.RGBA16Float ) return 8;
  42720. // 128-bit formats
  42721. if ( format === GPUTextureFormat.RGBA32Uint ||
  42722. format === GPUTextureFormat.RGBA32Sint ||
  42723. format === GPUTextureFormat.RGBA32Float ) return 16;
  42724. }
  42725. _getTypedArrayType( format ) {
  42726. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42727. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42728. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42729. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42730. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42731. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42732. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42733. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42734. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42735. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42736. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42737. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42738. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42739. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42740. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42741. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42742. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42743. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42744. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  42745. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  42746. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  42747. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42748. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42749. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  42750. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  42751. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  42752. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  42753. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  42754. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  42755. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  42756. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  42757. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  42758. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42759. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42760. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42761. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42762. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42763. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42764. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42765. }
  42766. _getDimension( texture ) {
  42767. let dimension;
  42768. if ( texture.isData3DTexture ) {
  42769. dimension = GPUTextureDimension.ThreeD;
  42770. } else {
  42771. dimension = GPUTextureDimension.TwoD;
  42772. }
  42773. return dimension;
  42774. }
  42775. }
  42776. function getFormat( texture, device = null ) {
  42777. const format = texture.format;
  42778. const type = texture.type;
  42779. const colorSpace = texture.colorSpace;
  42780. let formatGPU;
  42781. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  42782. formatGPU = GPUTextureFormat.BGRA8Unorm;
  42783. } else if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42784. switch ( format ) {
  42785. case RGBA_S3TC_DXT1_Format:
  42786. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42787. break;
  42788. case RGBA_S3TC_DXT3_Format:
  42789. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42790. break;
  42791. case RGBA_S3TC_DXT5_Format:
  42792. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42793. break;
  42794. case RGB_ETC2_Format:
  42795. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42796. break;
  42797. case RGBA_ETC2_EAC_Format:
  42798. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42799. break;
  42800. case RGBA_ASTC_4x4_Format:
  42801. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42802. break;
  42803. case RGBA_ASTC_5x4_Format:
  42804. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42805. break;
  42806. case RGBA_ASTC_5x5_Format:
  42807. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42808. break;
  42809. case RGBA_ASTC_6x5_Format:
  42810. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42811. break;
  42812. case RGBA_ASTC_6x6_Format:
  42813. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42814. break;
  42815. case RGBA_ASTC_8x5_Format:
  42816. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42817. break;
  42818. case RGBA_ASTC_8x6_Format:
  42819. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42820. break;
  42821. case RGBA_ASTC_8x8_Format:
  42822. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42823. break;
  42824. case RGBA_ASTC_10x5_Format:
  42825. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42826. break;
  42827. case RGBA_ASTC_10x6_Format:
  42828. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42829. break;
  42830. case RGBA_ASTC_10x8_Format:
  42831. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42832. break;
  42833. case RGBA_ASTC_10x10_Format:
  42834. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42835. break;
  42836. case RGBA_ASTC_12x10_Format:
  42837. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42838. break;
  42839. case RGBA_ASTC_12x12_Format:
  42840. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42841. break;
  42842. default:
  42843. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42844. }
  42845. } else {
  42846. switch ( format ) {
  42847. case RGBAFormat:
  42848. switch ( type ) {
  42849. case ByteType:
  42850. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42851. break;
  42852. case ShortType:
  42853. formatGPU = GPUTextureFormat.RGBA16Sint;
  42854. break;
  42855. case UnsignedShortType:
  42856. formatGPU = GPUTextureFormat.RGBA16Uint;
  42857. break;
  42858. case UnsignedIntType:
  42859. formatGPU = GPUTextureFormat.RGBA32Uint;
  42860. break;
  42861. case IntType:
  42862. formatGPU = GPUTextureFormat.RGBA32Sint;
  42863. break;
  42864. case UnsignedByteType:
  42865. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42866. break;
  42867. case HalfFloatType:
  42868. formatGPU = GPUTextureFormat.RGBA16Float;
  42869. break;
  42870. case FloatType:
  42871. formatGPU = GPUTextureFormat.RGBA32Float;
  42872. break;
  42873. default:
  42874. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42875. }
  42876. break;
  42877. case RGBFormat:
  42878. switch ( type ) {
  42879. case UnsignedInt5999Type:
  42880. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42881. break;
  42882. default:
  42883. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42884. }
  42885. break;
  42886. case RedFormat:
  42887. switch ( type ) {
  42888. case ByteType:
  42889. formatGPU = GPUTextureFormat.R8Snorm;
  42890. break;
  42891. case ShortType:
  42892. formatGPU = GPUTextureFormat.R16Sint;
  42893. break;
  42894. case UnsignedShortType:
  42895. formatGPU = GPUTextureFormat.R16Uint;
  42896. break;
  42897. case UnsignedIntType:
  42898. formatGPU = GPUTextureFormat.R32Uint;
  42899. break;
  42900. case IntType:
  42901. formatGPU = GPUTextureFormat.R32Sint;
  42902. break;
  42903. case UnsignedByteType:
  42904. formatGPU = GPUTextureFormat.R8Unorm;
  42905. break;
  42906. case HalfFloatType:
  42907. formatGPU = GPUTextureFormat.R16Float;
  42908. break;
  42909. case FloatType:
  42910. formatGPU = GPUTextureFormat.R32Float;
  42911. break;
  42912. default:
  42913. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42914. }
  42915. break;
  42916. case RGFormat:
  42917. switch ( type ) {
  42918. case ByteType:
  42919. formatGPU = GPUTextureFormat.RG8Snorm;
  42920. break;
  42921. case ShortType:
  42922. formatGPU = GPUTextureFormat.RG16Sint;
  42923. break;
  42924. case UnsignedShortType:
  42925. formatGPU = GPUTextureFormat.RG16Uint;
  42926. break;
  42927. case UnsignedIntType:
  42928. formatGPU = GPUTextureFormat.RG32Uint;
  42929. break;
  42930. case IntType:
  42931. formatGPU = GPUTextureFormat.RG32Sint;
  42932. break;
  42933. case UnsignedByteType:
  42934. formatGPU = GPUTextureFormat.RG8Unorm;
  42935. break;
  42936. case HalfFloatType:
  42937. formatGPU = GPUTextureFormat.RG16Float;
  42938. break;
  42939. case FloatType:
  42940. formatGPU = GPUTextureFormat.RG32Float;
  42941. break;
  42942. default:
  42943. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42944. }
  42945. break;
  42946. case DepthFormat:
  42947. switch ( type ) {
  42948. case UnsignedShortType:
  42949. formatGPU = GPUTextureFormat.Depth16Unorm;
  42950. break;
  42951. case UnsignedIntType:
  42952. formatGPU = GPUTextureFormat.Depth24Plus;
  42953. break;
  42954. case FloatType:
  42955. formatGPU = GPUTextureFormat.Depth32Float;
  42956. break;
  42957. default:
  42958. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42959. }
  42960. break;
  42961. case DepthStencilFormat:
  42962. switch ( type ) {
  42963. case UnsignedInt248Type:
  42964. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42965. break;
  42966. case FloatType:
  42967. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42968. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42969. }
  42970. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42971. break;
  42972. default:
  42973. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42974. }
  42975. break;
  42976. case RedIntegerFormat:
  42977. switch ( type ) {
  42978. case IntType:
  42979. formatGPU = GPUTextureFormat.R32Sint;
  42980. break;
  42981. case UnsignedIntType:
  42982. formatGPU = GPUTextureFormat.R32Uint;
  42983. break;
  42984. default:
  42985. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42986. }
  42987. break;
  42988. case RGIntegerFormat:
  42989. switch ( type ) {
  42990. case IntType:
  42991. formatGPU = GPUTextureFormat.RG32Sint;
  42992. break;
  42993. case UnsignedIntType:
  42994. formatGPU = GPUTextureFormat.RG32Uint;
  42995. break;
  42996. default:
  42997. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42998. }
  42999. break;
  43000. case RGBAIntegerFormat:
  43001. switch ( type ) {
  43002. case IntType:
  43003. formatGPU = GPUTextureFormat.RGBA32Sint;
  43004. break;
  43005. case UnsignedIntType:
  43006. formatGPU = GPUTextureFormat.RGBA32Uint;
  43007. break;
  43008. default:
  43009. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43010. }
  43011. break;
  43012. default:
  43013. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43014. }
  43015. }
  43016. return formatGPU;
  43017. }
  43018. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43019. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43020. const wgslTypeLib$1 = {
  43021. 'f32': 'float',
  43022. 'i32': 'int',
  43023. 'u32': 'uint',
  43024. 'bool': 'bool',
  43025. 'vec2<f32>': 'vec2',
  43026. 'vec2<i32>': 'ivec2',
  43027. 'vec2<u32>': 'uvec2',
  43028. 'vec2<bool>': 'bvec2',
  43029. 'vec2f': 'vec2',
  43030. 'vec2i': 'ivec2',
  43031. 'vec2u': 'uvec2',
  43032. 'vec2b': 'bvec2',
  43033. 'vec3<f32>': 'vec3',
  43034. 'vec3<i32>': 'ivec3',
  43035. 'vec3<u32>': 'uvec3',
  43036. 'vec3<bool>': 'bvec3',
  43037. 'vec3f': 'vec3',
  43038. 'vec3i': 'ivec3',
  43039. 'vec3u': 'uvec3',
  43040. 'vec3b': 'bvec3',
  43041. 'vec4<f32>': 'vec4',
  43042. 'vec4<i32>': 'ivec4',
  43043. 'vec4<u32>': 'uvec4',
  43044. 'vec4<bool>': 'bvec4',
  43045. 'vec4f': 'vec4',
  43046. 'vec4i': 'ivec4',
  43047. 'vec4u': 'uvec4',
  43048. 'vec4b': 'bvec4',
  43049. 'mat2x2<f32>': 'mat2',
  43050. 'mat2x2f': 'mat2',
  43051. 'mat3x3<f32>': 'mat3',
  43052. 'mat3x3f': 'mat3',
  43053. 'mat4x4<f32>': 'mat4',
  43054. 'mat4x4f': 'mat4',
  43055. 'sampler': 'sampler',
  43056. 'texture_1d': 'texture',
  43057. 'texture_2d': 'texture',
  43058. 'texture_2d_array': 'texture',
  43059. 'texture_multisampled_2d': 'cubeTexture',
  43060. 'texture_depth_2d': 'depthTexture',
  43061. 'texture_3d': 'texture3D',
  43062. 'texture_cube': 'cubeTexture',
  43063. 'texture_cube_array': 'cubeTexture',
  43064. 'texture_storage_1d': 'storageTexture',
  43065. 'texture_storage_2d': 'storageTexture',
  43066. 'texture_storage_2d_array': 'storageTexture',
  43067. 'texture_storage_3d': 'storageTexture'
  43068. };
  43069. const parse = ( source ) => {
  43070. source = source.trim();
  43071. const declaration = source.match( declarationRegexp );
  43072. if ( declaration !== null && declaration.length === 4 ) {
  43073. const inputsCode = declaration[ 2 ];
  43074. const propsMatches = [];
  43075. let match = null;
  43076. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  43077. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  43078. }
  43079. // Process matches to correctly pair names and types
  43080. const inputs = [];
  43081. for ( let i = 0; i < propsMatches.length; i ++ ) {
  43082. const { name, type } = propsMatches[ i ];
  43083. let resolvedType = type;
  43084. if ( resolvedType.startsWith( 'texture' ) ) {
  43085. resolvedType = type.split( '<' )[ 0 ];
  43086. }
  43087. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  43088. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  43089. }
  43090. const blockCode = source.substring( declaration[ 0 ].length );
  43091. const outputType = declaration[ 3 ] || 'void';
  43092. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  43093. const type = wgslTypeLib$1[ outputType ] || outputType;
  43094. return {
  43095. type,
  43096. inputs,
  43097. name,
  43098. inputsCode,
  43099. blockCode,
  43100. outputType
  43101. };
  43102. } else {
  43103. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  43104. }
  43105. };
  43106. class WGSLNodeFunction extends NodeFunction {
  43107. constructor( source ) {
  43108. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  43109. super( type, inputs, name );
  43110. this.inputsCode = inputsCode;
  43111. this.blockCode = blockCode;
  43112. this.outputType = outputType;
  43113. }
  43114. getCode( name = this.name ) {
  43115. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  43116. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  43117. }
  43118. }
  43119. class WGSLNodeParser extends NodeParser {
  43120. parseFunction( source ) {
  43121. return new WGSLNodeFunction( source );
  43122. }
  43123. }
  43124. // GPUShaderStage is not defined in browsers not supporting WebGPU
  43125. const GPUShaderStage = self.GPUShaderStage;
  43126. const gpuShaderStageLib = {
  43127. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  43128. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  43129. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  43130. };
  43131. const supports = {
  43132. instance: true,
  43133. swizzleAssign: false,
  43134. storageBuffer: true
  43135. };
  43136. const wgslFnOpLib = {
  43137. '^^': 'tsl_xor'
  43138. };
  43139. const wgslTypeLib = {
  43140. float: 'f32',
  43141. int: 'i32',
  43142. uint: 'u32',
  43143. bool: 'bool',
  43144. color: 'vec3<f32>',
  43145. vec2: 'vec2<f32>',
  43146. ivec2: 'vec2<i32>',
  43147. uvec2: 'vec2<u32>',
  43148. bvec2: 'vec2<bool>',
  43149. vec3: 'vec3<f32>',
  43150. ivec3: 'vec3<i32>',
  43151. uvec3: 'vec3<u32>',
  43152. bvec3: 'vec3<bool>',
  43153. vec4: 'vec4<f32>',
  43154. ivec4: 'vec4<i32>',
  43155. uvec4: 'vec4<u32>',
  43156. bvec4: 'vec4<bool>',
  43157. mat2: 'mat2x2<f32>',
  43158. imat2: 'mat2x2<i32>',
  43159. umat2: 'mat2x2<u32>',
  43160. bmat2: 'mat2x2<bool>',
  43161. mat3: 'mat3x3<f32>',
  43162. imat3: 'mat3x3<i32>',
  43163. umat3: 'mat3x3<u32>',
  43164. bmat3: 'mat3x3<bool>',
  43165. mat4: 'mat4x4<f32>',
  43166. imat4: 'mat4x4<i32>',
  43167. umat4: 'mat4x4<u32>',
  43168. bmat4: 'mat4x4<bool>'
  43169. };
  43170. const wgslPolyfill = {
  43171. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  43172. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  43173. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  43174. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  43175. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  43176. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  43177. 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 ); }' ),
  43178. 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 ); }' ),
  43179. 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 ); }' ),
  43180. repeatWrapping: new CodeNode( `
  43181. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  43182. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  43183. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  43184. }
  43185. ` ),
  43186. biquadraticTexture: new CodeNode( `
  43187. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  43188. let res = vec2f( textureDimensions( map, level ) );
  43189. let uvScaled = coord * res;
  43190. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  43191. // https://www.shadertoy.com/view/WtyXRy
  43192. let uv = uvWrapping - 0.5;
  43193. let iuv = floor( uv );
  43194. let f = fract( uv );
  43195. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  43196. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  43197. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  43198. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  43199. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  43200. }
  43201. ` )
  43202. };
  43203. const wgslMethods = {
  43204. dFdx: 'dpdx',
  43205. dFdy: '- dpdy',
  43206. mod_float: 'tsl_mod_float',
  43207. mod_vec2: 'tsl_mod_vec2',
  43208. mod_vec3: 'tsl_mod_vec3',
  43209. mod_vec4: 'tsl_mod_vec4',
  43210. equals_bool: 'tsl_equals_bool',
  43211. equals_bvec2: 'tsl_equals_bvec2',
  43212. equals_bvec3: 'tsl_equals_bvec3',
  43213. equals_bvec4: 'tsl_equals_bvec4',
  43214. inversesqrt: 'inverseSqrt',
  43215. bitcast: 'bitcast<f32>'
  43216. };
  43217. // WebGPU issue: does not support pow() with negative base on Windows
  43218. if ( /Windows/g.test( navigator.userAgent ) ) {
  43219. 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 ); }' );
  43220. 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 ] );
  43221. 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 ] );
  43222. 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 ] );
  43223. wgslMethods.pow_float = 'tsl_pow_float';
  43224. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  43225. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  43226. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  43227. }
  43228. //
  43229. class WGSLNodeBuilder extends NodeBuilder {
  43230. constructor( object, renderer ) {
  43231. super( object, renderer, new WGSLNodeParser() );
  43232. this.uniformGroups = {};
  43233. this.builtins = {};
  43234. this.directives = {};
  43235. }
  43236. needsToWorkingColorSpace( texture ) {
  43237. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43238. }
  43239. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43240. if ( shaderStage === 'fragment' ) {
  43241. if ( depthSnippet ) {
  43242. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43243. } else {
  43244. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43245. }
  43246. } else if ( this.isFilteredTexture( texture ) ) {
  43247. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43248. } else {
  43249. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  43250. }
  43251. }
  43252. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43253. if ( shaderStage === 'fragment' ) {
  43254. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43255. } else {
  43256. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43257. }
  43258. }
  43259. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43260. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  43261. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43262. } else if ( this.isFilteredTexture( texture ) ) {
  43263. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43264. } else {
  43265. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  43266. }
  43267. }
  43268. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43269. this._include( 'biquadraticTexture' );
  43270. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  43271. }
  43272. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43273. this._include( 'repeatWrapping' );
  43274. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  43275. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  43276. }
  43277. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43278. if ( depthSnippet ) {
  43279. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  43280. } else {
  43281. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  43282. }
  43283. }
  43284. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43285. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43286. }
  43287. isUnfilterable( texture ) {
  43288. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  43289. }
  43290. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43291. let snippet = null;
  43292. if ( texture.isVideoTexture === true ) {
  43293. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43294. } else if ( this.isUnfilterable( texture ) ) {
  43295. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  43296. } else {
  43297. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43298. }
  43299. return snippet;
  43300. }
  43301. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43302. if ( shaderStage === 'fragment' ) {
  43303. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43304. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43305. } else {
  43306. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43307. }
  43308. }
  43309. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43310. if ( shaderStage === 'fragment' ) {
  43311. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43312. } else {
  43313. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43314. }
  43315. }
  43316. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43317. let snippet = null;
  43318. if ( texture.isVideoTexture === true ) {
  43319. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43320. } else {
  43321. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  43322. }
  43323. return snippet;
  43324. }
  43325. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43326. if ( shaderStage === 'fragment' ) {
  43327. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  43328. } else {
  43329. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  43330. }
  43331. }
  43332. getPropertyName( node, shaderStage = this.shaderStage ) {
  43333. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  43334. if ( shaderStage === 'vertex' ) {
  43335. return `varyings.${ node.name }`;
  43336. }
  43337. } else if ( node.isNodeUniform === true ) {
  43338. const name = node.name;
  43339. const type = node.type;
  43340. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43341. return name;
  43342. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  43343. return `NodeBuffer_${ node.id }.${name}`;
  43344. } else {
  43345. return node.groupNode.name + '.' + name;
  43346. }
  43347. }
  43348. return super.getPropertyName( node );
  43349. }
  43350. getOutputStructName() {
  43351. return 'output';
  43352. }
  43353. _getUniformGroupCount( shaderStage ) {
  43354. return Object.keys( this.uniforms[ shaderStage ] ).length;
  43355. }
  43356. getFunctionOperator( op ) {
  43357. const fnOp = wgslFnOpLib[ op ];
  43358. if ( fnOp !== undefined ) {
  43359. this._include( fnOp );
  43360. return fnOp;
  43361. }
  43362. return null;
  43363. }
  43364. getStorageAccess( node ) {
  43365. if ( node.isStorageTextureNode ) {
  43366. switch ( node.access ) {
  43367. case GPUStorageTextureAccess.ReadOnly:
  43368. return 'read';
  43369. case GPUStorageTextureAccess.WriteOnly:
  43370. return 'write';
  43371. default:
  43372. return 'read_write';
  43373. }
  43374. } else {
  43375. switch ( node.access ) {
  43376. case GPUBufferBindingType.Storage:
  43377. return 'read_write';
  43378. case GPUBufferBindingType.ReadOnlyStorage:
  43379. return 'read';
  43380. default:
  43381. return 'write';
  43382. }
  43383. }
  43384. }
  43385. getUniformFromNode( node, type, shaderStage, name = null ) {
  43386. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43387. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43388. if ( nodeData.uniformGPU === undefined ) {
  43389. let uniformGPU;
  43390. const group = node.groupNode;
  43391. const groupName = group.name;
  43392. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43393. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43394. let texture = null;
  43395. if ( type === 'texture' || type === 'storageTexture' ) {
  43396. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43397. } else if ( type === 'cubeTexture' ) {
  43398. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43399. } else if ( type === 'texture3D' ) {
  43400. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43401. }
  43402. texture.store = node.isStorageTextureNode === true;
  43403. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43404. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  43405. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  43406. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43407. bindings.push( sampler, texture );
  43408. uniformGPU = [ sampler, texture ];
  43409. } else {
  43410. bindings.push( texture );
  43411. uniformGPU = [ texture ];
  43412. }
  43413. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  43414. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  43415. const buffer = new bufferClass( node, group );
  43416. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43417. bindings.push( buffer );
  43418. uniformGPU = buffer;
  43419. } else {
  43420. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43421. let uniformsGroup = uniformsStage[ groupName ];
  43422. if ( uniformsGroup === undefined ) {
  43423. uniformsGroup = new NodeUniformsGroup( groupName, group );
  43424. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43425. uniformsStage[ groupName ] = uniformsGroup;
  43426. bindings.push( uniformsGroup );
  43427. }
  43428. uniformGPU = this.getNodeUniform( uniformNode, type );
  43429. uniformsGroup.addUniform( uniformGPU );
  43430. }
  43431. nodeData.uniformGPU = uniformGPU;
  43432. }
  43433. return uniformNode;
  43434. }
  43435. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  43436. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  43437. if ( map.has( name ) === false ) {
  43438. map.set( name, {
  43439. name,
  43440. property,
  43441. type
  43442. } );
  43443. }
  43444. return property;
  43445. }
  43446. getVertexIndex() {
  43447. if ( this.shaderStage === 'vertex' ) {
  43448. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  43449. }
  43450. return 'vertexIndex';
  43451. }
  43452. buildFunctionCode( shaderNode ) {
  43453. const layout = shaderNode.layout;
  43454. const flowData = this.flowShaderNode( shaderNode );
  43455. const parameters = [];
  43456. for ( const input of layout.inputs ) {
  43457. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  43458. }
  43459. //
  43460. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  43461. ${ flowData.vars }
  43462. ${ flowData.code }
  43463. `;
  43464. if ( flowData.result ) {
  43465. code += `\treturn ${ flowData.result };\n`;
  43466. }
  43467. code += '\n}\n';
  43468. //
  43469. return code;
  43470. }
  43471. getInstanceIndex() {
  43472. if ( this.shaderStage === 'vertex' ) {
  43473. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  43474. }
  43475. return 'instanceIndex';
  43476. }
  43477. getInvocationLocalIndex() {
  43478. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  43479. }
  43480. getSubgroupSize() {
  43481. this.enableSubGroups();
  43482. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43483. }
  43484. getSubgroupIndex() {
  43485. this.enableSubGroups();
  43486. return this.getBuiltin( 'subgroup_invocation_id', 'subgroupIndex', 'u32', 'attribute' );
  43487. }
  43488. getDrawIndex() {
  43489. return null;
  43490. }
  43491. getFrontFacing() {
  43492. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  43493. }
  43494. getFragCoord() {
  43495. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  43496. }
  43497. getFragDepth() {
  43498. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  43499. }
  43500. isFlipY() {
  43501. return false;
  43502. }
  43503. enableDirective( name, shaderStage = this.shaderStage ) {
  43504. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  43505. stage.add( name );
  43506. }
  43507. getDirectives( shaderStage ) {
  43508. const snippets = [];
  43509. const directives = this.directives[ shaderStage ];
  43510. if ( directives !== undefined ) {
  43511. for ( const directive of directives ) {
  43512. snippets.push( `enable ${directive};` );
  43513. }
  43514. }
  43515. return snippets.join( '\n' );
  43516. }
  43517. enableSubGroups() {
  43518. this.enableDirective( 'subgroups' );
  43519. }
  43520. enableSubgroupsF16() {
  43521. this.enableDirective( 'subgroups-f16' );
  43522. }
  43523. enableClipDistances() {
  43524. this.enableDirective( 'clip_distances' );
  43525. }
  43526. enableShaderF16() {
  43527. this.enableDirective( 'f16' );
  43528. }
  43529. enableDualSourceBlending() {
  43530. this.enableDirective( 'dual_source_blending' );
  43531. }
  43532. getBuiltins( shaderStage ) {
  43533. const snippets = [];
  43534. const builtins = this.builtins[ shaderStage ];
  43535. if ( builtins !== undefined ) {
  43536. for ( const { name, property, type } of builtins.values() ) {
  43537. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43538. }
  43539. }
  43540. return snippets.join( ',\n\t' );
  43541. }
  43542. getAttributes( shaderStage ) {
  43543. const snippets = [];
  43544. if ( shaderStage === 'compute' ) {
  43545. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43546. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43547. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43548. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43549. }
  43550. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43551. const builtins = this.getBuiltins( 'attribute' );
  43552. if ( builtins ) snippets.push( builtins );
  43553. const attributes = this.getAttributesArray();
  43554. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43555. const attribute = attributes[ index ];
  43556. const name = attribute.name;
  43557. const type = this.getType( attribute.type );
  43558. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43559. }
  43560. }
  43561. return snippets.join( ',\n\t' );
  43562. }
  43563. getStructMembers( struct ) {
  43564. const snippets = [];
  43565. const members = struct.getMemberTypes();
  43566. for ( let i = 0; i < members.length; i ++ ) {
  43567. const member = members[ i ];
  43568. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43569. }
  43570. const builtins = this.getBuiltins( 'output' );
  43571. if ( builtins ) snippets.push( '\t' + builtins );
  43572. return snippets.join( ',\n' );
  43573. }
  43574. getStructs( shaderStage ) {
  43575. const snippets = [];
  43576. const structs = this.structs[ shaderStage ];
  43577. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43578. const struct = structs[ index ];
  43579. const name = struct.name;
  43580. let snippet = `\struct ${ name } {\n`;
  43581. snippet += this.getStructMembers( struct );
  43582. snippet += '\n}';
  43583. snippets.push( snippet );
  43584. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43585. }
  43586. return snippets.join( '\n\n' );
  43587. }
  43588. getVar( type, name ) {
  43589. return `var ${ name } : ${ this.getType( type ) }`;
  43590. }
  43591. getVars( shaderStage ) {
  43592. const snippets = [];
  43593. const vars = this.vars[ shaderStage ];
  43594. if ( vars !== undefined ) {
  43595. for ( const variable of vars ) {
  43596. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43597. }
  43598. }
  43599. return `\n${ snippets.join( '\n' ) }\n`;
  43600. }
  43601. getVaryings( shaderStage ) {
  43602. const snippets = [];
  43603. if ( shaderStage === 'vertex' ) {
  43604. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43605. }
  43606. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43607. const varyings = this.varyings;
  43608. const vars = this.vars[ shaderStage ];
  43609. for ( let index = 0; index < varyings.length; index ++ ) {
  43610. const varying = varyings[ index ];
  43611. if ( varying.needsInterpolation ) {
  43612. let attributesSnippet = `@location( ${index} )`;
  43613. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43614. attributesSnippet += ' @interpolate( flat )';
  43615. }
  43616. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43617. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43618. vars.push( varying );
  43619. }
  43620. }
  43621. }
  43622. const builtins = this.getBuiltins( shaderStage );
  43623. if ( builtins ) snippets.push( builtins );
  43624. const code = snippets.join( ',\n\t' );
  43625. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43626. }
  43627. getUniforms( shaderStage ) {
  43628. const uniforms = this.uniforms[ shaderStage ];
  43629. const bindingSnippets = [];
  43630. const bufferSnippets = [];
  43631. const structSnippets = [];
  43632. const uniformGroups = {};
  43633. for ( const uniform of uniforms ) {
  43634. const groundName = uniform.groupNode.name;
  43635. const uniformIndexes = this.bindingsIndexes[ groundName ];
  43636. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43637. const texture = uniform.node.value;
  43638. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43639. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  43640. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43641. } else {
  43642. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43643. }
  43644. }
  43645. let textureType;
  43646. let multisampled = '';
  43647. if ( texture.isMultisampleRenderTargetTexture === true ) {
  43648. multisampled = '_multisampled';
  43649. }
  43650. if ( texture.isCubeTexture === true ) {
  43651. textureType = 'texture_cube<f32>';
  43652. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43653. textureType = 'texture_2d_array<f32>';
  43654. } else if ( texture.isDepthTexture === true ) {
  43655. textureType = `texture_depth${multisampled}_2d`;
  43656. } else if ( texture.isVideoTexture === true ) {
  43657. textureType = 'texture_external';
  43658. } else if ( texture.isData3DTexture === true ) {
  43659. textureType = 'texture_3d<f32>';
  43660. } else if ( uniform.node.isStorageTextureNode === true ) {
  43661. const format = getFormat( texture );
  43662. const access = this.getStorageAccess( uniform.node );
  43663. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43664. } else {
  43665. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43666. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43667. }
  43668. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43669. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  43670. const bufferNode = uniform.node;
  43671. const bufferType = this.getType( bufferNode.bufferType );
  43672. const bufferCount = bufferNode.bufferCount;
  43673. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  43674. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  43675. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  43676. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43677. } else {
  43678. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43679. const groupName = uniform.groupNode.name;
  43680. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43681. index: uniformIndexes.binding ++,
  43682. id: uniformIndexes.group,
  43683. snippets: []
  43684. } );
  43685. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43686. }
  43687. }
  43688. for ( const name in uniformGroups ) {
  43689. const group = uniformGroups[ name ];
  43690. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43691. }
  43692. let code = bindingSnippets.join( '\n' );
  43693. code += bufferSnippets.join( '\n' );
  43694. code += structSnippets.join( '\n' );
  43695. return code;
  43696. }
  43697. buildCode() {
  43698. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43699. this.sortBindingGroups();
  43700. for ( const shaderStage in shadersData ) {
  43701. const stageData = shadersData[ shaderStage ];
  43702. stageData.uniforms = this.getUniforms( shaderStage );
  43703. stageData.attributes = this.getAttributes( shaderStage );
  43704. stageData.varyings = this.getVaryings( shaderStage );
  43705. stageData.structs = this.getStructs( shaderStage );
  43706. stageData.vars = this.getVars( shaderStage );
  43707. stageData.codes = this.getCodes( shaderStage );
  43708. stageData.directives = this.getDirectives( shaderStage );
  43709. //
  43710. let flow = '// code\n\n';
  43711. flow += this.flowCode[ shaderStage ];
  43712. const flowNodes = this.flowNodes[ shaderStage ];
  43713. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43714. const outputNode = mainNode.outputNode;
  43715. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43716. for ( const node of flowNodes ) {
  43717. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43718. const slotName = node.name;
  43719. if ( slotName ) {
  43720. if ( flow.length > 0 ) flow += '\n';
  43721. flow += `\t// flow -> ${ slotName }\n\t`;
  43722. }
  43723. flow += `${ flowSlotData.code }\n\t`;
  43724. if ( node === mainNode && shaderStage !== 'compute' ) {
  43725. flow += '// result\n\n\t';
  43726. if ( shaderStage === 'vertex' ) {
  43727. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43728. } else if ( shaderStage === 'fragment' ) {
  43729. if ( isOutputStruct ) {
  43730. stageData.returnType = outputNode.nodeType;
  43731. flow += `return ${ flowSlotData.result };`;
  43732. } else {
  43733. let structSnippet = '\t@location(0) color: vec4<f32>';
  43734. const builtins = this.getBuiltins( 'output' );
  43735. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43736. stageData.returnType = 'OutputStruct';
  43737. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43738. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43739. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43740. }
  43741. }
  43742. }
  43743. }
  43744. stageData.flow = flow;
  43745. }
  43746. if ( this.material !== null ) {
  43747. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43748. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43749. } else {
  43750. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43751. }
  43752. }
  43753. getMethod( method, output = null ) {
  43754. let wgslMethod;
  43755. if ( output !== null ) {
  43756. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43757. }
  43758. if ( wgslMethod === undefined ) {
  43759. wgslMethod = this._getWGSLMethod( method );
  43760. }
  43761. return wgslMethod || method;
  43762. }
  43763. getType( type ) {
  43764. return wgslTypeLib[ type ] || type;
  43765. }
  43766. isAvailable( name ) {
  43767. let result = supports[ name ];
  43768. if ( result === undefined ) {
  43769. if ( name === 'float32Filterable' ) {
  43770. result = this.renderer.hasFeature( 'float32-filterable' );
  43771. }
  43772. supports[ name ] = result;
  43773. }
  43774. return result;
  43775. }
  43776. _getWGSLMethod( method ) {
  43777. if ( wgslPolyfill[ method ] !== undefined ) {
  43778. this._include( method );
  43779. }
  43780. return wgslMethods[ method ];
  43781. }
  43782. _include( name ) {
  43783. const codeNode = wgslPolyfill[ name ];
  43784. codeNode.build( this );
  43785. if ( this.currentFunctionNode !== null ) {
  43786. this.currentFunctionNode.includes.push( codeNode );
  43787. }
  43788. return codeNode;
  43789. }
  43790. _getWGSLVertexCode( shaderData ) {
  43791. return `${ this.getSignature() }
  43792. // directives
  43793. ${shaderData.directives}
  43794. // uniforms
  43795. ${shaderData.uniforms}
  43796. // varyings
  43797. ${shaderData.varyings}
  43798. var<private> varyings : VaryingsStruct;
  43799. // codes
  43800. ${shaderData.codes}
  43801. @vertex
  43802. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43803. // vars
  43804. ${shaderData.vars}
  43805. // flow
  43806. ${shaderData.flow}
  43807. return varyings;
  43808. }
  43809. `;
  43810. }
  43811. _getWGSLFragmentCode( shaderData ) {
  43812. return `${ this.getSignature() }
  43813. diagnostic( off, derivative_uniformity );
  43814. // uniforms
  43815. ${shaderData.uniforms}
  43816. // structs
  43817. ${shaderData.structs}
  43818. // codes
  43819. ${shaderData.codes}
  43820. @fragment
  43821. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43822. // vars
  43823. ${shaderData.vars}
  43824. // flow
  43825. ${shaderData.flow}
  43826. }
  43827. `;
  43828. }
  43829. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43830. return `${ this.getSignature() }
  43831. // directives
  43832. ${shaderData.directives}
  43833. // system
  43834. var<private> instanceIndex : u32;
  43835. // uniforms
  43836. ${shaderData.uniforms}
  43837. // codes
  43838. ${shaderData.codes}
  43839. @compute @workgroup_size( ${workgroupSize} )
  43840. fn main( ${shaderData.attributes} ) {
  43841. // system
  43842. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43843. // vars
  43844. ${shaderData.vars}
  43845. // flow
  43846. ${shaderData.flow}
  43847. }
  43848. `;
  43849. }
  43850. _getWGSLStruct( name, vars ) {
  43851. return `
  43852. struct ${name} {
  43853. ${vars}
  43854. };`;
  43855. }
  43856. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43857. const structName = name + 'Struct';
  43858. const structSnippet = this._getWGSLStruct( structName, vars );
  43859. return `${structSnippet}
  43860. @binding( ${binding} ) @group( ${group} )
  43861. var<${access}> ${name} : ${structName};`;
  43862. }
  43863. }
  43864. class WebGPUUtils {
  43865. constructor( backend ) {
  43866. this.backend = backend;
  43867. }
  43868. getCurrentDepthStencilFormat( renderContext ) {
  43869. let format;
  43870. if ( renderContext.depthTexture !== null ) {
  43871. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43872. } else if ( renderContext.depth && renderContext.stencil ) {
  43873. format = GPUTextureFormat.Depth24PlusStencil8;
  43874. } else if ( renderContext.depth ) {
  43875. format = GPUTextureFormat.Depth24Plus;
  43876. }
  43877. return format;
  43878. }
  43879. getTextureFormatGPU( texture ) {
  43880. return this.backend.get( texture ).texture.format;
  43881. }
  43882. getCurrentColorFormat( renderContext ) {
  43883. let format;
  43884. if ( renderContext.textures !== null ) {
  43885. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43886. } else {
  43887. format = this.getPreferredCanvasFormat(); // default context format
  43888. }
  43889. return format;
  43890. }
  43891. getCurrentColorSpace( renderContext ) {
  43892. if ( renderContext.textures !== null ) {
  43893. return renderContext.textures[ 0 ].colorSpace;
  43894. }
  43895. return this.backend.renderer.outputColorSpace;
  43896. }
  43897. getPrimitiveTopology( object, material ) {
  43898. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43899. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43900. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43901. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43902. }
  43903. getSampleCount( sampleCount ) {
  43904. let count = 1;
  43905. if ( sampleCount > 1 ) {
  43906. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43907. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43908. if ( count === 2 ) {
  43909. count = 4;
  43910. }
  43911. }
  43912. return count;
  43913. }
  43914. getSampleCountRenderContext( renderContext ) {
  43915. if ( renderContext.textures !== null ) {
  43916. return this.getSampleCount( renderContext.sampleCount );
  43917. }
  43918. return this.getSampleCount( this.backend.renderer.samples );
  43919. }
  43920. getPreferredCanvasFormat() {
  43921. // TODO: Remove this check when Quest 34.5 is out
  43922. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43923. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43924. return GPUTextureFormat.BGRA8Unorm;
  43925. } else {
  43926. return navigator.gpu.getPreferredCanvasFormat();
  43927. }
  43928. }
  43929. }
  43930. const typedArraysToVertexFormatPrefix = new Map( [
  43931. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43932. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43933. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43934. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43935. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43936. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43937. [ Float32Array, [ 'float32', ]],
  43938. ] );
  43939. const typedAttributeToVertexFormatPrefix = new Map( [
  43940. [ Float16BufferAttribute, [ 'float16', ]],
  43941. ] );
  43942. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43943. [ Int32Array, 'sint32' ],
  43944. [ Int16Array, 'sint32' ], // patch for INT16
  43945. [ Uint32Array, 'uint32' ],
  43946. [ Uint16Array, 'uint32' ], // patch for UINT16
  43947. [ Float32Array, 'float32' ]
  43948. ] );
  43949. class WebGPUAttributeUtils {
  43950. constructor( backend ) {
  43951. this.backend = backend;
  43952. }
  43953. createAttribute( attribute, usage ) {
  43954. const bufferAttribute = this._getBufferAttribute( attribute );
  43955. const backend = this.backend;
  43956. const bufferData = backend.get( bufferAttribute );
  43957. let buffer = bufferData.buffer;
  43958. if ( buffer === undefined ) {
  43959. const device = backend.device;
  43960. let array = bufferAttribute.array;
  43961. // patch for INT16 and UINT16
  43962. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  43963. const tempArray = new Uint32Array( array.length );
  43964. for ( let i = 0; i < array.length; i ++ ) {
  43965. tempArray[ i ] = array[ i ];
  43966. }
  43967. array = tempArray;
  43968. }
  43969. bufferAttribute.array = array;
  43970. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43971. array = new array.constructor( bufferAttribute.count * 4 );
  43972. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43973. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43974. }
  43975. // Update BufferAttribute
  43976. bufferAttribute.itemSize = 4;
  43977. bufferAttribute.array = array;
  43978. }
  43979. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43980. buffer = device.createBuffer( {
  43981. label: bufferAttribute.name,
  43982. size: size,
  43983. usage: usage,
  43984. mappedAtCreation: true
  43985. } );
  43986. new array.constructor( buffer.getMappedRange() ).set( array );
  43987. buffer.unmap();
  43988. bufferData.buffer = buffer;
  43989. }
  43990. }
  43991. updateAttribute( attribute ) {
  43992. const bufferAttribute = this._getBufferAttribute( attribute );
  43993. const backend = this.backend;
  43994. const device = backend.device;
  43995. const buffer = backend.get( bufferAttribute ).buffer;
  43996. const array = bufferAttribute.array;
  43997. const updateRanges = bufferAttribute.updateRanges;
  43998. if ( updateRanges.length === 0 ) {
  43999. // Not using update ranges
  44000. device.queue.writeBuffer(
  44001. buffer,
  44002. 0,
  44003. array,
  44004. 0
  44005. );
  44006. } else {
  44007. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44008. const range = updateRanges[ i ];
  44009. device.queue.writeBuffer(
  44010. buffer,
  44011. 0,
  44012. array,
  44013. range.start * array.BYTES_PER_ELEMENT,
  44014. range.count * array.BYTES_PER_ELEMENT
  44015. );
  44016. }
  44017. bufferAttribute.clearUpdateRanges();
  44018. }
  44019. }
  44020. createShaderVertexBuffers( renderObject ) {
  44021. const attributes = renderObject.getAttributes();
  44022. const vertexBuffers = new Map();
  44023. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  44024. const geometryAttribute = attributes[ slot ];
  44025. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  44026. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  44027. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  44028. if ( vertexBufferLayout === undefined ) {
  44029. let arrayStride, stepMode;
  44030. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  44031. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  44032. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44033. } else {
  44034. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  44035. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44036. }
  44037. // patch for INT16 and UINT16
  44038. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  44039. arrayStride = 4;
  44040. }
  44041. vertexBufferLayout = {
  44042. arrayStride,
  44043. attributes: [],
  44044. stepMode
  44045. };
  44046. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  44047. }
  44048. const format = this._getVertexFormat( geometryAttribute );
  44049. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  44050. vertexBufferLayout.attributes.push( {
  44051. shaderLocation: slot,
  44052. offset,
  44053. format
  44054. } );
  44055. }
  44056. return Array.from( vertexBuffers.values() );
  44057. }
  44058. destroyAttribute( attribute ) {
  44059. const backend = this.backend;
  44060. const data = backend.get( this._getBufferAttribute( attribute ) );
  44061. data.buffer.destroy();
  44062. backend.delete( attribute );
  44063. }
  44064. async getArrayBufferAsync( attribute ) {
  44065. const backend = this.backend;
  44066. const device = backend.device;
  44067. const data = backend.get( this._getBufferAttribute( attribute ) );
  44068. const bufferGPU = data.buffer;
  44069. const size = bufferGPU.size;
  44070. const readBufferGPU = device.createBuffer( {
  44071. label: attribute.name,
  44072. size,
  44073. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44074. } );
  44075. const cmdEncoder = device.createCommandEncoder( {} );
  44076. cmdEncoder.copyBufferToBuffer(
  44077. bufferGPU,
  44078. 0,
  44079. readBufferGPU,
  44080. 0,
  44081. size
  44082. );
  44083. readBufferGPU.unmap();
  44084. const gpuCommands = cmdEncoder.finish();
  44085. device.queue.submit( [ gpuCommands ] );
  44086. await readBufferGPU.mapAsync( GPUMapMode.READ );
  44087. const arrayBuffer = readBufferGPU.getMappedRange();
  44088. return arrayBuffer;
  44089. }
  44090. _getVertexFormat( geometryAttribute ) {
  44091. const { itemSize, normalized } = geometryAttribute;
  44092. const ArrayType = geometryAttribute.array.constructor;
  44093. const AttributeType = geometryAttribute.constructor;
  44094. let format;
  44095. if ( itemSize == 1 ) {
  44096. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  44097. } else {
  44098. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  44099. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  44100. if ( prefix ) {
  44101. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  44102. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  44103. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  44104. if ( paddedItemSize % 1 ) {
  44105. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  44106. }
  44107. format = `${prefix}x${paddedItemSize}`;
  44108. }
  44109. }
  44110. if ( ! format ) {
  44111. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  44112. }
  44113. return format;
  44114. }
  44115. _getBufferAttribute( attribute ) {
  44116. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  44117. return attribute;
  44118. }
  44119. }
  44120. class WebGPUBindingUtils {
  44121. constructor( backend ) {
  44122. this.backend = backend;
  44123. this.bindGroupLayoutCache = new WeakMap();
  44124. }
  44125. createBindingsLayout( bindGroup ) {
  44126. const backend = this.backend;
  44127. const device = backend.device;
  44128. const entries = [];
  44129. let index = 0;
  44130. for ( const binding of bindGroup.bindings ) {
  44131. const bindingGPU = {
  44132. binding: index ++,
  44133. visibility: binding.visibility
  44134. };
  44135. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  44136. const buffer = {}; // GPUBufferBindingLayout
  44137. if ( binding.isStorageBuffer ) {
  44138. buffer.type = binding.access;
  44139. }
  44140. bindingGPU.buffer = buffer;
  44141. } else if ( binding.isSampler ) {
  44142. const sampler = {}; // GPUSamplerBindingLayout
  44143. if ( binding.texture.isDepthTexture ) {
  44144. if ( binding.texture.compareFunction !== null ) {
  44145. sampler.type = 'comparison';
  44146. }
  44147. }
  44148. bindingGPU.sampler = sampler;
  44149. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  44150. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  44151. } else if ( binding.isSampledTexture && binding.store ) {
  44152. const format = this.backend.get( binding.texture ).texture.format;
  44153. const access = binding.access;
  44154. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  44155. } else if ( binding.isSampledTexture ) {
  44156. const texture = {}; // GPUTextureBindingLayout
  44157. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  44158. texture.multisampled = true;
  44159. }
  44160. if ( binding.texture.isDepthTexture ) {
  44161. texture.sampleType = GPUTextureSampleType.Depth;
  44162. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  44163. const type = binding.texture.type;
  44164. if ( type === IntType ) {
  44165. texture.sampleType = GPUTextureSampleType.SInt;
  44166. } else if ( type === UnsignedIntType ) {
  44167. texture.sampleType = GPUTextureSampleType.UInt;
  44168. } else if ( type === FloatType ) {
  44169. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  44170. texture.sampleType = GPUTextureSampleType.Float;
  44171. } else {
  44172. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44173. }
  44174. }
  44175. }
  44176. if ( binding.isSampledCubeTexture ) {
  44177. texture.viewDimension = GPUTextureViewDimension.Cube;
  44178. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44179. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  44180. } else if ( binding.isSampledTexture3D ) {
  44181. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  44182. }
  44183. bindingGPU.texture = texture;
  44184. } else {
  44185. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  44186. }
  44187. entries.push( bindingGPU );
  44188. }
  44189. return device.createBindGroupLayout( { entries } );
  44190. }
  44191. createBindings( bindGroup ) {
  44192. const { backend, bindGroupLayoutCache } = this;
  44193. const bindingsData = backend.get( bindGroup );
  44194. // setup (static) binding layout and (dynamic) binding group
  44195. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  44196. if ( bindLayoutGPU === undefined ) {
  44197. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  44198. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  44199. }
  44200. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  44201. bindingsData.layout = bindLayoutGPU;
  44202. bindingsData.group = bindGroupGPU;
  44203. }
  44204. updateBinding( binding ) {
  44205. const backend = this.backend;
  44206. const device = backend.device;
  44207. const buffer = binding.buffer;
  44208. const bufferGPU = backend.get( binding ).buffer;
  44209. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  44210. }
  44211. createBindGroup( bindGroup, layoutGPU ) {
  44212. const backend = this.backend;
  44213. const device = backend.device;
  44214. let bindingPoint = 0;
  44215. const entriesGPU = [];
  44216. for ( const binding of bindGroup.bindings ) {
  44217. if ( binding.isUniformBuffer ) {
  44218. const bindingData = backend.get( binding );
  44219. if ( bindingData.buffer === undefined ) {
  44220. const byteLength = binding.byteLength;
  44221. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  44222. const bufferGPU = device.createBuffer( {
  44223. label: 'bindingBuffer_' + binding.name,
  44224. size: byteLength,
  44225. usage: usage
  44226. } );
  44227. bindingData.buffer = bufferGPU;
  44228. }
  44229. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44230. } else if ( binding.isStorageBuffer ) {
  44231. const bindingData = backend.get( binding );
  44232. if ( bindingData.buffer === undefined ) {
  44233. const attribute = binding.attribute;
  44234. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  44235. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  44236. bindingData.buffer = backend.get( attribute ).buffer;
  44237. }
  44238. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44239. } else if ( binding.isSampler ) {
  44240. const textureGPU = backend.get( binding.texture );
  44241. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  44242. } else if ( binding.isSampledTexture ) {
  44243. const textureData = backend.get( binding.texture );
  44244. let resourceGPU;
  44245. if ( textureData.externalTexture !== undefined ) {
  44246. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  44247. } else {
  44248. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  44249. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  44250. resourceGPU = textureData[ propertyName ];
  44251. if ( resourceGPU === undefined ) {
  44252. const aspectGPU = GPUTextureAspect.All;
  44253. let dimensionViewGPU;
  44254. if ( binding.isSampledCubeTexture ) {
  44255. dimensionViewGPU = GPUTextureViewDimension.Cube;
  44256. } else if ( binding.isSampledTexture3D ) {
  44257. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  44258. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44259. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  44260. } else {
  44261. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  44262. }
  44263. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  44264. }
  44265. }
  44266. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  44267. }
  44268. bindingPoint ++;
  44269. }
  44270. return device.createBindGroup( {
  44271. label: 'bindGroup_' + bindGroup.name,
  44272. layout: layoutGPU,
  44273. entries: entriesGPU
  44274. } );
  44275. }
  44276. }
  44277. class WebGPUPipelineUtils {
  44278. constructor( backend ) {
  44279. this.backend = backend;
  44280. }
  44281. _getSampleCount( renderObjectContext ) {
  44282. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  44283. }
  44284. createRenderPipeline( renderObject, promises ) {
  44285. const { object, material, geometry, pipeline } = renderObject;
  44286. const { vertexProgram, fragmentProgram } = pipeline;
  44287. const backend = this.backend;
  44288. const device = backend.device;
  44289. const utils = backend.utils;
  44290. const pipelineData = backend.get( pipeline );
  44291. // bind group layouts
  44292. const bindGroupLayouts = [];
  44293. for ( const bindGroup of renderObject.getBindings() ) {
  44294. const bindingsData = backend.get( bindGroup );
  44295. bindGroupLayouts.push( bindingsData.layout );
  44296. }
  44297. // vertex buffers
  44298. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  44299. // blending
  44300. let blending;
  44301. if ( material.transparent === true && material.blending !== NoBlending ) {
  44302. blending = this._getBlending( material );
  44303. }
  44304. // stencil
  44305. let stencilFront = {};
  44306. if ( material.stencilWrite === true ) {
  44307. stencilFront = {
  44308. compare: this._getStencilCompare( material ),
  44309. failOp: this._getStencilOperation( material.stencilFail ),
  44310. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  44311. passOp: this._getStencilOperation( material.stencilZPass )
  44312. };
  44313. }
  44314. const colorWriteMask = this._getColorWriteMask( material );
  44315. const targets = [];
  44316. if ( renderObject.context.textures !== null ) {
  44317. const textures = renderObject.context.textures;
  44318. for ( let i = 0; i < textures.length; i ++ ) {
  44319. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  44320. targets.push( {
  44321. format: colorFormat,
  44322. blend: blending,
  44323. writeMask: colorWriteMask
  44324. } );
  44325. }
  44326. } else {
  44327. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44328. targets.push( {
  44329. format: colorFormat,
  44330. blend: blending,
  44331. writeMask: colorWriteMask
  44332. } );
  44333. }
  44334. const vertexModule = backend.get( vertexProgram ).module;
  44335. const fragmentModule = backend.get( fragmentProgram ).module;
  44336. const primitiveState = this._getPrimitiveState( object, geometry, material );
  44337. const depthCompare = this._getDepthCompare( material );
  44338. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44339. const sampleCount = this._getSampleCount( renderObject.context );
  44340. const pipelineDescriptor = {
  44341. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  44342. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  44343. fragment: Object.assign( {}, fragmentModule, { targets } ),
  44344. primitive: primitiveState,
  44345. depthStencil: {
  44346. format: depthStencilFormat,
  44347. depthWriteEnabled: material.depthWrite,
  44348. depthCompare: depthCompare,
  44349. stencilFront: stencilFront,
  44350. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  44351. stencilReadMask: material.stencilFuncMask,
  44352. stencilWriteMask: material.stencilWriteMask
  44353. },
  44354. multisample: {
  44355. count: sampleCount,
  44356. alphaToCoverageEnabled: material.alphaToCoverage
  44357. },
  44358. layout: device.createPipelineLayout( {
  44359. bindGroupLayouts
  44360. } )
  44361. };
  44362. if ( promises === null ) {
  44363. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  44364. } else {
  44365. const p = new Promise( ( resolve /*, reject*/ ) => {
  44366. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  44367. pipelineData.pipeline = pipeline;
  44368. resolve();
  44369. } );
  44370. } );
  44371. promises.push( p );
  44372. }
  44373. }
  44374. createBundleEncoder( renderContext ) {
  44375. const backend = this.backend;
  44376. const { utils, device } = backend;
  44377. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  44378. const colorFormat = utils.getCurrentColorFormat( renderContext );
  44379. const sampleCount = this._getSampleCount( renderContext );
  44380. const descriptor = {
  44381. label: 'renderBundleEncoder',
  44382. colorFormats: [ colorFormat ],
  44383. depthStencilFormat,
  44384. sampleCount
  44385. };
  44386. return device.createRenderBundleEncoder( descriptor );
  44387. }
  44388. createComputePipeline( pipeline, bindings ) {
  44389. const backend = this.backend;
  44390. const device = backend.device;
  44391. const computeProgram = backend.get( pipeline.computeProgram ).module;
  44392. const pipelineGPU = backend.get( pipeline );
  44393. // bind group layouts
  44394. const bindGroupLayouts = [];
  44395. for ( const bindingsGroup of bindings ) {
  44396. const bindingsData = backend.get( bindingsGroup );
  44397. bindGroupLayouts.push( bindingsData.layout );
  44398. }
  44399. pipelineGPU.pipeline = device.createComputePipeline( {
  44400. compute: computeProgram,
  44401. layout: device.createPipelineLayout( {
  44402. bindGroupLayouts
  44403. } )
  44404. } );
  44405. }
  44406. _getBlending( material ) {
  44407. let color, alpha;
  44408. const blending = material.blending;
  44409. const blendSrc = material.blendSrc;
  44410. const blendDst = material.blendDst;
  44411. const blendEquation = material.blendEquation;
  44412. if ( blending === CustomBlending ) {
  44413. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44414. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44415. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44416. color = {
  44417. srcFactor: this._getBlendFactor( blendSrc ),
  44418. dstFactor: this._getBlendFactor( blendDst ),
  44419. operation: this._getBlendOperation( blendEquation )
  44420. };
  44421. alpha = {
  44422. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44423. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44424. operation: this._getBlendOperation( blendEquationAlpha )
  44425. };
  44426. } else {
  44427. const premultipliedAlpha = material.premultipliedAlpha;
  44428. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44429. color = {
  44430. srcFactor: srcRGB,
  44431. dstFactor: dstRGB,
  44432. operation: GPUBlendOperation.Add
  44433. };
  44434. alpha = {
  44435. srcFactor: srcAlpha,
  44436. dstFactor: dstAlpha,
  44437. operation: GPUBlendOperation.Add
  44438. };
  44439. };
  44440. if ( premultipliedAlpha ) {
  44441. switch ( blending ) {
  44442. case NormalBlending:
  44443. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44444. break;
  44445. case AdditiveBlending:
  44446. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44447. break;
  44448. case SubtractiveBlending:
  44449. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44450. break;
  44451. case MultiplyBlending:
  44452. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44453. break;
  44454. }
  44455. } else {
  44456. switch ( blending ) {
  44457. case NormalBlending:
  44458. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44459. break;
  44460. case AdditiveBlending:
  44461. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44462. break;
  44463. case SubtractiveBlending:
  44464. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44465. break;
  44466. case MultiplyBlending:
  44467. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44468. break;
  44469. }
  44470. }
  44471. }
  44472. if ( color !== undefined && alpha !== undefined ) {
  44473. return { color, alpha };
  44474. } else {
  44475. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44476. }
  44477. }
  44478. _getBlendFactor( blend ) {
  44479. let blendFactor;
  44480. switch ( blend ) {
  44481. case ZeroFactor:
  44482. blendFactor = GPUBlendFactor.Zero;
  44483. break;
  44484. case OneFactor:
  44485. blendFactor = GPUBlendFactor.One;
  44486. break;
  44487. case SrcColorFactor:
  44488. blendFactor = GPUBlendFactor.Src;
  44489. break;
  44490. case OneMinusSrcColorFactor:
  44491. blendFactor = GPUBlendFactor.OneMinusSrc;
  44492. break;
  44493. case SrcAlphaFactor:
  44494. blendFactor = GPUBlendFactor.SrcAlpha;
  44495. break;
  44496. case OneMinusSrcAlphaFactor:
  44497. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44498. break;
  44499. case DstColorFactor:
  44500. blendFactor = GPUBlendFactor.Dst;
  44501. break;
  44502. case OneMinusDstColorFactor:
  44503. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44504. break;
  44505. case DstAlphaFactor:
  44506. blendFactor = GPUBlendFactor.DstAlpha;
  44507. break;
  44508. case OneMinusDstAlphaFactor:
  44509. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44510. break;
  44511. case SrcAlphaSaturateFactor:
  44512. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44513. break;
  44514. case BlendColorFactor:
  44515. blendFactor = GPUBlendFactor.Constant;
  44516. break;
  44517. case OneMinusBlendColorFactor:
  44518. blendFactor = GPUBlendFactor.OneMinusConstant;
  44519. break;
  44520. default:
  44521. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44522. }
  44523. return blendFactor;
  44524. }
  44525. _getStencilCompare( material ) {
  44526. let stencilCompare;
  44527. const stencilFunc = material.stencilFunc;
  44528. switch ( stencilFunc ) {
  44529. case NeverStencilFunc:
  44530. stencilCompare = GPUCompareFunction.Never;
  44531. break;
  44532. case AlwaysStencilFunc:
  44533. stencilCompare = GPUCompareFunction.Always;
  44534. break;
  44535. case LessStencilFunc:
  44536. stencilCompare = GPUCompareFunction.Less;
  44537. break;
  44538. case LessEqualStencilFunc:
  44539. stencilCompare = GPUCompareFunction.LessEqual;
  44540. break;
  44541. case EqualStencilFunc:
  44542. stencilCompare = GPUCompareFunction.Equal;
  44543. break;
  44544. case GreaterEqualStencilFunc:
  44545. stencilCompare = GPUCompareFunction.GreaterEqual;
  44546. break;
  44547. case GreaterStencilFunc:
  44548. stencilCompare = GPUCompareFunction.Greater;
  44549. break;
  44550. case NotEqualStencilFunc:
  44551. stencilCompare = GPUCompareFunction.NotEqual;
  44552. break;
  44553. default:
  44554. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44555. }
  44556. return stencilCompare;
  44557. }
  44558. _getStencilOperation( op ) {
  44559. let stencilOperation;
  44560. switch ( op ) {
  44561. case KeepStencilOp:
  44562. stencilOperation = GPUStencilOperation.Keep;
  44563. break;
  44564. case ZeroStencilOp:
  44565. stencilOperation = GPUStencilOperation.Zero;
  44566. break;
  44567. case ReplaceStencilOp:
  44568. stencilOperation = GPUStencilOperation.Replace;
  44569. break;
  44570. case InvertStencilOp:
  44571. stencilOperation = GPUStencilOperation.Invert;
  44572. break;
  44573. case IncrementStencilOp:
  44574. stencilOperation = GPUStencilOperation.IncrementClamp;
  44575. break;
  44576. case DecrementStencilOp:
  44577. stencilOperation = GPUStencilOperation.DecrementClamp;
  44578. break;
  44579. case IncrementWrapStencilOp:
  44580. stencilOperation = GPUStencilOperation.IncrementWrap;
  44581. break;
  44582. case DecrementWrapStencilOp:
  44583. stencilOperation = GPUStencilOperation.DecrementWrap;
  44584. break;
  44585. default:
  44586. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44587. }
  44588. return stencilOperation;
  44589. }
  44590. _getBlendOperation( blendEquation ) {
  44591. let blendOperation;
  44592. switch ( blendEquation ) {
  44593. case AddEquation:
  44594. blendOperation = GPUBlendOperation.Add;
  44595. break;
  44596. case SubtractEquation:
  44597. blendOperation = GPUBlendOperation.Subtract;
  44598. break;
  44599. case ReverseSubtractEquation:
  44600. blendOperation = GPUBlendOperation.ReverseSubtract;
  44601. break;
  44602. case MinEquation:
  44603. blendOperation = GPUBlendOperation.Min;
  44604. break;
  44605. case MaxEquation:
  44606. blendOperation = GPUBlendOperation.Max;
  44607. break;
  44608. default:
  44609. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44610. }
  44611. return blendOperation;
  44612. }
  44613. _getPrimitiveState( object, geometry, material ) {
  44614. const descriptor = {};
  44615. const utils = this.backend.utils;
  44616. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44617. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44618. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44619. }
  44620. switch ( material.side ) {
  44621. case FrontSide:
  44622. descriptor.frontFace = GPUFrontFace.CCW;
  44623. descriptor.cullMode = GPUCullMode.Back;
  44624. break;
  44625. case BackSide:
  44626. descriptor.frontFace = GPUFrontFace.CCW;
  44627. descriptor.cullMode = GPUCullMode.Front;
  44628. break;
  44629. case DoubleSide:
  44630. descriptor.frontFace = GPUFrontFace.CCW;
  44631. descriptor.cullMode = GPUCullMode.None;
  44632. break;
  44633. default:
  44634. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44635. break;
  44636. }
  44637. return descriptor;
  44638. }
  44639. _getColorWriteMask( material ) {
  44640. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44641. }
  44642. _getDepthCompare( material ) {
  44643. let depthCompare;
  44644. if ( material.depthTest === false ) {
  44645. depthCompare = GPUCompareFunction.Always;
  44646. } else {
  44647. const depthFunc = material.depthFunc;
  44648. switch ( depthFunc ) {
  44649. case NeverDepth:
  44650. depthCompare = GPUCompareFunction.Never;
  44651. break;
  44652. case AlwaysDepth:
  44653. depthCompare = GPUCompareFunction.Always;
  44654. break;
  44655. case LessDepth:
  44656. depthCompare = GPUCompareFunction.Less;
  44657. break;
  44658. case LessEqualDepth:
  44659. depthCompare = GPUCompareFunction.LessEqual;
  44660. break;
  44661. case EqualDepth:
  44662. depthCompare = GPUCompareFunction.Equal;
  44663. break;
  44664. case GreaterEqualDepth:
  44665. depthCompare = GPUCompareFunction.GreaterEqual;
  44666. break;
  44667. case GreaterDepth:
  44668. depthCompare = GPUCompareFunction.Greater;
  44669. break;
  44670. case NotEqualDepth:
  44671. depthCompare = GPUCompareFunction.NotEqual;
  44672. break;
  44673. default:
  44674. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44675. }
  44676. }
  44677. return depthCompare;
  44678. }
  44679. }
  44680. /*// debugger tools
  44681. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44682. //*/
  44683. //
  44684. class WebGPUBackend extends Backend {
  44685. constructor( parameters = {} ) {
  44686. super( parameters );
  44687. this.isWebGPUBackend = true;
  44688. // some parameters require default values other than "undefined"
  44689. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44690. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44691. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44692. this.device = null;
  44693. this.context = null;
  44694. this.colorBuffer = null;
  44695. this.defaultRenderPassdescriptor = null;
  44696. this.utils = new WebGPUUtils( this );
  44697. this.attributeUtils = new WebGPUAttributeUtils( this );
  44698. this.bindingUtils = new WebGPUBindingUtils( this );
  44699. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44700. this.textureUtils = new WebGPUTextureUtils( this );
  44701. this.occludedResolveCache = new Map();
  44702. }
  44703. async init( renderer ) {
  44704. await super.init( renderer );
  44705. //
  44706. const parameters = this.parameters;
  44707. // create the device if it is not passed with parameters
  44708. let device;
  44709. if ( parameters.device === undefined ) {
  44710. const adapterOptions = {
  44711. powerPreference: parameters.powerPreference
  44712. };
  44713. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44714. if ( adapter === null ) {
  44715. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44716. }
  44717. // feature support
  44718. const features = Object.values( GPUFeatureName );
  44719. const supportedFeatures = [];
  44720. for ( const name of features ) {
  44721. if ( adapter.features.has( name ) ) {
  44722. supportedFeatures.push( name );
  44723. }
  44724. }
  44725. const deviceDescriptor = {
  44726. requiredFeatures: supportedFeatures,
  44727. requiredLimits: parameters.requiredLimits
  44728. };
  44729. device = await adapter.requestDevice( deviceDescriptor );
  44730. } else {
  44731. device = parameters.device;
  44732. }
  44733. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44734. this.device = device;
  44735. this.context = context;
  44736. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44737. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44738. this.context.configure( {
  44739. device: this.device,
  44740. format: this.utils.getPreferredCanvasFormat(),
  44741. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44742. alphaMode: alphaMode
  44743. } );
  44744. this.updateSize();
  44745. }
  44746. get coordinateSystem() {
  44747. return WebGPUCoordinateSystem;
  44748. }
  44749. async getArrayBufferAsync( attribute ) {
  44750. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44751. }
  44752. getContext() {
  44753. return this.context;
  44754. }
  44755. _getDefaultRenderPassDescriptor() {
  44756. let descriptor = this.defaultRenderPassdescriptor;
  44757. if ( descriptor === null ) {
  44758. const renderer = this.renderer;
  44759. descriptor = {
  44760. colorAttachments: [ {
  44761. view: null
  44762. } ],
  44763. depthStencilAttachment: {
  44764. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44765. }
  44766. };
  44767. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44768. if ( this.renderer.samples > 0 ) {
  44769. colorAttachment.view = this.colorBuffer.createView();
  44770. } else {
  44771. colorAttachment.resolveTarget = undefined;
  44772. }
  44773. this.defaultRenderPassdescriptor = descriptor;
  44774. }
  44775. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44776. if ( this.renderer.samples > 0 ) {
  44777. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44778. } else {
  44779. colorAttachment.view = this.context.getCurrentTexture().createView();
  44780. }
  44781. return descriptor;
  44782. }
  44783. _getRenderPassDescriptor( renderContext ) {
  44784. const renderTarget = renderContext.renderTarget;
  44785. const renderTargetData = this.get( renderTarget );
  44786. let descriptors = renderTargetData.descriptors;
  44787. if ( descriptors === undefined ||
  44788. renderTargetData.width !== renderTarget.width ||
  44789. renderTargetData.height !== renderTarget.height ||
  44790. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44791. renderTargetData.samples !== renderTarget.samples
  44792. ) {
  44793. descriptors = {};
  44794. renderTargetData.descriptors = descriptors;
  44795. // dispose
  44796. const onDispose = () => {
  44797. renderTarget.removeEventListener( 'dispose', onDispose );
  44798. this.delete( renderTarget );
  44799. };
  44800. renderTarget.addEventListener( 'dispose', onDispose );
  44801. }
  44802. const cacheKey = renderContext.getCacheKey();
  44803. let descriptor = descriptors[ cacheKey ];
  44804. if ( descriptor === undefined ) {
  44805. const textures = renderContext.textures;
  44806. const colorAttachments = [];
  44807. for ( let i = 0; i < textures.length; i ++ ) {
  44808. const textureData = this.get( textures[ i ] );
  44809. const textureView = textureData.texture.createView( {
  44810. baseMipLevel: renderContext.activeMipmapLevel,
  44811. mipLevelCount: 1,
  44812. baseArrayLayer: renderContext.activeCubeFace,
  44813. dimension: GPUTextureViewDimension.TwoD
  44814. } );
  44815. let view, resolveTarget;
  44816. if ( textureData.msaaTexture !== undefined ) {
  44817. view = textureData.msaaTexture.createView();
  44818. resolveTarget = textureView;
  44819. } else {
  44820. view = textureView;
  44821. resolveTarget = undefined;
  44822. }
  44823. colorAttachments.push( {
  44824. view,
  44825. resolveTarget,
  44826. loadOp: GPULoadOp.Load,
  44827. storeOp: GPUStoreOp.Store
  44828. } );
  44829. }
  44830. const depthTextureData = this.get( renderContext.depthTexture );
  44831. const depthStencilAttachment = {
  44832. view: depthTextureData.texture.createView()
  44833. };
  44834. descriptor = {
  44835. colorAttachments,
  44836. depthStencilAttachment
  44837. };
  44838. descriptors[ cacheKey ] = descriptor;
  44839. renderTargetData.width = renderTarget.width;
  44840. renderTargetData.height = renderTarget.height;
  44841. renderTargetData.samples = renderTarget.samples;
  44842. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  44843. }
  44844. return descriptor;
  44845. }
  44846. beginRender( renderContext ) {
  44847. const renderContextData = this.get( renderContext );
  44848. const device = this.device;
  44849. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44850. let occlusionQuerySet;
  44851. if ( occlusionQueryCount > 0 ) {
  44852. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  44853. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  44854. // Get a reference to the array of objects with queries. The renderContextData property
  44855. // can be changed by another render pass before the buffer.mapAsyc() completes.
  44856. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  44857. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  44858. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44859. //
  44860. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  44861. renderContextData.occlusionQuerySet = occlusionQuerySet;
  44862. renderContextData.occlusionQueryIndex = 0;
  44863. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44864. renderContextData.lastOcclusionObject = null;
  44865. }
  44866. let descriptor;
  44867. if ( renderContext.textures === null ) {
  44868. descriptor = this._getDefaultRenderPassDescriptor();
  44869. } else {
  44870. descriptor = this._getRenderPassDescriptor( renderContext );
  44871. }
  44872. this.initTimestampQuery( renderContext, descriptor );
  44873. descriptor.occlusionQuerySet = occlusionQuerySet;
  44874. const depthStencilAttachment = descriptor.depthStencilAttachment;
  44875. if ( renderContext.textures !== null ) {
  44876. const colorAttachments = descriptor.colorAttachments;
  44877. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  44878. const colorAttachment = colorAttachments[ i ];
  44879. if ( renderContext.clearColor ) {
  44880. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  44881. colorAttachment.loadOp = GPULoadOp.Clear;
  44882. colorAttachment.storeOp = GPUStoreOp.Store;
  44883. } else {
  44884. colorAttachment.loadOp = GPULoadOp.Load;
  44885. colorAttachment.storeOp = GPUStoreOp.Store;
  44886. }
  44887. }
  44888. } else {
  44889. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44890. if ( renderContext.clearColor ) {
  44891. colorAttachment.clearValue = renderContext.clearColorValue;
  44892. colorAttachment.loadOp = GPULoadOp.Clear;
  44893. colorAttachment.storeOp = GPUStoreOp.Store;
  44894. } else {
  44895. colorAttachment.loadOp = GPULoadOp.Load;
  44896. colorAttachment.storeOp = GPUStoreOp.Store;
  44897. }
  44898. }
  44899. //
  44900. if ( renderContext.depth ) {
  44901. if ( renderContext.clearDepth ) {
  44902. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  44903. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44904. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44905. } else {
  44906. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44907. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44908. }
  44909. }
  44910. if ( renderContext.stencil ) {
  44911. if ( renderContext.clearStencil ) {
  44912. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  44913. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44914. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44915. } else {
  44916. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44917. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44918. }
  44919. }
  44920. //
  44921. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  44922. const currentPass = encoder.beginRenderPass( descriptor );
  44923. //
  44924. renderContextData.descriptor = descriptor;
  44925. renderContextData.encoder = encoder;
  44926. renderContextData.currentPass = currentPass;
  44927. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44928. renderContextData.renderBundles = [];
  44929. //
  44930. if ( renderContext.viewport ) {
  44931. this.updateViewport( renderContext );
  44932. }
  44933. if ( renderContext.scissor ) {
  44934. const { x, y, width, height } = renderContext.scissorValue;
  44935. currentPass.setScissorRect( x, y, width, height );
  44936. }
  44937. }
  44938. finishRender( renderContext ) {
  44939. const renderContextData = this.get( renderContext );
  44940. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44941. if ( renderContextData.renderBundles.length > 0 ) {
  44942. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  44943. }
  44944. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44945. renderContextData.currentPass.endOcclusionQuery();
  44946. }
  44947. renderContextData.currentPass.end();
  44948. if ( occlusionQueryCount > 0 ) {
  44949. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  44950. //
  44951. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  44952. if ( queryResolveBuffer === undefined ) {
  44953. queryResolveBuffer = this.device.createBuffer(
  44954. {
  44955. size: bufferSize,
  44956. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  44957. }
  44958. );
  44959. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  44960. }
  44961. //
  44962. const readBuffer = this.device.createBuffer(
  44963. {
  44964. size: bufferSize,
  44965. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44966. }
  44967. );
  44968. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  44969. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  44970. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  44971. renderContextData.occlusionQueryBuffer = readBuffer;
  44972. //
  44973. this.resolveOccludedAsync( renderContext );
  44974. }
  44975. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  44976. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  44977. //
  44978. if ( renderContext.textures !== null ) {
  44979. const textures = renderContext.textures;
  44980. for ( let i = 0; i < textures.length; i ++ ) {
  44981. const texture = textures[ i ];
  44982. if ( texture.generateMipmaps === true ) {
  44983. this.textureUtils.generateMipmaps( texture );
  44984. }
  44985. }
  44986. }
  44987. }
  44988. isOccluded( renderContext, object ) {
  44989. const renderContextData = this.get( renderContext );
  44990. return renderContextData.occluded && renderContextData.occluded.has( object );
  44991. }
  44992. async resolveOccludedAsync( renderContext ) {
  44993. const renderContextData = this.get( renderContext );
  44994. // handle occlusion query results
  44995. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  44996. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  44997. const occluded = new WeakSet();
  44998. renderContextData.currentOcclusionQueryObjects = null;
  44999. renderContextData.currentOcclusionQueryBuffer = null;
  45000. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  45001. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  45002. const results = new BigUint64Array( buffer );
  45003. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  45004. if ( results[ i ] !== BigInt( 0 ) ) {
  45005. occluded.add( currentOcclusionQueryObjects[ i ] );
  45006. }
  45007. }
  45008. currentOcclusionQueryBuffer.destroy();
  45009. renderContextData.occluded = occluded;
  45010. }
  45011. }
  45012. updateViewport( renderContext ) {
  45013. const { currentPass } = this.get( renderContext );
  45014. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  45015. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  45016. }
  45017. clear( color, depth, stencil, renderTargetData = null ) {
  45018. const device = this.device;
  45019. const renderer = this.renderer;
  45020. let colorAttachments = [];
  45021. let depthStencilAttachment;
  45022. let clearValue;
  45023. let supportsDepth;
  45024. let supportsStencil;
  45025. if ( color ) {
  45026. const clearColor = this.getClearColor();
  45027. if ( this.renderer.alpha === true ) {
  45028. // premultiply alpha
  45029. const a = clearColor.a;
  45030. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  45031. } else {
  45032. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  45033. }
  45034. }
  45035. if ( renderTargetData === null ) {
  45036. supportsDepth = renderer.depth;
  45037. supportsStencil = renderer.stencil;
  45038. const descriptor = this._getDefaultRenderPassDescriptor();
  45039. if ( color ) {
  45040. colorAttachments = descriptor.colorAttachments;
  45041. const colorAttachment = colorAttachments[ 0 ];
  45042. colorAttachment.clearValue = clearValue;
  45043. colorAttachment.loadOp = GPULoadOp.Clear;
  45044. colorAttachment.storeOp = GPUStoreOp.Store;
  45045. }
  45046. if ( supportsDepth || supportsStencil ) {
  45047. depthStencilAttachment = descriptor.depthStencilAttachment;
  45048. }
  45049. } else {
  45050. supportsDepth = renderTargetData.depth;
  45051. supportsStencil = renderTargetData.stencil;
  45052. if ( color ) {
  45053. for ( const texture of renderTargetData.textures ) {
  45054. const textureData = this.get( texture );
  45055. const textureView = textureData.texture.createView();
  45056. let view, resolveTarget;
  45057. if ( textureData.msaaTexture !== undefined ) {
  45058. view = textureData.msaaTexture.createView();
  45059. resolveTarget = textureView;
  45060. } else {
  45061. view = textureView;
  45062. resolveTarget = undefined;
  45063. }
  45064. colorAttachments.push( {
  45065. view,
  45066. resolveTarget,
  45067. clearValue,
  45068. loadOp: GPULoadOp.Clear,
  45069. storeOp: GPUStoreOp.Store
  45070. } );
  45071. }
  45072. }
  45073. if ( supportsDepth || supportsStencil ) {
  45074. const depthTextureData = this.get( renderTargetData.depthTexture );
  45075. depthStencilAttachment = {
  45076. view: depthTextureData.texture.createView()
  45077. };
  45078. }
  45079. }
  45080. //
  45081. if ( supportsDepth ) {
  45082. if ( depth ) {
  45083. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45084. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  45085. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45086. } else {
  45087. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45088. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45089. }
  45090. }
  45091. //
  45092. if ( supportsStencil ) {
  45093. if ( stencil ) {
  45094. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45095. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  45096. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45097. } else {
  45098. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45099. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45100. }
  45101. }
  45102. //
  45103. const encoder = device.createCommandEncoder( {} );
  45104. const currentPass = encoder.beginRenderPass( {
  45105. colorAttachments,
  45106. depthStencilAttachment
  45107. } );
  45108. currentPass.end();
  45109. device.queue.submit( [ encoder.finish() ] );
  45110. }
  45111. // compute
  45112. beginCompute( computeGroup ) {
  45113. const groupGPU = this.get( computeGroup );
  45114. const descriptor = {};
  45115. this.initTimestampQuery( computeGroup, descriptor );
  45116. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  45117. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  45118. }
  45119. compute( computeGroup, computeNode, bindings, pipeline ) {
  45120. const { passEncoderGPU } = this.get( computeGroup );
  45121. // pipeline
  45122. const pipelineGPU = this.get( pipeline ).pipeline;
  45123. passEncoderGPU.setPipeline( pipelineGPU );
  45124. // bind groups
  45125. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45126. const bindGroup = bindings[ i ];
  45127. const bindingsData = this.get( bindGroup );
  45128. passEncoderGPU.setBindGroup( i, bindingsData.group );
  45129. }
  45130. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  45131. const computeNodeData = this.get( computeNode );
  45132. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  45133. const { dispatchSize } = computeNodeData;
  45134. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  45135. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  45136. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  45137. } else {
  45138. dispatchSize.x = computeNode.dispatchCount;
  45139. }
  45140. passEncoderGPU.dispatchWorkgroups(
  45141. dispatchSize.x,
  45142. dispatchSize.y,
  45143. dispatchSize.z
  45144. );
  45145. }
  45146. finishCompute( computeGroup ) {
  45147. const groupData = this.get( computeGroup );
  45148. groupData.passEncoderGPU.end();
  45149. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  45150. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  45151. }
  45152. // render object
  45153. draw( renderObject, info ) {
  45154. const { object, material, geometry, context, pipeline, group } = renderObject;
  45155. const bindings = renderObject.getBindings();
  45156. const renderContextData = this.get( context );
  45157. const pipelineGPU = this.get( pipeline ).pipeline;
  45158. const currentSets = renderContextData.currentSets;
  45159. const passEncoderGPU = renderContextData.currentPass;
  45160. // pipeline
  45161. if ( currentSets.pipeline !== pipelineGPU ) {
  45162. passEncoderGPU.setPipeline( pipelineGPU );
  45163. currentSets.pipeline = pipelineGPU;
  45164. }
  45165. // bind groups
  45166. const currentBindingGroups = currentSets.bindingGroups;
  45167. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45168. const bindGroup = bindings[ i ];
  45169. const bindingsData = this.get( bindGroup );
  45170. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  45171. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  45172. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  45173. }
  45174. }
  45175. // attributes
  45176. const index = renderObject.getIndex();
  45177. const hasIndex = ( index !== null );
  45178. // index
  45179. if ( hasIndex === true ) {
  45180. if ( currentSets.index !== index ) {
  45181. const buffer = this.get( index ).buffer;
  45182. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45183. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  45184. currentSets.index = index;
  45185. }
  45186. }
  45187. // vertex buffers
  45188. const vertexBuffers = renderObject.getVertexBuffers();
  45189. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  45190. const vertexBuffer = vertexBuffers[ i ];
  45191. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  45192. const buffer = this.get( vertexBuffer ).buffer;
  45193. passEncoderGPU.setVertexBuffer( i, buffer );
  45194. currentSets.attributes[ i ] = vertexBuffer;
  45195. }
  45196. }
  45197. // occlusion queries - handle multiple consecutive draw calls for an object
  45198. if ( renderContextData.occlusionQuerySet !== undefined ) {
  45199. const lastObject = renderContextData.lastOcclusionObject;
  45200. if ( lastObject !== object ) {
  45201. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45202. passEncoderGPU.endOcclusionQuery();
  45203. renderContextData.occlusionQueryIndex ++;
  45204. }
  45205. if ( object.occlusionTest === true ) {
  45206. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  45207. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  45208. }
  45209. renderContextData.lastOcclusionObject = object;
  45210. }
  45211. }
  45212. // draw
  45213. const drawRange = renderObject.drawRange;
  45214. let rangeFactor = 1;
  45215. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  45216. rangeFactor = 2;
  45217. }
  45218. let firstVertex = drawRange.start * rangeFactor;
  45219. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  45220. if ( group !== null ) {
  45221. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  45222. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  45223. }
  45224. const instanceCount = this.getInstanceCount( renderObject );
  45225. if ( instanceCount === 0 ) return;
  45226. if ( object.isBatchedMesh === true ) {
  45227. const starts = object._multiDrawStarts;
  45228. const counts = object._multiDrawCounts;
  45229. const drawCount = object._multiDrawCount;
  45230. const drawInstances = object._multiDrawInstances;
  45231. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  45232. for ( let i = 0; i < drawCount; i ++ ) {
  45233. const count = drawInstances ? drawInstances[ i ] : 1;
  45234. const firstInstance = count > 1 ? 0 : i;
  45235. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  45236. }
  45237. } else if ( hasIndex === true ) {
  45238. const indexCount = index.count;
  45239. firstVertex = Math.max( firstVertex, 0 );
  45240. lastVertex = Math.min( lastVertex, indexCount );
  45241. const count = lastVertex - firstVertex;
  45242. if ( count < 0 || count === Infinity ) return;
  45243. passEncoderGPU.drawIndexed( count, instanceCount, firstVertex, 0, 0 );
  45244. info.update( object, indexCount, instanceCount );
  45245. } else {
  45246. const positionAttribute = geometry.attributes.position;
  45247. const vertexCount = positionAttribute.count;
  45248. firstVertex = Math.max( firstVertex, 0 );
  45249. lastVertex = Math.min( lastVertex, vertexCount );
  45250. const count = lastVertex - firstVertex;
  45251. if ( count < 0 || count === Infinity ) return;
  45252. passEncoderGPU.draw( count, instanceCount, firstVertex, 0 );
  45253. info.update( object, vertexCount, instanceCount );
  45254. }
  45255. }
  45256. // cache key
  45257. needsRenderUpdate( renderObject ) {
  45258. const data = this.get( renderObject );
  45259. const { object, material } = renderObject;
  45260. const utils = this.utils;
  45261. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  45262. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  45263. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45264. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45265. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  45266. let needsUpdate = false;
  45267. if ( data.material !== material || data.materialVersion !== material.version ||
  45268. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  45269. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  45270. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  45271. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  45272. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  45273. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  45274. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  45275. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  45276. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  45277. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  45278. data.primitiveTopology !== primitiveTopology ||
  45279. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  45280. ) {
  45281. data.material = material; data.materialVersion = material.version;
  45282. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  45283. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  45284. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  45285. data.colorWrite = material.colorWrite;
  45286. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  45287. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  45288. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  45289. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  45290. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  45291. data.sampleCount = sampleCount;
  45292. data.colorSpace = colorSpace;
  45293. data.colorFormat = colorFormat;
  45294. data.depthStencilFormat = depthStencilFormat;
  45295. data.primitiveTopology = primitiveTopology;
  45296. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  45297. needsUpdate = true;
  45298. }
  45299. return needsUpdate;
  45300. }
  45301. getRenderCacheKey( renderObject ) {
  45302. const { object, material } = renderObject;
  45303. const utils = this.utils;
  45304. const renderContext = renderObject.context;
  45305. return [
  45306. material.transparent, material.blending, material.premultipliedAlpha,
  45307. material.blendSrc, material.blendDst, material.blendEquation,
  45308. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  45309. material.colorWrite,
  45310. material.depthWrite, material.depthTest, material.depthFunc,
  45311. material.stencilWrite, material.stencilFunc,
  45312. material.stencilFail, material.stencilZFail, material.stencilZPass,
  45313. material.stencilFuncMask, material.stencilWriteMask,
  45314. material.side,
  45315. utils.getSampleCountRenderContext( renderContext ),
  45316. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  45317. utils.getPrimitiveTopology( object, material ),
  45318. renderObject.clippingContext.cacheKey
  45319. ].join();
  45320. }
  45321. // textures
  45322. createSampler( texture ) {
  45323. this.textureUtils.createSampler( texture );
  45324. }
  45325. destroySampler( texture ) {
  45326. this.textureUtils.destroySampler( texture );
  45327. }
  45328. createDefaultTexture( texture ) {
  45329. this.textureUtils.createDefaultTexture( texture );
  45330. }
  45331. createTexture( texture, options ) {
  45332. this.textureUtils.createTexture( texture, options );
  45333. }
  45334. updateTexture( texture, options ) {
  45335. this.textureUtils.updateTexture( texture, options );
  45336. }
  45337. generateMipmaps( texture ) {
  45338. this.textureUtils.generateMipmaps( texture );
  45339. }
  45340. destroyTexture( texture ) {
  45341. this.textureUtils.destroyTexture( texture );
  45342. }
  45343. copyTextureToBuffer( texture, x, y, width, height ) {
  45344. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  45345. }
  45346. initTimestampQuery( renderContext, descriptor ) {
  45347. if ( ! this.trackTimestamp ) return;
  45348. const renderContextData = this.get( renderContext );
  45349. if ( ! renderContextData.timeStampQuerySet ) {
  45350. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  45351. // beginning and one for the end of compute pass execution.
  45352. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  45353. const timestampWrites = {
  45354. querySet: timeStampQuerySet,
  45355. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  45356. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  45357. };
  45358. Object.assign( descriptor, {
  45359. timestampWrites,
  45360. } );
  45361. renderContextData.timeStampQuerySet = timeStampQuerySet;
  45362. }
  45363. }
  45364. // timestamp utils
  45365. prepareTimestampBuffer( renderContext, encoder ) {
  45366. if ( ! this.trackTimestamp ) return;
  45367. const renderContextData = this.get( renderContext );
  45368. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  45369. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  45370. renderContextData.currentTimestampQueryBuffers = {
  45371. resolveBuffer: this.device.createBuffer( {
  45372. label: 'timestamp resolve buffer',
  45373. size: size,
  45374. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  45375. } ),
  45376. resultBuffer: this.device.createBuffer( {
  45377. label: 'timestamp result buffer',
  45378. size: size,
  45379. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45380. } ),
  45381. isMappingPending: false,
  45382. };
  45383. }
  45384. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45385. if ( isMappingPending === true ) return;
  45386. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  45387. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  45388. }
  45389. async resolveTimestampAsync( renderContext, type = 'render' ) {
  45390. if ( ! this.trackTimestamp ) return;
  45391. const renderContextData = this.get( renderContext );
  45392. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  45393. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45394. if ( isMappingPending === true ) return;
  45395. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  45396. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  45397. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  45398. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  45399. this.renderer.info.updateTimestamp( type, duration );
  45400. resultBuffer.unmap();
  45401. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  45402. } );
  45403. }
  45404. // node builder
  45405. createNodeBuilder( object, renderer ) {
  45406. return new WGSLNodeBuilder( object, renderer );
  45407. }
  45408. // program
  45409. createProgram( program ) {
  45410. const programGPU = this.get( program );
  45411. programGPU.module = {
  45412. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  45413. entryPoint: 'main'
  45414. };
  45415. }
  45416. destroyProgram( program ) {
  45417. this.delete( program );
  45418. }
  45419. // pipelines
  45420. createRenderPipeline( renderObject, promises ) {
  45421. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  45422. }
  45423. createComputePipeline( computePipeline, bindings ) {
  45424. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  45425. }
  45426. beginBundle( renderContext ) {
  45427. const renderContextData = this.get( renderContext );
  45428. renderContextData._currentPass = renderContextData.currentPass;
  45429. renderContextData._currentSets = renderContextData.currentSets;
  45430. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45431. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  45432. }
  45433. finishBundle( renderContext, bundle ) {
  45434. const renderContextData = this.get( renderContext );
  45435. const bundleEncoder = renderContextData.currentPass;
  45436. const bundleGPU = bundleEncoder.finish();
  45437. this.get( bundle ).bundleGPU = bundleGPU;
  45438. // restore render pass state
  45439. renderContextData.currentSets = renderContextData._currentSets;
  45440. renderContextData.currentPass = renderContextData._currentPass;
  45441. }
  45442. addBundle( renderContext, bundle ) {
  45443. const renderContextData = this.get( renderContext );
  45444. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  45445. }
  45446. // bindings
  45447. createBindings( bindGroup ) {
  45448. this.bindingUtils.createBindings( bindGroup );
  45449. }
  45450. updateBindings( bindGroup ) {
  45451. this.bindingUtils.createBindings( bindGroup );
  45452. }
  45453. updateBinding( binding ) {
  45454. this.bindingUtils.updateBinding( binding );
  45455. }
  45456. // attributes
  45457. createIndexAttribute( attribute ) {
  45458. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45459. }
  45460. createAttribute( attribute ) {
  45461. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45462. }
  45463. createStorageAttribute( attribute ) {
  45464. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45465. }
  45466. updateAttribute( attribute ) {
  45467. this.attributeUtils.updateAttribute( attribute );
  45468. }
  45469. destroyAttribute( attribute ) {
  45470. this.attributeUtils.destroyAttribute( attribute );
  45471. }
  45472. // canvas
  45473. updateSize() {
  45474. this.colorBuffer = this.textureUtils.getColorBuffer();
  45475. this.defaultRenderPassdescriptor = null;
  45476. }
  45477. // utils public
  45478. getMaxAnisotropy() {
  45479. return 16;
  45480. }
  45481. hasFeature( name ) {
  45482. return this.device.features.has( name );
  45483. }
  45484. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45485. let dstX = 0;
  45486. let dstY = 0;
  45487. let srcX = 0;
  45488. let srcY = 0;
  45489. let srcWidth = srcTexture.image.width;
  45490. let srcHeight = srcTexture.image.height;
  45491. if ( srcRegion !== null ) {
  45492. srcX = srcRegion.x;
  45493. srcY = srcRegion.y;
  45494. srcWidth = srcRegion.width;
  45495. srcHeight = srcRegion.height;
  45496. }
  45497. if ( dstPosition !== null ) {
  45498. dstX = dstPosition.x;
  45499. dstY = dstPosition.y;
  45500. }
  45501. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45502. const sourceGPU = this.get( srcTexture ).texture;
  45503. const destinationGPU = this.get( dstTexture ).texture;
  45504. encoder.copyTextureToTexture(
  45505. {
  45506. texture: sourceGPU,
  45507. mipLevel: level,
  45508. origin: { x: srcX, y: srcY, z: 0 }
  45509. },
  45510. {
  45511. texture: destinationGPU,
  45512. mipLevel: level,
  45513. origin: { x: dstX, y: dstY, z: 0 }
  45514. },
  45515. [
  45516. srcWidth,
  45517. srcHeight
  45518. ]
  45519. );
  45520. this.device.queue.submit( [ encoder.finish() ] );
  45521. }
  45522. copyFramebufferToTexture( texture, renderContext ) {
  45523. const renderContextData = this.get( renderContext );
  45524. const { encoder, descriptor } = renderContextData;
  45525. let sourceGPU = null;
  45526. if ( renderContext.renderTarget ) {
  45527. if ( texture.isDepthTexture ) {
  45528. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45529. } else {
  45530. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45531. }
  45532. } else {
  45533. if ( texture.isDepthTexture ) {
  45534. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45535. } else {
  45536. sourceGPU = this.context.getCurrentTexture();
  45537. }
  45538. }
  45539. const destinationGPU = this.get( texture ).texture;
  45540. if ( sourceGPU.format !== destinationGPU.format ) {
  45541. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45542. return;
  45543. }
  45544. renderContextData.currentPass.end();
  45545. encoder.copyTextureToTexture(
  45546. {
  45547. texture: sourceGPU,
  45548. origin: { x: 0, y: 0, z: 0 }
  45549. },
  45550. {
  45551. texture: destinationGPU
  45552. },
  45553. [
  45554. texture.image.width,
  45555. texture.image.height
  45556. ]
  45557. );
  45558. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45559. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45560. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45561. }
  45562. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45563. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45564. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  45565. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45566. }
  45567. }
  45568. class IESSpotLight extends SpotLight {
  45569. constructor( color, intensity, distance, angle, penumbra, decay ) {
  45570. super( color, intensity, distance, angle, penumbra, decay );
  45571. this.iesMap = null;
  45572. }
  45573. copy( source, recursive ) {
  45574. super.copy( source, recursive );
  45575. this.iesMap = source.iesMap;
  45576. return this;
  45577. }
  45578. }
  45579. class StandardNodeLibrary extends NodeLibrary {
  45580. constructor() {
  45581. super();
  45582. this.addMaterial( MeshPhongNodeMaterial, MeshPhongMaterial );
  45583. this.addMaterial( MeshStandardNodeMaterial, MeshStandardMaterial );
  45584. this.addMaterial( MeshPhysicalNodeMaterial, MeshPhysicalMaterial );
  45585. this.addMaterial( MeshToonNodeMaterial, MeshToonMaterial );
  45586. this.addMaterial( MeshBasicNodeMaterial, MeshBasicMaterial );
  45587. this.addMaterial( MeshLambertNodeMaterial, MeshLambertMaterial );
  45588. this.addMaterial( MeshNormalNodeMaterial, MeshNormalMaterial );
  45589. this.addMaterial( MeshMatcapNodeMaterial, MeshMatcapMaterial );
  45590. this.addMaterial( LineBasicNodeMaterial, LineBasicMaterial );
  45591. this.addMaterial( LineDashedNodeMaterial, LineDashedMaterial );
  45592. this.addMaterial( PointsNodeMaterial, PointsMaterial );
  45593. this.addMaterial( SpriteNodeMaterial, SpriteMaterial );
  45594. this.addMaterial( ShadowNodeMaterial, ShadowMaterial );
  45595. this.addLight( PointLightNode, PointLight );
  45596. this.addLight( DirectionalLightNode, DirectionalLight );
  45597. this.addLight( RectAreaLightNode, RectAreaLight );
  45598. this.addLight( SpotLightNode, SpotLight );
  45599. this.addLight( AmbientLightNode, AmbientLight );
  45600. this.addLight( HemisphereLightNode, HemisphereLight );
  45601. this.addLight( LightProbeNode, LightProbe );
  45602. this.addLight( IESSpotLightNode, IESSpotLight );
  45603. this.addToneMapping( linearToneMapping, LinearToneMapping );
  45604. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  45605. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  45606. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  45607. this.addToneMapping( agxToneMapping, AgXToneMapping );
  45608. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  45609. this.addColorSpace( linearSRGBTosRGB, getColorSpaceMethod( LinearSRGBColorSpace, SRGBColorSpace ) );
  45610. this.addColorSpace( sRGBToLinearSRGB, getColorSpaceMethod( SRGBColorSpace, LinearSRGBColorSpace ) );
  45611. }
  45612. }
  45613. /*
  45614. const debugHandler = {
  45615. get: function ( target, name ) {
  45616. // Add |update
  45617. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  45618. return target[ name ];
  45619. }
  45620. };
  45621. */
  45622. class WebGPURenderer extends Renderer {
  45623. constructor( parameters = {} ) {
  45624. let BackendClass;
  45625. if ( parameters.forceWebGL ) {
  45626. BackendClass = WebGLBackend;
  45627. } else {
  45628. BackendClass = WebGPUBackend;
  45629. parameters.getFallback = () => {
  45630. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  45631. return new WebGLBackend( parameters );
  45632. };
  45633. }
  45634. const backend = new BackendClass( parameters );
  45635. //super( new Proxy( backend, debugHandler ) );
  45636. super( backend, parameters );
  45637. this.nodes.library = new StandardNodeLibrary();
  45638. this.isWebGPURenderer = true;
  45639. }
  45640. }
  45641. class BundleGroup extends Group {
  45642. constructor() {
  45643. super();
  45644. this.isBundleGroup = true;
  45645. this.type = 'BundleGroup';
  45646. }
  45647. }
  45648. const _material = /*@__PURE__*/ new NodeMaterial();
  45649. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  45650. class PostProcessing {
  45651. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  45652. this.renderer = renderer;
  45653. this.outputNode = outputNode;
  45654. this.outputColorTransform = true;
  45655. this.needsUpdate = true;
  45656. _material.name = 'PostProcessing';
  45657. }
  45658. render() {
  45659. this.update();
  45660. const renderer = this.renderer;
  45661. const toneMapping = renderer.toneMapping;
  45662. const outputColorSpace = renderer.outputColorSpace;
  45663. renderer.toneMapping = NoToneMapping;
  45664. renderer.outputColorSpace = LinearSRGBColorSpace;
  45665. //
  45666. _quadMesh.render( renderer );
  45667. //
  45668. renderer.toneMapping = toneMapping;
  45669. renderer.outputColorSpace = outputColorSpace;
  45670. }
  45671. update() {
  45672. if ( this.needsUpdate === true ) {
  45673. const renderer = this.renderer;
  45674. const toneMapping = renderer.toneMapping;
  45675. const outputColorSpace = renderer.outputColorSpace;
  45676. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  45677. _quadMesh.material.needsUpdate = true;
  45678. this.needsUpdate = false;
  45679. }
  45680. }
  45681. async renderAsync() {
  45682. this.update();
  45683. const renderer = this.renderer;
  45684. const toneMapping = renderer.toneMapping;
  45685. const outputColorSpace = renderer.outputColorSpace;
  45686. renderer.toneMapping = NoToneMapping;
  45687. renderer.outputColorSpace = LinearSRGBColorSpace;
  45688. //
  45689. await _quadMesh.renderAsync( renderer );
  45690. //
  45691. renderer.toneMapping = toneMapping;
  45692. renderer.outputColorSpace = outputColorSpace;
  45693. }
  45694. }
  45695. class StorageTexture extends Texture {
  45696. constructor( width = 1, height = 1 ) {
  45697. super();
  45698. this.image = { width, height };
  45699. this.magFilter = LinearFilter;
  45700. this.minFilter = LinearFilter;
  45701. this.isStorageTexture = true;
  45702. }
  45703. }
  45704. class StorageBufferAttribute extends BufferAttribute {
  45705. constructor( array, itemSize, typeClass = Float32Array ) {
  45706. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45707. super( array, itemSize );
  45708. this.isStorageBufferAttribute = true;
  45709. }
  45710. }
  45711. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  45712. constructor( array, itemSize, typeClass = Float32Array ) {
  45713. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45714. super( array, itemSize );
  45715. this.isStorageInstancedBufferAttribute = true;
  45716. }
  45717. }
  45718. class NodeLoader extends Loader {
  45719. constructor( manager ) {
  45720. super( manager );
  45721. this.textures = {};
  45722. this.nodes = {};
  45723. }
  45724. load( url, onLoad, onProgress, onError ) {
  45725. const loader = new FileLoader( this.manager );
  45726. loader.setPath( this.path );
  45727. loader.setRequestHeader( this.requestHeader );
  45728. loader.setWithCredentials( this.withCredentials );
  45729. loader.load( url, ( text ) => {
  45730. try {
  45731. onLoad( this.parse( JSON.parse( text ) ) );
  45732. } catch ( e ) {
  45733. if ( onError ) {
  45734. onError( e );
  45735. } else {
  45736. console.error( e );
  45737. }
  45738. this.manager.itemError( url );
  45739. }
  45740. }, onProgress, onError );
  45741. }
  45742. parseNodes( json ) {
  45743. const nodes = {};
  45744. if ( json !== undefined ) {
  45745. for ( const nodeJSON of json ) {
  45746. const { uuid, type } = nodeJSON;
  45747. nodes[ uuid ] = this.createNodeFromType( type );
  45748. nodes[ uuid ].uuid = uuid;
  45749. }
  45750. const meta = { nodes, textures: this.textures };
  45751. for ( const nodeJSON of json ) {
  45752. nodeJSON.meta = meta;
  45753. const node = nodes[ nodeJSON.uuid ];
  45754. node.deserialize( nodeJSON );
  45755. delete nodeJSON.meta;
  45756. }
  45757. }
  45758. return nodes;
  45759. }
  45760. parse( json ) {
  45761. const node = this.createNodeFromType( json.type );
  45762. node.uuid = json.uuid;
  45763. const nodes = this.parseNodes( json.nodes );
  45764. const meta = { nodes, textures: this.textures };
  45765. json.meta = meta;
  45766. node.deserialize( json );
  45767. delete json.meta;
  45768. return node;
  45769. }
  45770. setTextures( value ) {
  45771. this.textures = value;
  45772. return this;
  45773. }
  45774. setNodes( value ) {
  45775. this.nodes = value;
  45776. return this;
  45777. }
  45778. createNodeFromType( type ) {
  45779. if ( this.nodes[ type ] === undefined ) {
  45780. console.error( 'THREE.NodeLoader: Node type not found:', type );
  45781. return float();
  45782. }
  45783. return nodeObject( new this.nodes[ type ]() );
  45784. }
  45785. }
  45786. class NodeMaterialLoader extends MaterialLoader {
  45787. constructor( manager ) {
  45788. super( manager );
  45789. this.nodes = {};
  45790. this.nodeMaterials = {};
  45791. }
  45792. parse( json ) {
  45793. const material = super.parse( json );
  45794. const nodes = this.nodes;
  45795. const inputNodes = json.inputNodes;
  45796. for ( const property in inputNodes ) {
  45797. const uuid = inputNodes[ property ];
  45798. material[ property ] = nodes[ uuid ];
  45799. }
  45800. return material;
  45801. }
  45802. setNodes( value ) {
  45803. this.nodes = value;
  45804. return this;
  45805. }
  45806. setNodeMaterials( value ) {
  45807. this.nodeMaterials = value;
  45808. return this;
  45809. }
  45810. createMaterialFromType( type ) {
  45811. const materialClass = this.nodeMaterials[ type ];
  45812. if ( materialClass !== undefined ) {
  45813. return new materialClass();
  45814. }
  45815. return super.createMaterialFromType( type );
  45816. }
  45817. }
  45818. class NodeObjectLoader extends ObjectLoader {
  45819. constructor( manager ) {
  45820. super( manager );
  45821. this.nodes = {};
  45822. this.nodeMaterials = {};
  45823. this._nodesJSON = null;
  45824. }
  45825. setNodes( value ) {
  45826. this.nodes = value;
  45827. return this;
  45828. }
  45829. setNodeMaterials( value ) {
  45830. this.nodeMaterials = value;
  45831. return this;
  45832. }
  45833. parse( json, onLoad ) {
  45834. this._nodesJSON = json.nodes;
  45835. const data = super.parse( json, onLoad );
  45836. this._nodesJSON = null; // dispose
  45837. return data;
  45838. }
  45839. parseNodes( json, textures ) {
  45840. if ( json !== undefined ) {
  45841. const loader = new NodeLoader();
  45842. loader.setNodes( this.nodes );
  45843. loader.setTextures( textures );
  45844. return loader.parseNodes( json );
  45845. }
  45846. return {};
  45847. }
  45848. parseMaterials( json, textures ) {
  45849. const materials = {};
  45850. if ( json !== undefined ) {
  45851. const nodes = this.parseNodes( this._nodesJSON, textures );
  45852. const loader = new NodeMaterialLoader();
  45853. loader.setTextures( textures );
  45854. loader.setNodes( nodes );
  45855. loader.setNodeMaterials( this.nodeMaterials );
  45856. for ( let i = 0, l = json.length; i < l; i ++ ) {
  45857. const data = json[ i ];
  45858. materials[ data.uuid ] = loader.parse( data );
  45859. }
  45860. }
  45861. return materials;
  45862. }
  45863. }
  45864. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  45865. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  45866. revision: REVISION,
  45867. } } ) );
  45868. }
  45869. if ( typeof window !== 'undefined' ) {
  45870. if ( window.__THREE__ ) {
  45871. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  45872. } else {
  45873. window.__THREE__ = REVISION;
  45874. }
  45875. }
  45876. 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, LightNode, 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, 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, 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, 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, ViewportNode, 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, 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, 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, highPrecisionModelNormalMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightTargetDirection, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, 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, 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, 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, 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, storageObject, storageTexture, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, 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, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, xor };
粤ICP备19079148号