three.webgpu.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '167dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const 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$1 = {};
  974. function warnOnce( message ) {
  975. if ( message in _cache$1 ) return;
  976. _cache$1[ 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. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5513. customProgramCacheKey() {
  5514. return this.onBeforeCompile.toString();
  5515. }
  5516. setValues( values ) {
  5517. if ( values === undefined ) return;
  5518. for ( const key in values ) {
  5519. const newValue = values[ key ];
  5520. if ( newValue === undefined ) {
  5521. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5522. continue;
  5523. }
  5524. const currentValue = this[ key ];
  5525. if ( currentValue === undefined ) {
  5526. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5527. continue;
  5528. }
  5529. if ( currentValue && currentValue.isColor ) {
  5530. currentValue.set( newValue );
  5531. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5532. currentValue.copy( newValue );
  5533. } else {
  5534. this[ key ] = newValue;
  5535. }
  5536. }
  5537. }
  5538. toJSON( meta ) {
  5539. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5540. if ( isRootObject ) {
  5541. meta = {
  5542. textures: {},
  5543. images: {}
  5544. };
  5545. }
  5546. const data = {
  5547. metadata: {
  5548. version: 4.6,
  5549. type: 'Material',
  5550. generator: 'Material.toJSON'
  5551. }
  5552. };
  5553. // standard Material serialization
  5554. data.uuid = this.uuid;
  5555. data.type = this.type;
  5556. if ( this.name !== '' ) data.name = this.name;
  5557. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5558. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5559. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5560. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5561. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5562. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5563. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5564. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5565. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5566. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5567. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5568. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5569. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5570. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5571. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5572. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5573. }
  5574. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5575. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5576. }
  5577. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5578. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5579. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5580. }
  5581. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5582. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5583. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5584. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5585. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5586. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5587. }
  5588. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5589. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5590. }
  5591. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5592. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5593. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5594. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5595. }
  5596. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5597. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5598. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5599. if ( this.lightMap && this.lightMap.isTexture ) {
  5600. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5601. data.lightMapIntensity = this.lightMapIntensity;
  5602. }
  5603. if ( this.aoMap && this.aoMap.isTexture ) {
  5604. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5605. data.aoMapIntensity = this.aoMapIntensity;
  5606. }
  5607. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5608. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5609. data.bumpScale = this.bumpScale;
  5610. }
  5611. if ( this.normalMap && this.normalMap.isTexture ) {
  5612. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5613. data.normalMapType = this.normalMapType;
  5614. data.normalScale = this.normalScale.toArray();
  5615. }
  5616. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5617. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5618. data.displacementScale = this.displacementScale;
  5619. data.displacementBias = this.displacementBias;
  5620. }
  5621. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5622. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5623. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5624. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5625. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5626. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5627. if ( this.envMap && this.envMap.isTexture ) {
  5628. data.envMap = this.envMap.toJSON( meta ).uuid;
  5629. if ( this.combine !== undefined ) data.combine = this.combine;
  5630. }
  5631. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5632. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5633. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5634. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5635. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5636. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5637. }
  5638. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5639. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5640. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5641. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5642. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5643. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5644. if ( this.size !== undefined ) data.size = this.size;
  5645. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5646. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5647. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5648. if ( this.side !== FrontSide ) data.side = this.side;
  5649. if ( this.vertexColors === true ) data.vertexColors = true;
  5650. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5651. if ( this.transparent === true ) data.transparent = true;
  5652. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5653. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5654. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5655. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5656. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5657. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5658. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5659. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5660. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5661. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5662. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5663. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5664. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5665. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5666. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5667. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5668. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5669. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5670. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5671. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5672. // rotation (SpriteMaterial)
  5673. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5674. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5675. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5676. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5677. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5678. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5679. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5680. if ( this.scale !== undefined ) data.scale = this.scale;
  5681. if ( this.dithering === true ) data.dithering = true;
  5682. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5683. if ( this.alphaHash === true ) data.alphaHash = true;
  5684. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5685. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5686. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5687. if ( this.wireframe === true ) data.wireframe = true;
  5688. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5689. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5690. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5691. if ( this.flatShading === true ) data.flatShading = true;
  5692. if ( this.visible === false ) data.visible = false;
  5693. if ( this.toneMapped === false ) data.toneMapped = false;
  5694. if ( this.fog === false ) data.fog = false;
  5695. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5696. // TODO: Copied from Object3D.toJSON
  5697. function extractFromCache( cache ) {
  5698. const values = [];
  5699. for ( const key in cache ) {
  5700. const data = cache[ key ];
  5701. delete data.metadata;
  5702. values.push( data );
  5703. }
  5704. return values;
  5705. }
  5706. if ( isRootObject ) {
  5707. const textures = extractFromCache( meta.textures );
  5708. const images = extractFromCache( meta.images );
  5709. if ( textures.length > 0 ) data.textures = textures;
  5710. if ( images.length > 0 ) data.images = images;
  5711. }
  5712. return data;
  5713. }
  5714. clone() {
  5715. return new this.constructor().copy( this );
  5716. }
  5717. copy( source ) {
  5718. this.name = source.name;
  5719. this.blending = source.blending;
  5720. this.side = source.side;
  5721. this.vertexColors = source.vertexColors;
  5722. this.opacity = source.opacity;
  5723. this.transparent = source.transparent;
  5724. this.blendSrc = source.blendSrc;
  5725. this.blendDst = source.blendDst;
  5726. this.blendEquation = source.blendEquation;
  5727. this.blendSrcAlpha = source.blendSrcAlpha;
  5728. this.blendDstAlpha = source.blendDstAlpha;
  5729. this.blendEquationAlpha = source.blendEquationAlpha;
  5730. this.blendColor.copy( source.blendColor );
  5731. this.blendAlpha = source.blendAlpha;
  5732. this.depthFunc = source.depthFunc;
  5733. this.depthTest = source.depthTest;
  5734. this.depthWrite = source.depthWrite;
  5735. this.stencilWriteMask = source.stencilWriteMask;
  5736. this.stencilFunc = source.stencilFunc;
  5737. this.stencilRef = source.stencilRef;
  5738. this.stencilFuncMask = source.stencilFuncMask;
  5739. this.stencilFail = source.stencilFail;
  5740. this.stencilZFail = source.stencilZFail;
  5741. this.stencilZPass = source.stencilZPass;
  5742. this.stencilWrite = source.stencilWrite;
  5743. const srcPlanes = source.clippingPlanes;
  5744. let dstPlanes = null;
  5745. if ( srcPlanes !== null ) {
  5746. const n = srcPlanes.length;
  5747. dstPlanes = new Array( n );
  5748. for ( let i = 0; i !== n; ++ i ) {
  5749. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5750. }
  5751. }
  5752. this.clippingPlanes = dstPlanes;
  5753. this.clipIntersection = source.clipIntersection;
  5754. this.clipShadows = source.clipShadows;
  5755. this.shadowSide = source.shadowSide;
  5756. this.colorWrite = source.colorWrite;
  5757. this.precision = source.precision;
  5758. this.polygonOffset = source.polygonOffset;
  5759. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5760. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5761. this.dithering = source.dithering;
  5762. this.alphaTest = source.alphaTest;
  5763. this.alphaHash = source.alphaHash;
  5764. this.alphaToCoverage = source.alphaToCoverage;
  5765. this.premultipliedAlpha = source.premultipliedAlpha;
  5766. this.forceSinglePass = source.forceSinglePass;
  5767. this.visible = source.visible;
  5768. this.toneMapped = source.toneMapped;
  5769. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5770. return this;
  5771. }
  5772. dispose() {
  5773. this.dispatchEvent( { type: 'dispose' } );
  5774. }
  5775. set needsUpdate( value ) {
  5776. if ( value === true ) this.version ++;
  5777. }
  5778. onBuild( /* shaderobject, renderer */ ) {
  5779. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5780. }
  5781. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {
  5782. console.warn( 'Material: onBeforeRender() has been removed.' ); // @deprecated, r166
  5783. }
  5784. }
  5785. class MeshBasicMaterial extends Material {
  5786. constructor( parameters ) {
  5787. super();
  5788. this.isMeshBasicMaterial = true;
  5789. this.type = 'MeshBasicMaterial';
  5790. this.color = new Color( 0xffffff ); // emissive
  5791. this.map = null;
  5792. this.lightMap = null;
  5793. this.lightMapIntensity = 1.0;
  5794. this.aoMap = null;
  5795. this.aoMapIntensity = 1.0;
  5796. this.specularMap = null;
  5797. this.alphaMap = null;
  5798. this.envMap = null;
  5799. this.envMapRotation = new Euler();
  5800. this.combine = MultiplyOperation;
  5801. this.reflectivity = 1;
  5802. this.refractionRatio = 0.98;
  5803. this.wireframe = false;
  5804. this.wireframeLinewidth = 1;
  5805. this.wireframeLinecap = 'round';
  5806. this.wireframeLinejoin = 'round';
  5807. this.fog = true;
  5808. this.setValues( parameters );
  5809. }
  5810. copy( source ) {
  5811. super.copy( source );
  5812. this.color.copy( source.color );
  5813. this.map = source.map;
  5814. this.lightMap = source.lightMap;
  5815. this.lightMapIntensity = source.lightMapIntensity;
  5816. this.aoMap = source.aoMap;
  5817. this.aoMapIntensity = source.aoMapIntensity;
  5818. this.specularMap = source.specularMap;
  5819. this.alphaMap = source.alphaMap;
  5820. this.envMap = source.envMap;
  5821. this.envMapRotation.copy( source.envMapRotation );
  5822. this.combine = source.combine;
  5823. this.reflectivity = source.reflectivity;
  5824. this.refractionRatio = source.refractionRatio;
  5825. this.wireframe = source.wireframe;
  5826. this.wireframeLinewidth = source.wireframeLinewidth;
  5827. this.wireframeLinecap = source.wireframeLinecap;
  5828. this.wireframeLinejoin = source.wireframeLinejoin;
  5829. this.fog = source.fog;
  5830. return this;
  5831. }
  5832. }
  5833. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5834. const _tables = /*@__PURE__*/ _generateTables();
  5835. function _generateTables() {
  5836. // float32 to float16 helpers
  5837. const buffer = new ArrayBuffer( 4 );
  5838. const floatView = new Float32Array( buffer );
  5839. const uint32View = new Uint32Array( buffer );
  5840. const baseTable = new Uint32Array( 512 );
  5841. const shiftTable = new Uint32Array( 512 );
  5842. for ( let i = 0; i < 256; ++ i ) {
  5843. const e = i - 127;
  5844. // very small number (0, -0)
  5845. if ( e < - 27 ) {
  5846. baseTable[ i ] = 0x0000;
  5847. baseTable[ i | 0x100 ] = 0x8000;
  5848. shiftTable[ i ] = 24;
  5849. shiftTable[ i | 0x100 ] = 24;
  5850. // small number (denorm)
  5851. } else if ( e < - 14 ) {
  5852. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5853. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5854. shiftTable[ i ] = - e - 1;
  5855. shiftTable[ i | 0x100 ] = - e - 1;
  5856. // normal number
  5857. } else if ( e <= 15 ) {
  5858. baseTable[ i ] = ( e + 15 ) << 10;
  5859. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5860. shiftTable[ i ] = 13;
  5861. shiftTable[ i | 0x100 ] = 13;
  5862. // large number (Infinity, -Infinity)
  5863. } else if ( e < 128 ) {
  5864. baseTable[ i ] = 0x7c00;
  5865. baseTable[ i | 0x100 ] = 0xfc00;
  5866. shiftTable[ i ] = 24;
  5867. shiftTable[ i | 0x100 ] = 24;
  5868. // stay (NaN, Infinity, -Infinity)
  5869. } else {
  5870. baseTable[ i ] = 0x7c00;
  5871. baseTable[ i | 0x100 ] = 0xfc00;
  5872. shiftTable[ i ] = 13;
  5873. shiftTable[ i | 0x100 ] = 13;
  5874. }
  5875. }
  5876. // float16 to float32 helpers
  5877. const mantissaTable = new Uint32Array( 2048 );
  5878. const exponentTable = new Uint32Array( 64 );
  5879. const offsetTable = new Uint32Array( 64 );
  5880. for ( let i = 1; i < 1024; ++ i ) {
  5881. let m = i << 13; // zero pad mantissa bits
  5882. let e = 0; // zero exponent
  5883. // normalized
  5884. while ( ( m & 0x00800000 ) === 0 ) {
  5885. m <<= 1;
  5886. e -= 0x00800000; // decrement exponent
  5887. }
  5888. m &= ~ 0x00800000; // clear leading 1 bit
  5889. e += 0x38800000; // adjust bias
  5890. mantissaTable[ i ] = m | e;
  5891. }
  5892. for ( let i = 1024; i < 2048; ++ i ) {
  5893. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5894. }
  5895. for ( let i = 1; i < 31; ++ i ) {
  5896. exponentTable[ i ] = i << 23;
  5897. }
  5898. exponentTable[ 31 ] = 0x47800000;
  5899. exponentTable[ 32 ] = 0x80000000;
  5900. for ( let i = 33; i < 63; ++ i ) {
  5901. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5902. }
  5903. exponentTable[ 63 ] = 0xc7800000;
  5904. for ( let i = 1; i < 64; ++ i ) {
  5905. if ( i !== 32 ) {
  5906. offsetTable[ i ] = 1024;
  5907. }
  5908. }
  5909. return {
  5910. floatView: floatView,
  5911. uint32View: uint32View,
  5912. baseTable: baseTable,
  5913. shiftTable: shiftTable,
  5914. mantissaTable: mantissaTable,
  5915. exponentTable: exponentTable,
  5916. offsetTable: offsetTable
  5917. };
  5918. }
  5919. // float32 to float16
  5920. function toHalfFloat( val ) {
  5921. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5922. val = clamp$1( val, - 65504, 65504 );
  5923. _tables.floatView[ 0 ] = val;
  5924. const f = _tables.uint32View[ 0 ];
  5925. const e = ( f >> 23 ) & 0x1ff;
  5926. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5927. }
  5928. // float16 to float32
  5929. function fromHalfFloat( val ) {
  5930. const m = val >> 10;
  5931. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5932. return _tables.floatView[ 0 ];
  5933. }
  5934. const DataUtils = {
  5935. toHalfFloat: toHalfFloat,
  5936. fromHalfFloat: fromHalfFloat,
  5937. };
  5938. const _vector$9 = /*@__PURE__*/ new Vector3();
  5939. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5940. class BufferAttribute {
  5941. constructor( array, itemSize, normalized = false ) {
  5942. if ( Array.isArray( array ) ) {
  5943. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5944. }
  5945. this.isBufferAttribute = true;
  5946. this.name = '';
  5947. this.array = array;
  5948. this.itemSize = itemSize;
  5949. this.count = array !== undefined ? array.length / itemSize : 0;
  5950. this.normalized = normalized;
  5951. this.usage = StaticDrawUsage;
  5952. this._updateRange = { offset: 0, count: - 1 };
  5953. this.updateRanges = [];
  5954. this.gpuType = FloatType;
  5955. this.version = 0;
  5956. }
  5957. onUploadCallback() {}
  5958. set needsUpdate( value ) {
  5959. if ( value === true ) this.version ++;
  5960. }
  5961. get updateRange() {
  5962. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5963. return this._updateRange;
  5964. }
  5965. setUsage( value ) {
  5966. this.usage = value;
  5967. return this;
  5968. }
  5969. addUpdateRange( start, count ) {
  5970. this.updateRanges.push( { start, count } );
  5971. }
  5972. clearUpdateRanges() {
  5973. this.updateRanges.length = 0;
  5974. }
  5975. copy( source ) {
  5976. this.name = source.name;
  5977. this.array = new source.array.constructor( source.array );
  5978. this.itemSize = source.itemSize;
  5979. this.count = source.count;
  5980. this.normalized = source.normalized;
  5981. this.usage = source.usage;
  5982. this.gpuType = source.gpuType;
  5983. return this;
  5984. }
  5985. copyAt( index1, attribute, index2 ) {
  5986. index1 *= this.itemSize;
  5987. index2 *= attribute.itemSize;
  5988. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5989. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5990. }
  5991. return this;
  5992. }
  5993. copyArray( array ) {
  5994. this.array.set( array );
  5995. return this;
  5996. }
  5997. applyMatrix3( m ) {
  5998. if ( this.itemSize === 2 ) {
  5999. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6000. _vector2$1.fromBufferAttribute( this, i );
  6001. _vector2$1.applyMatrix3( m );
  6002. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6003. }
  6004. } else if ( this.itemSize === 3 ) {
  6005. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6006. _vector$9.fromBufferAttribute( this, i );
  6007. _vector$9.applyMatrix3( m );
  6008. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6009. }
  6010. }
  6011. return this;
  6012. }
  6013. applyMatrix4( m ) {
  6014. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6015. _vector$9.fromBufferAttribute( this, i );
  6016. _vector$9.applyMatrix4( m );
  6017. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6018. }
  6019. return this;
  6020. }
  6021. applyNormalMatrix( m ) {
  6022. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6023. _vector$9.fromBufferAttribute( this, i );
  6024. _vector$9.applyNormalMatrix( m );
  6025. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6026. }
  6027. return this;
  6028. }
  6029. transformDirection( m ) {
  6030. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6031. _vector$9.fromBufferAttribute( this, i );
  6032. _vector$9.transformDirection( m );
  6033. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6034. }
  6035. return this;
  6036. }
  6037. set( value, offset = 0 ) {
  6038. // Matching BufferAttribute constructor, do not normalize the array.
  6039. this.array.set( value, offset );
  6040. return this;
  6041. }
  6042. getComponent( index, component ) {
  6043. let value = this.array[ index * this.itemSize + component ];
  6044. if ( this.normalized ) value = denormalize( value, this.array );
  6045. return value;
  6046. }
  6047. setComponent( index, component, value ) {
  6048. if ( this.normalized ) value = normalize$1( value, this.array );
  6049. this.array[ index * this.itemSize + component ] = value;
  6050. return this;
  6051. }
  6052. getX( index ) {
  6053. let x = this.array[ index * this.itemSize ];
  6054. if ( this.normalized ) x = denormalize( x, this.array );
  6055. return x;
  6056. }
  6057. setX( index, x ) {
  6058. if ( this.normalized ) x = normalize$1( x, this.array );
  6059. this.array[ index * this.itemSize ] = x;
  6060. return this;
  6061. }
  6062. getY( index ) {
  6063. let y = this.array[ index * this.itemSize + 1 ];
  6064. if ( this.normalized ) y = denormalize( y, this.array );
  6065. return y;
  6066. }
  6067. setY( index, y ) {
  6068. if ( this.normalized ) y = normalize$1( y, this.array );
  6069. this.array[ index * this.itemSize + 1 ] = y;
  6070. return this;
  6071. }
  6072. getZ( index ) {
  6073. let z = this.array[ index * this.itemSize + 2 ];
  6074. if ( this.normalized ) z = denormalize( z, this.array );
  6075. return z;
  6076. }
  6077. setZ( index, z ) {
  6078. if ( this.normalized ) z = normalize$1( z, this.array );
  6079. this.array[ index * this.itemSize + 2 ] = z;
  6080. return this;
  6081. }
  6082. getW( index ) {
  6083. let w = this.array[ index * this.itemSize + 3 ];
  6084. if ( this.normalized ) w = denormalize( w, this.array );
  6085. return w;
  6086. }
  6087. setW( index, w ) {
  6088. if ( this.normalized ) w = normalize$1( w, this.array );
  6089. this.array[ index * this.itemSize + 3 ] = w;
  6090. return this;
  6091. }
  6092. setXY( index, x, y ) {
  6093. index *= this.itemSize;
  6094. if ( this.normalized ) {
  6095. x = normalize$1( x, this.array );
  6096. y = normalize$1( y, this.array );
  6097. }
  6098. this.array[ index + 0 ] = x;
  6099. this.array[ index + 1 ] = y;
  6100. return this;
  6101. }
  6102. setXYZ( index, x, y, z ) {
  6103. index *= this.itemSize;
  6104. if ( this.normalized ) {
  6105. x = normalize$1( x, this.array );
  6106. y = normalize$1( y, this.array );
  6107. z = normalize$1( z, this.array );
  6108. }
  6109. this.array[ index + 0 ] = x;
  6110. this.array[ index + 1 ] = y;
  6111. this.array[ index + 2 ] = z;
  6112. return this;
  6113. }
  6114. setXYZW( index, x, y, z, w ) {
  6115. index *= this.itemSize;
  6116. if ( this.normalized ) {
  6117. x = normalize$1( x, this.array );
  6118. y = normalize$1( y, this.array );
  6119. z = normalize$1( z, this.array );
  6120. w = normalize$1( w, this.array );
  6121. }
  6122. this.array[ index + 0 ] = x;
  6123. this.array[ index + 1 ] = y;
  6124. this.array[ index + 2 ] = z;
  6125. this.array[ index + 3 ] = w;
  6126. return this;
  6127. }
  6128. onUpload( callback ) {
  6129. this.onUploadCallback = callback;
  6130. return this;
  6131. }
  6132. clone() {
  6133. return new this.constructor( this.array, this.itemSize ).copy( this );
  6134. }
  6135. toJSON() {
  6136. const data = {
  6137. itemSize: this.itemSize,
  6138. type: this.array.constructor.name,
  6139. array: Array.from( this.array ),
  6140. normalized: this.normalized
  6141. };
  6142. if ( this.name !== '' ) data.name = this.name;
  6143. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6144. return data;
  6145. }
  6146. }
  6147. //
  6148. class Int8BufferAttribute extends BufferAttribute {
  6149. constructor( array, itemSize, normalized ) {
  6150. super( new Int8Array( array ), itemSize, normalized );
  6151. }
  6152. }
  6153. class Uint8BufferAttribute extends BufferAttribute {
  6154. constructor( array, itemSize, normalized ) {
  6155. super( new Uint8Array( array ), itemSize, normalized );
  6156. }
  6157. }
  6158. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6159. constructor( array, itemSize, normalized ) {
  6160. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6161. }
  6162. }
  6163. class Int16BufferAttribute extends BufferAttribute {
  6164. constructor( array, itemSize, normalized ) {
  6165. super( new Int16Array( array ), itemSize, normalized );
  6166. }
  6167. }
  6168. class Uint16BufferAttribute extends BufferAttribute {
  6169. constructor( array, itemSize, normalized ) {
  6170. super( new Uint16Array( array ), itemSize, normalized );
  6171. }
  6172. }
  6173. class Int32BufferAttribute extends BufferAttribute {
  6174. constructor( array, itemSize, normalized ) {
  6175. super( new Int32Array( array ), itemSize, normalized );
  6176. }
  6177. }
  6178. class Uint32BufferAttribute extends BufferAttribute {
  6179. constructor( array, itemSize, normalized ) {
  6180. super( new Uint32Array( array ), itemSize, normalized );
  6181. }
  6182. }
  6183. class Float16BufferAttribute extends BufferAttribute {
  6184. constructor( array, itemSize, normalized ) {
  6185. super( new Uint16Array( array ), itemSize, normalized );
  6186. this.isFloat16BufferAttribute = true;
  6187. }
  6188. getX( index ) {
  6189. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6190. if ( this.normalized ) x = denormalize( x, this.array );
  6191. return x;
  6192. }
  6193. setX( index, x ) {
  6194. if ( this.normalized ) x = normalize$1( x, this.array );
  6195. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6196. return this;
  6197. }
  6198. getY( index ) {
  6199. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6200. if ( this.normalized ) y = denormalize( y, this.array );
  6201. return y;
  6202. }
  6203. setY( index, y ) {
  6204. if ( this.normalized ) y = normalize$1( y, this.array );
  6205. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6206. return this;
  6207. }
  6208. getZ( index ) {
  6209. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6210. if ( this.normalized ) z = denormalize( z, this.array );
  6211. return z;
  6212. }
  6213. setZ( index, z ) {
  6214. if ( this.normalized ) z = normalize$1( z, this.array );
  6215. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6216. return this;
  6217. }
  6218. getW( index ) {
  6219. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6220. if ( this.normalized ) w = denormalize( w, this.array );
  6221. return w;
  6222. }
  6223. setW( index, w ) {
  6224. if ( this.normalized ) w = normalize$1( w, this.array );
  6225. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6226. return this;
  6227. }
  6228. setXY( index, x, y ) {
  6229. index *= this.itemSize;
  6230. if ( this.normalized ) {
  6231. x = normalize$1( x, this.array );
  6232. y = normalize$1( y, this.array );
  6233. }
  6234. this.array[ index + 0 ] = toHalfFloat( x );
  6235. this.array[ index + 1 ] = toHalfFloat( y );
  6236. return this;
  6237. }
  6238. setXYZ( index, x, y, z ) {
  6239. index *= this.itemSize;
  6240. if ( this.normalized ) {
  6241. x = normalize$1( x, this.array );
  6242. y = normalize$1( y, this.array );
  6243. z = normalize$1( z, this.array );
  6244. }
  6245. this.array[ index + 0 ] = toHalfFloat( x );
  6246. this.array[ index + 1 ] = toHalfFloat( y );
  6247. this.array[ index + 2 ] = toHalfFloat( z );
  6248. return this;
  6249. }
  6250. setXYZW( index, x, y, z, w ) {
  6251. index *= this.itemSize;
  6252. if ( this.normalized ) {
  6253. x = normalize$1( x, this.array );
  6254. y = normalize$1( y, this.array );
  6255. z = normalize$1( z, this.array );
  6256. w = normalize$1( w, this.array );
  6257. }
  6258. this.array[ index + 0 ] = toHalfFloat( x );
  6259. this.array[ index + 1 ] = toHalfFloat( y );
  6260. this.array[ index + 2 ] = toHalfFloat( z );
  6261. this.array[ index + 3 ] = toHalfFloat( w );
  6262. return this;
  6263. }
  6264. }
  6265. class Float32BufferAttribute extends BufferAttribute {
  6266. constructor( array, itemSize, normalized ) {
  6267. super( new Float32Array( array ), itemSize, normalized );
  6268. }
  6269. }
  6270. let _id$9 = 0;
  6271. const _m1 = /*@__PURE__*/ new Matrix4();
  6272. const _obj = /*@__PURE__*/ new Object3D();
  6273. const _offset = /*@__PURE__*/ new Vector3();
  6274. const _box$2 = /*@__PURE__*/ new Box3();
  6275. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6276. const _vector$8 = /*@__PURE__*/ new Vector3();
  6277. class BufferGeometry extends EventDispatcher {
  6278. constructor() {
  6279. super();
  6280. this.isBufferGeometry = true;
  6281. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6282. this.uuid = generateUUID();
  6283. this.name = '';
  6284. this.type = 'BufferGeometry';
  6285. this.index = null;
  6286. this.attributes = {};
  6287. this.morphAttributes = {};
  6288. this.morphTargetsRelative = false;
  6289. this.groups = [];
  6290. this.boundingBox = null;
  6291. this.boundingSphere = null;
  6292. this.drawRange = { start: 0, count: Infinity };
  6293. this.userData = {};
  6294. }
  6295. getIndex() {
  6296. return this.index;
  6297. }
  6298. setIndex( index ) {
  6299. if ( Array.isArray( index ) ) {
  6300. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6301. } else {
  6302. this.index = index;
  6303. }
  6304. return this;
  6305. }
  6306. getAttribute( name ) {
  6307. return this.attributes[ name ];
  6308. }
  6309. setAttribute( name, attribute ) {
  6310. this.attributes[ name ] = attribute;
  6311. return this;
  6312. }
  6313. deleteAttribute( name ) {
  6314. delete this.attributes[ name ];
  6315. return this;
  6316. }
  6317. hasAttribute( name ) {
  6318. return this.attributes[ name ] !== undefined;
  6319. }
  6320. addGroup( start, count, materialIndex = 0 ) {
  6321. this.groups.push( {
  6322. start: start,
  6323. count: count,
  6324. materialIndex: materialIndex
  6325. } );
  6326. }
  6327. clearGroups() {
  6328. this.groups = [];
  6329. }
  6330. setDrawRange( start, count ) {
  6331. this.drawRange.start = start;
  6332. this.drawRange.count = count;
  6333. }
  6334. applyMatrix4( matrix ) {
  6335. const position = this.attributes.position;
  6336. if ( position !== undefined ) {
  6337. position.applyMatrix4( matrix );
  6338. position.needsUpdate = true;
  6339. }
  6340. const normal = this.attributes.normal;
  6341. if ( normal !== undefined ) {
  6342. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6343. normal.applyNormalMatrix( normalMatrix );
  6344. normal.needsUpdate = true;
  6345. }
  6346. const tangent = this.attributes.tangent;
  6347. if ( tangent !== undefined ) {
  6348. tangent.transformDirection( matrix );
  6349. tangent.needsUpdate = true;
  6350. }
  6351. if ( this.boundingBox !== null ) {
  6352. this.computeBoundingBox();
  6353. }
  6354. if ( this.boundingSphere !== null ) {
  6355. this.computeBoundingSphere();
  6356. }
  6357. return this;
  6358. }
  6359. applyQuaternion( q ) {
  6360. _m1.makeRotationFromQuaternion( q );
  6361. this.applyMatrix4( _m1 );
  6362. return this;
  6363. }
  6364. rotateX( angle ) {
  6365. // rotate geometry around world x-axis
  6366. _m1.makeRotationX( angle );
  6367. this.applyMatrix4( _m1 );
  6368. return this;
  6369. }
  6370. rotateY( angle ) {
  6371. // rotate geometry around world y-axis
  6372. _m1.makeRotationY( angle );
  6373. this.applyMatrix4( _m1 );
  6374. return this;
  6375. }
  6376. rotateZ( angle ) {
  6377. // rotate geometry around world z-axis
  6378. _m1.makeRotationZ( angle );
  6379. this.applyMatrix4( _m1 );
  6380. return this;
  6381. }
  6382. translate( x, y, z ) {
  6383. // translate geometry
  6384. _m1.makeTranslation( x, y, z );
  6385. this.applyMatrix4( _m1 );
  6386. return this;
  6387. }
  6388. scale( x, y, z ) {
  6389. // scale geometry
  6390. _m1.makeScale( x, y, z );
  6391. this.applyMatrix4( _m1 );
  6392. return this;
  6393. }
  6394. lookAt( vector ) {
  6395. _obj.lookAt( vector );
  6396. _obj.updateMatrix();
  6397. this.applyMatrix4( _obj.matrix );
  6398. return this;
  6399. }
  6400. center() {
  6401. this.computeBoundingBox();
  6402. this.boundingBox.getCenter( _offset ).negate();
  6403. this.translate( _offset.x, _offset.y, _offset.z );
  6404. return this;
  6405. }
  6406. setFromPoints( points ) {
  6407. const position = [];
  6408. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6409. const point = points[ i ];
  6410. position.push( point.x, point.y, point.z || 0 );
  6411. }
  6412. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6413. return this;
  6414. }
  6415. computeBoundingBox() {
  6416. if ( this.boundingBox === null ) {
  6417. this.boundingBox = new Box3();
  6418. }
  6419. const position = this.attributes.position;
  6420. const morphAttributesPosition = this.morphAttributes.position;
  6421. if ( position && position.isGLBufferAttribute ) {
  6422. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6423. this.boundingBox.set(
  6424. new Vector3( - Infinity, - Infinity, - Infinity ),
  6425. new Vector3( + Infinity, + Infinity, + Infinity )
  6426. );
  6427. return;
  6428. }
  6429. if ( position !== undefined ) {
  6430. this.boundingBox.setFromBufferAttribute( position );
  6431. // process morph attributes if present
  6432. if ( morphAttributesPosition ) {
  6433. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6434. const morphAttribute = morphAttributesPosition[ i ];
  6435. _box$2.setFromBufferAttribute( morphAttribute );
  6436. if ( this.morphTargetsRelative ) {
  6437. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6438. this.boundingBox.expandByPoint( _vector$8 );
  6439. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6440. this.boundingBox.expandByPoint( _vector$8 );
  6441. } else {
  6442. this.boundingBox.expandByPoint( _box$2.min );
  6443. this.boundingBox.expandByPoint( _box$2.max );
  6444. }
  6445. }
  6446. }
  6447. } else {
  6448. this.boundingBox.makeEmpty();
  6449. }
  6450. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6451. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6452. }
  6453. }
  6454. computeBoundingSphere() {
  6455. if ( this.boundingSphere === null ) {
  6456. this.boundingSphere = new Sphere();
  6457. }
  6458. const position = this.attributes.position;
  6459. const morphAttributesPosition = this.morphAttributes.position;
  6460. if ( position && position.isGLBufferAttribute ) {
  6461. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6462. this.boundingSphere.set( new Vector3(), Infinity );
  6463. return;
  6464. }
  6465. if ( position ) {
  6466. // first, find the center of the bounding sphere
  6467. const center = this.boundingSphere.center;
  6468. _box$2.setFromBufferAttribute( position );
  6469. // process morph attributes if present
  6470. if ( morphAttributesPosition ) {
  6471. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6472. const morphAttribute = morphAttributesPosition[ i ];
  6473. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6474. if ( this.morphTargetsRelative ) {
  6475. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6476. _box$2.expandByPoint( _vector$8 );
  6477. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6478. _box$2.expandByPoint( _vector$8 );
  6479. } else {
  6480. _box$2.expandByPoint( _boxMorphTargets.min );
  6481. _box$2.expandByPoint( _boxMorphTargets.max );
  6482. }
  6483. }
  6484. }
  6485. _box$2.getCenter( center );
  6486. // second, try to find a boundingSphere with a radius smaller than the
  6487. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6488. let maxRadiusSq = 0;
  6489. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6490. _vector$8.fromBufferAttribute( position, i );
  6491. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6492. }
  6493. // process morph attributes if present
  6494. if ( morphAttributesPosition ) {
  6495. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6496. const morphAttribute = morphAttributesPosition[ i ];
  6497. const morphTargetsRelative = this.morphTargetsRelative;
  6498. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6499. _vector$8.fromBufferAttribute( morphAttribute, j );
  6500. if ( morphTargetsRelative ) {
  6501. _offset.fromBufferAttribute( position, j );
  6502. _vector$8.add( _offset );
  6503. }
  6504. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6505. }
  6506. }
  6507. }
  6508. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6509. if ( isNaN( this.boundingSphere.radius ) ) {
  6510. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6511. }
  6512. }
  6513. }
  6514. computeTangents() {
  6515. const index = this.index;
  6516. const attributes = this.attributes;
  6517. // based on http://www.terathon.com/code/tangent.html
  6518. // (per vertex tangents)
  6519. if ( index === null ||
  6520. attributes.position === undefined ||
  6521. attributes.normal === undefined ||
  6522. attributes.uv === undefined ) {
  6523. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6524. return;
  6525. }
  6526. const positionAttribute = attributes.position;
  6527. const normalAttribute = attributes.normal;
  6528. const uvAttribute = attributes.uv;
  6529. if ( this.hasAttribute( 'tangent' ) === false ) {
  6530. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6531. }
  6532. const tangentAttribute = this.getAttribute( 'tangent' );
  6533. const tan1 = [], tan2 = [];
  6534. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6535. tan1[ i ] = new Vector3();
  6536. tan2[ i ] = new Vector3();
  6537. }
  6538. const vA = new Vector3(),
  6539. vB = new Vector3(),
  6540. vC = new Vector3(),
  6541. uvA = new Vector2(),
  6542. uvB = new Vector2(),
  6543. uvC = new Vector2(),
  6544. sdir = new Vector3(),
  6545. tdir = new Vector3();
  6546. function handleTriangle( a, b, c ) {
  6547. vA.fromBufferAttribute( positionAttribute, a );
  6548. vB.fromBufferAttribute( positionAttribute, b );
  6549. vC.fromBufferAttribute( positionAttribute, c );
  6550. uvA.fromBufferAttribute( uvAttribute, a );
  6551. uvB.fromBufferAttribute( uvAttribute, b );
  6552. uvC.fromBufferAttribute( uvAttribute, c );
  6553. vB.sub( vA );
  6554. vC.sub( vA );
  6555. uvB.sub( uvA );
  6556. uvC.sub( uvA );
  6557. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6558. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6559. if ( ! isFinite( r ) ) return;
  6560. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6561. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6562. tan1[ a ].add( sdir );
  6563. tan1[ b ].add( sdir );
  6564. tan1[ c ].add( sdir );
  6565. tan2[ a ].add( tdir );
  6566. tan2[ b ].add( tdir );
  6567. tan2[ c ].add( tdir );
  6568. }
  6569. let groups = this.groups;
  6570. if ( groups.length === 0 ) {
  6571. groups = [ {
  6572. start: 0,
  6573. count: index.count
  6574. } ];
  6575. }
  6576. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6577. const group = groups[ i ];
  6578. const start = group.start;
  6579. const count = group.count;
  6580. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6581. handleTriangle(
  6582. index.getX( j + 0 ),
  6583. index.getX( j + 1 ),
  6584. index.getX( j + 2 )
  6585. );
  6586. }
  6587. }
  6588. const tmp = new Vector3(), tmp2 = new Vector3();
  6589. const n = new Vector3(), n2 = new Vector3();
  6590. function handleVertex( v ) {
  6591. n.fromBufferAttribute( normalAttribute, v );
  6592. n2.copy( n );
  6593. const t = tan1[ v ];
  6594. // Gram-Schmidt orthogonalize
  6595. tmp.copy( t );
  6596. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6597. // Calculate handedness
  6598. tmp2.crossVectors( n2, t );
  6599. const test = tmp2.dot( tan2[ v ] );
  6600. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6601. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6602. }
  6603. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6604. const group = groups[ i ];
  6605. const start = group.start;
  6606. const count = group.count;
  6607. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6608. handleVertex( index.getX( j + 0 ) );
  6609. handleVertex( index.getX( j + 1 ) );
  6610. handleVertex( index.getX( j + 2 ) );
  6611. }
  6612. }
  6613. }
  6614. computeVertexNormals() {
  6615. const index = this.index;
  6616. const positionAttribute = this.getAttribute( 'position' );
  6617. if ( positionAttribute !== undefined ) {
  6618. let normalAttribute = this.getAttribute( 'normal' );
  6619. if ( normalAttribute === undefined ) {
  6620. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6621. this.setAttribute( 'normal', normalAttribute );
  6622. } else {
  6623. // reset existing normals to zero
  6624. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6625. normalAttribute.setXYZ( i, 0, 0, 0 );
  6626. }
  6627. }
  6628. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6629. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6630. const cb = new Vector3(), ab = new Vector3();
  6631. // indexed elements
  6632. if ( index ) {
  6633. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6634. const vA = index.getX( i + 0 );
  6635. const vB = index.getX( i + 1 );
  6636. const vC = index.getX( i + 2 );
  6637. pA.fromBufferAttribute( positionAttribute, vA );
  6638. pB.fromBufferAttribute( positionAttribute, vB );
  6639. pC.fromBufferAttribute( positionAttribute, vC );
  6640. cb.subVectors( pC, pB );
  6641. ab.subVectors( pA, pB );
  6642. cb.cross( ab );
  6643. nA.fromBufferAttribute( normalAttribute, vA );
  6644. nB.fromBufferAttribute( normalAttribute, vB );
  6645. nC.fromBufferAttribute( normalAttribute, vC );
  6646. nA.add( cb );
  6647. nB.add( cb );
  6648. nC.add( cb );
  6649. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6650. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6651. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6652. }
  6653. } else {
  6654. // non-indexed elements (unconnected triangle soup)
  6655. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6656. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6657. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6658. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6659. cb.subVectors( pC, pB );
  6660. ab.subVectors( pA, pB );
  6661. cb.cross( ab );
  6662. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6663. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6664. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6665. }
  6666. }
  6667. this.normalizeNormals();
  6668. normalAttribute.needsUpdate = true;
  6669. }
  6670. }
  6671. normalizeNormals() {
  6672. const normals = this.attributes.normal;
  6673. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6674. _vector$8.fromBufferAttribute( normals, i );
  6675. _vector$8.normalize();
  6676. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6677. }
  6678. }
  6679. toNonIndexed() {
  6680. function convertBufferAttribute( attribute, indices ) {
  6681. const array = attribute.array;
  6682. const itemSize = attribute.itemSize;
  6683. const normalized = attribute.normalized;
  6684. const array2 = new array.constructor( indices.length * itemSize );
  6685. let index = 0, index2 = 0;
  6686. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6687. if ( attribute.isInterleavedBufferAttribute ) {
  6688. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6689. } else {
  6690. index = indices[ i ] * itemSize;
  6691. }
  6692. for ( let j = 0; j < itemSize; j ++ ) {
  6693. array2[ index2 ++ ] = array[ index ++ ];
  6694. }
  6695. }
  6696. return new BufferAttribute( array2, itemSize, normalized );
  6697. }
  6698. //
  6699. if ( this.index === null ) {
  6700. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6701. return this;
  6702. }
  6703. const geometry2 = new BufferGeometry();
  6704. const indices = this.index.array;
  6705. const attributes = this.attributes;
  6706. // attributes
  6707. for ( const name in attributes ) {
  6708. const attribute = attributes[ name ];
  6709. const newAttribute = convertBufferAttribute( attribute, indices );
  6710. geometry2.setAttribute( name, newAttribute );
  6711. }
  6712. // morph attributes
  6713. const morphAttributes = this.morphAttributes;
  6714. for ( const name in morphAttributes ) {
  6715. const morphArray = [];
  6716. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6717. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6718. const attribute = morphAttribute[ i ];
  6719. const newAttribute = convertBufferAttribute( attribute, indices );
  6720. morphArray.push( newAttribute );
  6721. }
  6722. geometry2.morphAttributes[ name ] = morphArray;
  6723. }
  6724. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6725. // groups
  6726. const groups = this.groups;
  6727. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6728. const group = groups[ i ];
  6729. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6730. }
  6731. return geometry2;
  6732. }
  6733. toJSON() {
  6734. const data = {
  6735. metadata: {
  6736. version: 4.6,
  6737. type: 'BufferGeometry',
  6738. generator: 'BufferGeometry.toJSON'
  6739. }
  6740. };
  6741. // standard BufferGeometry serialization
  6742. data.uuid = this.uuid;
  6743. data.type = this.type;
  6744. if ( this.name !== '' ) data.name = this.name;
  6745. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6746. if ( this.parameters !== undefined ) {
  6747. const parameters = this.parameters;
  6748. for ( const key in parameters ) {
  6749. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6750. }
  6751. return data;
  6752. }
  6753. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6754. data.data = { attributes: {} };
  6755. const index = this.index;
  6756. if ( index !== null ) {
  6757. data.data.index = {
  6758. type: index.array.constructor.name,
  6759. array: Array.prototype.slice.call( index.array )
  6760. };
  6761. }
  6762. const attributes = this.attributes;
  6763. for ( const key in attributes ) {
  6764. const attribute = attributes[ key ];
  6765. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6766. }
  6767. const morphAttributes = {};
  6768. let hasMorphAttributes = false;
  6769. for ( const key in this.morphAttributes ) {
  6770. const attributeArray = this.morphAttributes[ key ];
  6771. const array = [];
  6772. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6773. const attribute = attributeArray[ i ];
  6774. array.push( attribute.toJSON( data.data ) );
  6775. }
  6776. if ( array.length > 0 ) {
  6777. morphAttributes[ key ] = array;
  6778. hasMorphAttributes = true;
  6779. }
  6780. }
  6781. if ( hasMorphAttributes ) {
  6782. data.data.morphAttributes = morphAttributes;
  6783. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6784. }
  6785. const groups = this.groups;
  6786. if ( groups.length > 0 ) {
  6787. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6788. }
  6789. const boundingSphere = this.boundingSphere;
  6790. if ( boundingSphere !== null ) {
  6791. data.data.boundingSphere = {
  6792. center: boundingSphere.center.toArray(),
  6793. radius: boundingSphere.radius
  6794. };
  6795. }
  6796. return data;
  6797. }
  6798. clone() {
  6799. return new this.constructor().copy( this );
  6800. }
  6801. copy( source ) {
  6802. // reset
  6803. this.index = null;
  6804. this.attributes = {};
  6805. this.morphAttributes = {};
  6806. this.groups = [];
  6807. this.boundingBox = null;
  6808. this.boundingSphere = null;
  6809. // used for storing cloned, shared data
  6810. const data = {};
  6811. // name
  6812. this.name = source.name;
  6813. // index
  6814. const index = source.index;
  6815. if ( index !== null ) {
  6816. this.setIndex( index.clone( data ) );
  6817. }
  6818. // attributes
  6819. const attributes = source.attributes;
  6820. for ( const name in attributes ) {
  6821. const attribute = attributes[ name ];
  6822. this.setAttribute( name, attribute.clone( data ) );
  6823. }
  6824. // morph attributes
  6825. const morphAttributes = source.morphAttributes;
  6826. for ( const name in morphAttributes ) {
  6827. const array = [];
  6828. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6829. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6830. array.push( morphAttribute[ i ].clone( data ) );
  6831. }
  6832. this.morphAttributes[ name ] = array;
  6833. }
  6834. this.morphTargetsRelative = source.morphTargetsRelative;
  6835. // groups
  6836. const groups = source.groups;
  6837. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6838. const group = groups[ i ];
  6839. this.addGroup( group.start, group.count, group.materialIndex );
  6840. }
  6841. // bounding box
  6842. const boundingBox = source.boundingBox;
  6843. if ( boundingBox !== null ) {
  6844. this.boundingBox = boundingBox.clone();
  6845. }
  6846. // bounding sphere
  6847. const boundingSphere = source.boundingSphere;
  6848. if ( boundingSphere !== null ) {
  6849. this.boundingSphere = boundingSphere.clone();
  6850. }
  6851. // draw range
  6852. this.drawRange.start = source.drawRange.start;
  6853. this.drawRange.count = source.drawRange.count;
  6854. // user data
  6855. this.userData = source.userData;
  6856. return this;
  6857. }
  6858. dispose() {
  6859. this.dispatchEvent( { type: 'dispose' } );
  6860. }
  6861. }
  6862. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6863. const _ray$3 = /*@__PURE__*/ new Ray();
  6864. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6865. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6866. const _vA$1 = /*@__PURE__*/ new Vector3();
  6867. const _vB$1 = /*@__PURE__*/ new Vector3();
  6868. const _vC$1 = /*@__PURE__*/ new Vector3();
  6869. const _tempA = /*@__PURE__*/ new Vector3();
  6870. const _morphA = /*@__PURE__*/ new Vector3();
  6871. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6872. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6873. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6874. const _normalA = /*@__PURE__*/ new Vector3();
  6875. const _normalB = /*@__PURE__*/ new Vector3();
  6876. const _normalC = /*@__PURE__*/ new Vector3();
  6877. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6878. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6879. class Mesh extends Object3D {
  6880. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6881. super();
  6882. this.isMesh = true;
  6883. this.type = 'Mesh';
  6884. this.geometry = geometry;
  6885. this.material = material;
  6886. this.updateMorphTargets();
  6887. }
  6888. copy( source, recursive ) {
  6889. super.copy( source, recursive );
  6890. if ( source.morphTargetInfluences !== undefined ) {
  6891. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6892. }
  6893. if ( source.morphTargetDictionary !== undefined ) {
  6894. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6895. }
  6896. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6897. this.geometry = source.geometry;
  6898. return this;
  6899. }
  6900. updateMorphTargets() {
  6901. const geometry = this.geometry;
  6902. const morphAttributes = geometry.morphAttributes;
  6903. const keys = Object.keys( morphAttributes );
  6904. if ( keys.length > 0 ) {
  6905. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6906. if ( morphAttribute !== undefined ) {
  6907. this.morphTargetInfluences = [];
  6908. this.morphTargetDictionary = {};
  6909. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6910. const name = morphAttribute[ m ].name || String( m );
  6911. this.morphTargetInfluences.push( 0 );
  6912. this.morphTargetDictionary[ name ] = m;
  6913. }
  6914. }
  6915. }
  6916. }
  6917. getVertexPosition( index, target ) {
  6918. const geometry = this.geometry;
  6919. const position = geometry.attributes.position;
  6920. const morphPosition = geometry.morphAttributes.position;
  6921. const morphTargetsRelative = geometry.morphTargetsRelative;
  6922. target.fromBufferAttribute( position, index );
  6923. const morphInfluences = this.morphTargetInfluences;
  6924. if ( morphPosition && morphInfluences ) {
  6925. _morphA.set( 0, 0, 0 );
  6926. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6927. const influence = morphInfluences[ i ];
  6928. const morphAttribute = morphPosition[ i ];
  6929. if ( influence === 0 ) continue;
  6930. _tempA.fromBufferAttribute( morphAttribute, index );
  6931. if ( morphTargetsRelative ) {
  6932. _morphA.addScaledVector( _tempA, influence );
  6933. } else {
  6934. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6935. }
  6936. }
  6937. target.add( _morphA );
  6938. }
  6939. return target;
  6940. }
  6941. raycast( raycaster, intersects ) {
  6942. const geometry = this.geometry;
  6943. const material = this.material;
  6944. const matrixWorld = this.matrixWorld;
  6945. if ( material === undefined ) return;
  6946. // test with bounding sphere in world space
  6947. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6948. _sphere$6.copy( geometry.boundingSphere );
  6949. _sphere$6.applyMatrix4( matrixWorld );
  6950. // check distance from ray origin to bounding sphere
  6951. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6952. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6953. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6954. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6955. }
  6956. // convert ray to local space of mesh
  6957. _inverseMatrix$3.copy( matrixWorld ).invert();
  6958. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6959. // test with bounding box in local space
  6960. if ( geometry.boundingBox !== null ) {
  6961. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6962. }
  6963. // test for intersections with geometry
  6964. this._computeIntersections( raycaster, intersects, _ray$3 );
  6965. }
  6966. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6967. let intersection;
  6968. const geometry = this.geometry;
  6969. const material = this.material;
  6970. const index = geometry.index;
  6971. const position = geometry.attributes.position;
  6972. const uv = geometry.attributes.uv;
  6973. const uv1 = geometry.attributes.uv1;
  6974. const normal = geometry.attributes.normal;
  6975. const groups = geometry.groups;
  6976. const drawRange = geometry.drawRange;
  6977. if ( index !== null ) {
  6978. // indexed buffer geometry
  6979. if ( Array.isArray( material ) ) {
  6980. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6981. const group = groups[ i ];
  6982. const groupMaterial = material[ group.materialIndex ];
  6983. const start = Math.max( group.start, drawRange.start );
  6984. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6985. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6986. const a = index.getX( j );
  6987. const b = index.getX( j + 1 );
  6988. const c = index.getX( j + 2 );
  6989. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6990. if ( intersection ) {
  6991. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6992. intersection.face.materialIndex = group.materialIndex;
  6993. intersects.push( intersection );
  6994. }
  6995. }
  6996. }
  6997. } else {
  6998. const start = Math.max( 0, drawRange.start );
  6999. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7000. for ( let i = start, il = end; i < il; i += 3 ) {
  7001. const a = index.getX( i );
  7002. const b = index.getX( i + 1 );
  7003. const c = index.getX( i + 2 );
  7004. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7005. if ( intersection ) {
  7006. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7007. intersects.push( intersection );
  7008. }
  7009. }
  7010. }
  7011. } else if ( position !== undefined ) {
  7012. // non-indexed buffer geometry
  7013. if ( Array.isArray( material ) ) {
  7014. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7015. const group = groups[ i ];
  7016. const groupMaterial = material[ group.materialIndex ];
  7017. const start = Math.max( group.start, drawRange.start );
  7018. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7019. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7020. const a = j;
  7021. const b = j + 1;
  7022. const c = j + 2;
  7023. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7024. if ( intersection ) {
  7025. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7026. intersection.face.materialIndex = group.materialIndex;
  7027. intersects.push( intersection );
  7028. }
  7029. }
  7030. }
  7031. } else {
  7032. const start = Math.max( 0, drawRange.start );
  7033. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7034. for ( let i = start, il = end; i < il; i += 3 ) {
  7035. const a = i;
  7036. const b = i + 1;
  7037. const c = i + 2;
  7038. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7039. if ( intersection ) {
  7040. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7041. intersects.push( intersection );
  7042. }
  7043. }
  7044. }
  7045. }
  7046. }
  7047. }
  7048. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7049. let intersect;
  7050. if ( material.side === BackSide ) {
  7051. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7052. } else {
  7053. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7054. }
  7055. if ( intersect === null ) return null;
  7056. _intersectionPointWorld.copy( point );
  7057. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7058. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7059. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7060. return {
  7061. distance: distance,
  7062. point: _intersectionPointWorld.clone(),
  7063. object: object
  7064. };
  7065. }
  7066. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7067. object.getVertexPosition( a, _vA$1 );
  7068. object.getVertexPosition( b, _vB$1 );
  7069. object.getVertexPosition( c, _vC$1 );
  7070. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7071. if ( intersection ) {
  7072. if ( uv ) {
  7073. _uvA$1.fromBufferAttribute( uv, a );
  7074. _uvB$1.fromBufferAttribute( uv, b );
  7075. _uvC$1.fromBufferAttribute( uv, c );
  7076. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7077. }
  7078. if ( uv1 ) {
  7079. _uvA$1.fromBufferAttribute( uv1, a );
  7080. _uvB$1.fromBufferAttribute( uv1, b );
  7081. _uvC$1.fromBufferAttribute( uv1, c );
  7082. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7083. }
  7084. if ( normal ) {
  7085. _normalA.fromBufferAttribute( normal, a );
  7086. _normalB.fromBufferAttribute( normal, b );
  7087. _normalC.fromBufferAttribute( normal, c );
  7088. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7089. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7090. intersection.normal.multiplyScalar( - 1 );
  7091. }
  7092. }
  7093. const face = {
  7094. a: a,
  7095. b: b,
  7096. c: c,
  7097. normal: new Vector3(),
  7098. materialIndex: 0
  7099. };
  7100. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7101. intersection.face = face;
  7102. }
  7103. return intersection;
  7104. }
  7105. class BoxGeometry extends BufferGeometry {
  7106. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7107. super();
  7108. this.type = 'BoxGeometry';
  7109. this.parameters = {
  7110. width: width,
  7111. height: height,
  7112. depth: depth,
  7113. widthSegments: widthSegments,
  7114. heightSegments: heightSegments,
  7115. depthSegments: depthSegments
  7116. };
  7117. const scope = this;
  7118. // segments
  7119. widthSegments = Math.floor( widthSegments );
  7120. heightSegments = Math.floor( heightSegments );
  7121. depthSegments = Math.floor( depthSegments );
  7122. // buffers
  7123. const indices = [];
  7124. const vertices = [];
  7125. const normals = [];
  7126. const uvs = [];
  7127. // helper variables
  7128. let numberOfVertices = 0;
  7129. let groupStart = 0;
  7130. // build each side of the box geometry
  7131. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7132. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7133. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7134. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7135. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7136. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7137. // build geometry
  7138. this.setIndex( indices );
  7139. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7140. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7141. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7142. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7143. const segmentWidth = width / gridX;
  7144. const segmentHeight = height / gridY;
  7145. const widthHalf = width / 2;
  7146. const heightHalf = height / 2;
  7147. const depthHalf = depth / 2;
  7148. const gridX1 = gridX + 1;
  7149. const gridY1 = gridY + 1;
  7150. let vertexCounter = 0;
  7151. let groupCount = 0;
  7152. const vector = new Vector3();
  7153. // generate vertices, normals and uvs
  7154. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7155. const y = iy * segmentHeight - heightHalf;
  7156. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7157. const x = ix * segmentWidth - widthHalf;
  7158. // set values to correct vector component
  7159. vector[ u ] = x * udir;
  7160. vector[ v ] = y * vdir;
  7161. vector[ w ] = depthHalf;
  7162. // now apply vector to vertex buffer
  7163. vertices.push( vector.x, vector.y, vector.z );
  7164. // set values to correct vector component
  7165. vector[ u ] = 0;
  7166. vector[ v ] = 0;
  7167. vector[ w ] = depth > 0 ? 1 : - 1;
  7168. // now apply vector to normal buffer
  7169. normals.push( vector.x, vector.y, vector.z );
  7170. // uvs
  7171. uvs.push( ix / gridX );
  7172. uvs.push( 1 - ( iy / gridY ) );
  7173. // counters
  7174. vertexCounter += 1;
  7175. }
  7176. }
  7177. // indices
  7178. // 1. you need three indices to draw a single face
  7179. // 2. a single segment consists of two faces
  7180. // 3. so we need to generate six (2*3) indices per segment
  7181. for ( let iy = 0; iy < gridY; iy ++ ) {
  7182. for ( let ix = 0; ix < gridX; ix ++ ) {
  7183. const a = numberOfVertices + ix + gridX1 * iy;
  7184. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7185. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7186. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7187. // faces
  7188. indices.push( a, b, d );
  7189. indices.push( b, c, d );
  7190. // increase counter
  7191. groupCount += 6;
  7192. }
  7193. }
  7194. // add a group to the geometry. this will ensure multi material support
  7195. scope.addGroup( groupStart, groupCount, materialIndex );
  7196. // calculate new start value for groups
  7197. groupStart += groupCount;
  7198. // update total number of vertices
  7199. numberOfVertices += vertexCounter;
  7200. }
  7201. }
  7202. copy( source ) {
  7203. super.copy( source );
  7204. this.parameters = Object.assign( {}, source.parameters );
  7205. return this;
  7206. }
  7207. static fromJSON( data ) {
  7208. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7209. }
  7210. }
  7211. /**
  7212. * Uniform Utilities
  7213. */
  7214. function cloneUniforms( src ) {
  7215. const dst = {};
  7216. for ( const u in src ) {
  7217. dst[ u ] = {};
  7218. for ( const p in src[ u ] ) {
  7219. const property = src[ u ][ p ];
  7220. if ( property && ( property.isColor ||
  7221. property.isMatrix3 || property.isMatrix4 ||
  7222. property.isVector2 || property.isVector3 || property.isVector4 ||
  7223. property.isTexture || property.isQuaternion ) ) {
  7224. if ( property.isRenderTargetTexture ) {
  7225. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7226. dst[ u ][ p ] = null;
  7227. } else {
  7228. dst[ u ][ p ] = property.clone();
  7229. }
  7230. } else if ( Array.isArray( property ) ) {
  7231. dst[ u ][ p ] = property.slice();
  7232. } else {
  7233. dst[ u ][ p ] = property;
  7234. }
  7235. }
  7236. }
  7237. return dst;
  7238. }
  7239. function cloneUniformsGroups( src ) {
  7240. const dst = [];
  7241. for ( let u = 0; u < src.length; u ++ ) {
  7242. dst.push( src[ u ].clone() );
  7243. }
  7244. return dst;
  7245. }
  7246. var default_vertex = /* glsl */`
  7247. void main() {
  7248. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7249. }
  7250. `;
  7251. var default_fragment = /* glsl */`
  7252. void main() {
  7253. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7254. }
  7255. `;
  7256. class ShaderMaterial extends Material {
  7257. constructor( parameters ) {
  7258. super();
  7259. this.isShaderMaterial = true;
  7260. this.type = 'ShaderMaterial';
  7261. this.defines = {};
  7262. this.uniforms = {};
  7263. this.uniformsGroups = [];
  7264. this.vertexShader = default_vertex;
  7265. this.fragmentShader = default_fragment;
  7266. this.linewidth = 1;
  7267. this.wireframe = false;
  7268. this.wireframeLinewidth = 1;
  7269. this.fog = false; // set to use scene fog
  7270. this.lights = false; // set to use scene lights
  7271. this.clipping = false; // set to use user-defined clipping planes
  7272. this.forceSinglePass = true;
  7273. this.extensions = {
  7274. clipCullDistance: false, // set to use vertex shader clipping
  7275. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7276. };
  7277. // When rendered geometry doesn't include these attributes but the material does,
  7278. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7279. this.defaultAttributeValues = {
  7280. 'color': [ 1, 1, 1 ],
  7281. 'uv': [ 0, 0 ],
  7282. 'uv1': [ 0, 0 ]
  7283. };
  7284. this.index0AttributeName = undefined;
  7285. this.uniformsNeedUpdate = false;
  7286. this.glslVersion = null;
  7287. if ( parameters !== undefined ) {
  7288. this.setValues( parameters );
  7289. }
  7290. }
  7291. copy( source ) {
  7292. super.copy( source );
  7293. this.fragmentShader = source.fragmentShader;
  7294. this.vertexShader = source.vertexShader;
  7295. this.uniforms = cloneUniforms( source.uniforms );
  7296. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7297. this.defines = Object.assign( {}, source.defines );
  7298. this.wireframe = source.wireframe;
  7299. this.wireframeLinewidth = source.wireframeLinewidth;
  7300. this.fog = source.fog;
  7301. this.lights = source.lights;
  7302. this.clipping = source.clipping;
  7303. this.extensions = Object.assign( {}, source.extensions );
  7304. this.glslVersion = source.glslVersion;
  7305. return this;
  7306. }
  7307. toJSON( meta ) {
  7308. const data = super.toJSON( meta );
  7309. data.glslVersion = this.glslVersion;
  7310. data.uniforms = {};
  7311. for ( const name in this.uniforms ) {
  7312. const uniform = this.uniforms[ name ];
  7313. const value = uniform.value;
  7314. if ( value && value.isTexture ) {
  7315. data.uniforms[ name ] = {
  7316. type: 't',
  7317. value: value.toJSON( meta ).uuid
  7318. };
  7319. } else if ( value && value.isColor ) {
  7320. data.uniforms[ name ] = {
  7321. type: 'c',
  7322. value: value.getHex()
  7323. };
  7324. } else if ( value && value.isVector2 ) {
  7325. data.uniforms[ name ] = {
  7326. type: 'v2',
  7327. value: value.toArray()
  7328. };
  7329. } else if ( value && value.isVector3 ) {
  7330. data.uniforms[ name ] = {
  7331. type: 'v3',
  7332. value: value.toArray()
  7333. };
  7334. } else if ( value && value.isVector4 ) {
  7335. data.uniforms[ name ] = {
  7336. type: 'v4',
  7337. value: value.toArray()
  7338. };
  7339. } else if ( value && value.isMatrix3 ) {
  7340. data.uniforms[ name ] = {
  7341. type: 'm3',
  7342. value: value.toArray()
  7343. };
  7344. } else if ( value && value.isMatrix4 ) {
  7345. data.uniforms[ name ] = {
  7346. type: 'm4',
  7347. value: value.toArray()
  7348. };
  7349. } else {
  7350. data.uniforms[ name ] = {
  7351. value: value
  7352. };
  7353. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7354. }
  7355. }
  7356. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7357. data.vertexShader = this.vertexShader;
  7358. data.fragmentShader = this.fragmentShader;
  7359. data.lights = this.lights;
  7360. data.clipping = this.clipping;
  7361. const extensions = {};
  7362. for ( const key in this.extensions ) {
  7363. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7364. }
  7365. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7366. return data;
  7367. }
  7368. }
  7369. class Camera extends Object3D {
  7370. constructor() {
  7371. super();
  7372. this.isCamera = true;
  7373. this.type = 'Camera';
  7374. this.matrixWorldInverse = new Matrix4();
  7375. this.projectionMatrix = new Matrix4();
  7376. this.projectionMatrixInverse = new Matrix4();
  7377. this.coordinateSystem = WebGLCoordinateSystem;
  7378. }
  7379. copy( source, recursive ) {
  7380. super.copy( source, recursive );
  7381. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7382. this.projectionMatrix.copy( source.projectionMatrix );
  7383. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7384. this.coordinateSystem = source.coordinateSystem;
  7385. return this;
  7386. }
  7387. getWorldDirection( target ) {
  7388. return super.getWorldDirection( target ).negate();
  7389. }
  7390. updateMatrixWorld( force ) {
  7391. super.updateMatrixWorld( force );
  7392. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7393. }
  7394. updateWorldMatrix( updateParents, updateChildren ) {
  7395. super.updateWorldMatrix( updateParents, updateChildren );
  7396. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7397. }
  7398. clone() {
  7399. return new this.constructor().copy( this );
  7400. }
  7401. }
  7402. const _v3$1 = /*@__PURE__*/ new Vector3();
  7403. const _minTarget = /*@__PURE__*/ new Vector2();
  7404. const _maxTarget = /*@__PURE__*/ new Vector2();
  7405. class PerspectiveCamera extends Camera {
  7406. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7407. super();
  7408. this.isPerspectiveCamera = true;
  7409. this.type = 'PerspectiveCamera';
  7410. this.fov = fov;
  7411. this.zoom = 1;
  7412. this.near = near;
  7413. this.far = far;
  7414. this.focus = 10;
  7415. this.aspect = aspect;
  7416. this.view = null;
  7417. this.filmGauge = 35; // width of the film (default in millimeters)
  7418. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7419. this.updateProjectionMatrix();
  7420. }
  7421. copy( source, recursive ) {
  7422. super.copy( source, recursive );
  7423. this.fov = source.fov;
  7424. this.zoom = source.zoom;
  7425. this.near = source.near;
  7426. this.far = source.far;
  7427. this.focus = source.focus;
  7428. this.aspect = source.aspect;
  7429. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7430. this.filmGauge = source.filmGauge;
  7431. this.filmOffset = source.filmOffset;
  7432. return this;
  7433. }
  7434. /**
  7435. * Sets the FOV by focal length in respect to the current .filmGauge.
  7436. *
  7437. * The default film gauge is 35, so that the focal length can be specified for
  7438. * a 35mm (full frame) camera.
  7439. *
  7440. * Values for focal length and film gauge must have the same unit.
  7441. */
  7442. setFocalLength( focalLength ) {
  7443. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7444. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7445. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7446. this.updateProjectionMatrix();
  7447. }
  7448. /**
  7449. * Calculates the focal length from the current .fov and .filmGauge.
  7450. */
  7451. getFocalLength() {
  7452. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7453. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7454. }
  7455. getEffectiveFOV() {
  7456. return RAD2DEG * 2 * Math.atan(
  7457. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7458. }
  7459. getFilmWidth() {
  7460. // film not completely covered in portrait format (aspect < 1)
  7461. return this.filmGauge * Math.min( this.aspect, 1 );
  7462. }
  7463. getFilmHeight() {
  7464. // film not completely covered in landscape format (aspect > 1)
  7465. return this.filmGauge / Math.max( this.aspect, 1 );
  7466. }
  7467. /**
  7468. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7469. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7470. */
  7471. getViewBounds( distance, minTarget, maxTarget ) {
  7472. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7473. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7474. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7475. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7476. }
  7477. /**
  7478. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7479. * Copies the result into the target Vector2, where x is width and y is height.
  7480. */
  7481. getViewSize( distance, target ) {
  7482. this.getViewBounds( distance, _minTarget, _maxTarget );
  7483. return target.subVectors( _maxTarget, _minTarget );
  7484. }
  7485. /**
  7486. * Sets an offset in a larger frustum. This is useful for multi-window or
  7487. * multi-monitor/multi-machine setups.
  7488. *
  7489. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7490. * the monitors are in grid like this
  7491. *
  7492. * +---+---+---+
  7493. * | A | B | C |
  7494. * +---+---+---+
  7495. * | D | E | F |
  7496. * +---+---+---+
  7497. *
  7498. * then for each monitor you would call it like this
  7499. *
  7500. * const w = 1920;
  7501. * const h = 1080;
  7502. * const fullWidth = w * 3;
  7503. * const fullHeight = h * 2;
  7504. *
  7505. * --A--
  7506. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7507. * --B--
  7508. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7509. * --C--
  7510. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7511. * --D--
  7512. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7513. * --E--
  7514. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7515. * --F--
  7516. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7517. *
  7518. * Note there is no reason monitors have to be the same size or in a grid.
  7519. */
  7520. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7521. this.aspect = fullWidth / fullHeight;
  7522. if ( this.view === null ) {
  7523. this.view = {
  7524. enabled: true,
  7525. fullWidth: 1,
  7526. fullHeight: 1,
  7527. offsetX: 0,
  7528. offsetY: 0,
  7529. width: 1,
  7530. height: 1
  7531. };
  7532. }
  7533. this.view.enabled = true;
  7534. this.view.fullWidth = fullWidth;
  7535. this.view.fullHeight = fullHeight;
  7536. this.view.offsetX = x;
  7537. this.view.offsetY = y;
  7538. this.view.width = width;
  7539. this.view.height = height;
  7540. this.updateProjectionMatrix();
  7541. }
  7542. clearViewOffset() {
  7543. if ( this.view !== null ) {
  7544. this.view.enabled = false;
  7545. }
  7546. this.updateProjectionMatrix();
  7547. }
  7548. updateProjectionMatrix() {
  7549. const near = this.near;
  7550. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7551. let height = 2 * top;
  7552. let width = this.aspect * height;
  7553. let left = - 0.5 * width;
  7554. const view = this.view;
  7555. if ( this.view !== null && this.view.enabled ) {
  7556. const fullWidth = view.fullWidth,
  7557. fullHeight = view.fullHeight;
  7558. left += view.offsetX * width / fullWidth;
  7559. top -= view.offsetY * height / fullHeight;
  7560. width *= view.width / fullWidth;
  7561. height *= view.height / fullHeight;
  7562. }
  7563. const skew = this.filmOffset;
  7564. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7565. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7566. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7567. }
  7568. toJSON( meta ) {
  7569. const data = super.toJSON( meta );
  7570. data.object.fov = this.fov;
  7571. data.object.zoom = this.zoom;
  7572. data.object.near = this.near;
  7573. data.object.far = this.far;
  7574. data.object.focus = this.focus;
  7575. data.object.aspect = this.aspect;
  7576. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7577. data.object.filmGauge = this.filmGauge;
  7578. data.object.filmOffset = this.filmOffset;
  7579. return data;
  7580. }
  7581. }
  7582. const fov = - 90; // negative fov is not an error
  7583. const aspect = 1;
  7584. class CubeCamera extends Object3D {
  7585. constructor( near, far, renderTarget ) {
  7586. super();
  7587. this.type = 'CubeCamera';
  7588. this.renderTarget = renderTarget;
  7589. this.coordinateSystem = null;
  7590. this.activeMipmapLevel = 0;
  7591. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7592. cameraPX.layers = this.layers;
  7593. this.add( cameraPX );
  7594. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7595. cameraNX.layers = this.layers;
  7596. this.add( cameraNX );
  7597. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7598. cameraPY.layers = this.layers;
  7599. this.add( cameraPY );
  7600. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7601. cameraNY.layers = this.layers;
  7602. this.add( cameraNY );
  7603. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7604. cameraPZ.layers = this.layers;
  7605. this.add( cameraPZ );
  7606. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7607. cameraNZ.layers = this.layers;
  7608. this.add( cameraNZ );
  7609. }
  7610. updateCoordinateSystem() {
  7611. const coordinateSystem = this.coordinateSystem;
  7612. const cameras = this.children.concat();
  7613. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7614. for ( const camera of cameras ) this.remove( camera );
  7615. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7616. cameraPX.up.set( 0, 1, 0 );
  7617. cameraPX.lookAt( 1, 0, 0 );
  7618. cameraNX.up.set( 0, 1, 0 );
  7619. cameraNX.lookAt( - 1, 0, 0 );
  7620. cameraPY.up.set( 0, 0, - 1 );
  7621. cameraPY.lookAt( 0, 1, 0 );
  7622. cameraNY.up.set( 0, 0, 1 );
  7623. cameraNY.lookAt( 0, - 1, 0 );
  7624. cameraPZ.up.set( 0, 1, 0 );
  7625. cameraPZ.lookAt( 0, 0, 1 );
  7626. cameraNZ.up.set( 0, 1, 0 );
  7627. cameraNZ.lookAt( 0, 0, - 1 );
  7628. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7629. cameraPX.up.set( 0, - 1, 0 );
  7630. cameraPX.lookAt( - 1, 0, 0 );
  7631. cameraNX.up.set( 0, - 1, 0 );
  7632. cameraNX.lookAt( 1, 0, 0 );
  7633. cameraPY.up.set( 0, 0, 1 );
  7634. cameraPY.lookAt( 0, 1, 0 );
  7635. cameraNY.up.set( 0, 0, - 1 );
  7636. cameraNY.lookAt( 0, - 1, 0 );
  7637. cameraPZ.up.set( 0, - 1, 0 );
  7638. cameraPZ.lookAt( 0, 0, 1 );
  7639. cameraNZ.up.set( 0, - 1, 0 );
  7640. cameraNZ.lookAt( 0, 0, - 1 );
  7641. } else {
  7642. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7643. }
  7644. for ( const camera of cameras ) {
  7645. this.add( camera );
  7646. camera.updateMatrixWorld();
  7647. }
  7648. }
  7649. update( renderer, scene ) {
  7650. if ( this.parent === null ) this.updateMatrixWorld();
  7651. const { renderTarget, activeMipmapLevel } = this;
  7652. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7653. this.coordinateSystem = renderer.coordinateSystem;
  7654. this.updateCoordinateSystem();
  7655. }
  7656. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7657. const currentRenderTarget = renderer.getRenderTarget();
  7658. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7659. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7660. const currentXrEnabled = renderer.xr.enabled;
  7661. renderer.xr.enabled = false;
  7662. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7663. renderTarget.texture.generateMipmaps = false;
  7664. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7665. renderer.render( scene, cameraPX );
  7666. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7667. renderer.render( scene, cameraNX );
  7668. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7669. renderer.render( scene, cameraPY );
  7670. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7671. renderer.render( scene, cameraNY );
  7672. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7673. renderer.render( scene, cameraPZ );
  7674. // mipmaps are generated during the last call of render()
  7675. // at this point, all sides of the cube render target are defined
  7676. renderTarget.texture.generateMipmaps = generateMipmaps;
  7677. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7678. renderer.render( scene, cameraNZ );
  7679. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7680. renderer.xr.enabled = currentXrEnabled;
  7681. renderTarget.texture.needsPMREMUpdate = true;
  7682. }
  7683. }
  7684. class CubeTexture extends Texture {
  7685. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7686. images = images !== undefined ? images : [];
  7687. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7688. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7689. this.isCubeTexture = true;
  7690. this.flipY = false;
  7691. }
  7692. get images() {
  7693. return this.image;
  7694. }
  7695. set images( value ) {
  7696. this.image = value;
  7697. }
  7698. }
  7699. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7700. constructor( size = 1, options = {} ) {
  7701. super( size, size, options );
  7702. this.isWebGLCubeRenderTarget = true;
  7703. const image = { width: size, height: size, depth: 1 };
  7704. const images = [ image, image, image, image, image, image ];
  7705. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7706. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7707. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7708. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7709. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7710. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7711. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7712. this.texture.isRenderTargetTexture = true;
  7713. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7714. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7715. }
  7716. fromEquirectangularTexture( renderer, texture ) {
  7717. this.texture.type = texture.type;
  7718. this.texture.colorSpace = texture.colorSpace;
  7719. this.texture.generateMipmaps = texture.generateMipmaps;
  7720. this.texture.minFilter = texture.minFilter;
  7721. this.texture.magFilter = texture.magFilter;
  7722. const shader = {
  7723. uniforms: {
  7724. tEquirect: { value: null },
  7725. },
  7726. vertexShader: /* glsl */`
  7727. varying vec3 vWorldDirection;
  7728. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7729. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7730. }
  7731. void main() {
  7732. vWorldDirection = transformDirection( position, modelMatrix );
  7733. #include <begin_vertex>
  7734. #include <project_vertex>
  7735. }
  7736. `,
  7737. fragmentShader: /* glsl */`
  7738. uniform sampler2D tEquirect;
  7739. varying vec3 vWorldDirection;
  7740. #include <common>
  7741. void main() {
  7742. vec3 direction = normalize( vWorldDirection );
  7743. vec2 sampleUV = equirectUv( direction );
  7744. gl_FragColor = texture2D( tEquirect, sampleUV );
  7745. }
  7746. `
  7747. };
  7748. const geometry = new BoxGeometry( 5, 5, 5 );
  7749. const material = new ShaderMaterial( {
  7750. name: 'CubemapFromEquirect',
  7751. uniforms: cloneUniforms( shader.uniforms ),
  7752. vertexShader: shader.vertexShader,
  7753. fragmentShader: shader.fragmentShader,
  7754. side: BackSide,
  7755. blending: NoBlending
  7756. } );
  7757. material.uniforms.tEquirect.value = texture;
  7758. const mesh = new Mesh( geometry, material );
  7759. const currentMinFilter = texture.minFilter;
  7760. // Avoid blurred poles
  7761. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7762. const camera = new CubeCamera( 1, 10, this );
  7763. camera.update( renderer, mesh );
  7764. texture.minFilter = currentMinFilter;
  7765. mesh.geometry.dispose();
  7766. mesh.material.dispose();
  7767. return this;
  7768. }
  7769. clear( renderer, color, depth, stencil ) {
  7770. const currentRenderTarget = renderer.getRenderTarget();
  7771. for ( let i = 0; i < 6; i ++ ) {
  7772. renderer.setRenderTarget( this, i );
  7773. renderer.clear( color, depth, stencil );
  7774. }
  7775. renderer.setRenderTarget( currentRenderTarget );
  7776. }
  7777. }
  7778. class FogExp2 {
  7779. constructor( color, density = 0.00025 ) {
  7780. this.isFogExp2 = true;
  7781. this.name = '';
  7782. this.color = new Color( color );
  7783. this.density = density;
  7784. }
  7785. clone() {
  7786. return new FogExp2( this.color, this.density );
  7787. }
  7788. toJSON( /* meta */ ) {
  7789. return {
  7790. type: 'FogExp2',
  7791. name: this.name,
  7792. color: this.color.getHex(),
  7793. density: this.density
  7794. };
  7795. }
  7796. }
  7797. class Fog {
  7798. constructor( color, near = 1, far = 1000 ) {
  7799. this.isFog = true;
  7800. this.name = '';
  7801. this.color = new Color( color );
  7802. this.near = near;
  7803. this.far = far;
  7804. }
  7805. clone() {
  7806. return new Fog( this.color, this.near, this.far );
  7807. }
  7808. toJSON( /* meta */ ) {
  7809. return {
  7810. type: 'Fog',
  7811. name: this.name,
  7812. color: this.color.getHex(),
  7813. near: this.near,
  7814. far: this.far
  7815. };
  7816. }
  7817. }
  7818. class Scene extends Object3D {
  7819. constructor() {
  7820. super();
  7821. this.isScene = true;
  7822. this.type = 'Scene';
  7823. this.background = null;
  7824. this.environment = null;
  7825. this.fog = null;
  7826. this.backgroundBlurriness = 0;
  7827. this.backgroundIntensity = 1;
  7828. this.backgroundRotation = new Euler();
  7829. this.environmentIntensity = 1;
  7830. this.environmentRotation = new Euler();
  7831. this.overrideMaterial = null;
  7832. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7833. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7834. }
  7835. }
  7836. copy( source, recursive ) {
  7837. super.copy( source, recursive );
  7838. if ( source.background !== null ) this.background = source.background.clone();
  7839. if ( source.environment !== null ) this.environment = source.environment.clone();
  7840. if ( source.fog !== null ) this.fog = source.fog.clone();
  7841. this.backgroundBlurriness = source.backgroundBlurriness;
  7842. this.backgroundIntensity = source.backgroundIntensity;
  7843. this.backgroundRotation.copy( source.backgroundRotation );
  7844. this.environmentIntensity = source.environmentIntensity;
  7845. this.environmentRotation.copy( source.environmentRotation );
  7846. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7847. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7848. return this;
  7849. }
  7850. toJSON( meta ) {
  7851. const data = super.toJSON( meta );
  7852. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7853. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7854. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7855. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7856. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7857. data.object.environmentRotation = this.environmentRotation.toArray();
  7858. return data;
  7859. }
  7860. }
  7861. class InterleavedBuffer {
  7862. constructor( array, stride ) {
  7863. this.isInterleavedBuffer = true;
  7864. this.array = array;
  7865. this.stride = stride;
  7866. this.count = array !== undefined ? array.length / stride : 0;
  7867. this.usage = StaticDrawUsage;
  7868. this._updateRange = { offset: 0, count: - 1 };
  7869. this.updateRanges = [];
  7870. this.version = 0;
  7871. this.uuid = generateUUID();
  7872. }
  7873. onUploadCallback() {}
  7874. set needsUpdate( value ) {
  7875. if ( value === true ) this.version ++;
  7876. }
  7877. get updateRange() {
  7878. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  7879. return this._updateRange;
  7880. }
  7881. setUsage( value ) {
  7882. this.usage = value;
  7883. return this;
  7884. }
  7885. addUpdateRange( start, count ) {
  7886. this.updateRanges.push( { start, count } );
  7887. }
  7888. clearUpdateRanges() {
  7889. this.updateRanges.length = 0;
  7890. }
  7891. copy( source ) {
  7892. this.array = new source.array.constructor( source.array );
  7893. this.count = source.count;
  7894. this.stride = source.stride;
  7895. this.usage = source.usage;
  7896. return this;
  7897. }
  7898. copyAt( index1, attribute, index2 ) {
  7899. index1 *= this.stride;
  7900. index2 *= attribute.stride;
  7901. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7902. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7903. }
  7904. return this;
  7905. }
  7906. set( value, offset = 0 ) {
  7907. this.array.set( value, offset );
  7908. return this;
  7909. }
  7910. clone( data ) {
  7911. if ( data.arrayBuffers === undefined ) {
  7912. data.arrayBuffers = {};
  7913. }
  7914. if ( this.array.buffer._uuid === undefined ) {
  7915. this.array.buffer._uuid = generateUUID();
  7916. }
  7917. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7918. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7919. }
  7920. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7921. const ib = new this.constructor( array, this.stride );
  7922. ib.setUsage( this.usage );
  7923. return ib;
  7924. }
  7925. onUpload( callback ) {
  7926. this.onUploadCallback = callback;
  7927. return this;
  7928. }
  7929. toJSON( data ) {
  7930. if ( data.arrayBuffers === undefined ) {
  7931. data.arrayBuffers = {};
  7932. }
  7933. // generate UUID for array buffer if necessary
  7934. if ( this.array.buffer._uuid === undefined ) {
  7935. this.array.buffer._uuid = generateUUID();
  7936. }
  7937. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7938. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7939. }
  7940. //
  7941. return {
  7942. uuid: this.uuid,
  7943. buffer: this.array.buffer._uuid,
  7944. type: this.array.constructor.name,
  7945. stride: this.stride
  7946. };
  7947. }
  7948. }
  7949. const _vector$7 = /*@__PURE__*/ new Vector3();
  7950. class InterleavedBufferAttribute {
  7951. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7952. this.isInterleavedBufferAttribute = true;
  7953. this.name = '';
  7954. this.data = interleavedBuffer;
  7955. this.itemSize = itemSize;
  7956. this.offset = offset;
  7957. this.normalized = normalized;
  7958. }
  7959. get count() {
  7960. return this.data.count;
  7961. }
  7962. get array() {
  7963. return this.data.array;
  7964. }
  7965. set needsUpdate( value ) {
  7966. this.data.needsUpdate = value;
  7967. }
  7968. applyMatrix4( m ) {
  7969. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7970. _vector$7.fromBufferAttribute( this, i );
  7971. _vector$7.applyMatrix4( m );
  7972. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7973. }
  7974. return this;
  7975. }
  7976. applyNormalMatrix( m ) {
  7977. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7978. _vector$7.fromBufferAttribute( this, i );
  7979. _vector$7.applyNormalMatrix( m );
  7980. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7981. }
  7982. return this;
  7983. }
  7984. transformDirection( m ) {
  7985. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7986. _vector$7.fromBufferAttribute( this, i );
  7987. _vector$7.transformDirection( m );
  7988. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7989. }
  7990. return this;
  7991. }
  7992. getComponent( index, component ) {
  7993. let value = this.array[ index * this.data.stride + this.offset + component ];
  7994. if ( this.normalized ) value = denormalize( value, this.array );
  7995. return value;
  7996. }
  7997. setComponent( index, component, value ) {
  7998. if ( this.normalized ) value = normalize$1( value, this.array );
  7999. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8000. return this;
  8001. }
  8002. setX( index, x ) {
  8003. if ( this.normalized ) x = normalize$1( x, this.array );
  8004. this.data.array[ index * this.data.stride + this.offset ] = x;
  8005. return this;
  8006. }
  8007. setY( index, y ) {
  8008. if ( this.normalized ) y = normalize$1( y, this.array );
  8009. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8010. return this;
  8011. }
  8012. setZ( index, z ) {
  8013. if ( this.normalized ) z = normalize$1( z, this.array );
  8014. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8015. return this;
  8016. }
  8017. setW( index, w ) {
  8018. if ( this.normalized ) w = normalize$1( w, this.array );
  8019. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8020. return this;
  8021. }
  8022. getX( index ) {
  8023. let x = this.data.array[ index * this.data.stride + this.offset ];
  8024. if ( this.normalized ) x = denormalize( x, this.array );
  8025. return x;
  8026. }
  8027. getY( index ) {
  8028. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8029. if ( this.normalized ) y = denormalize( y, this.array );
  8030. return y;
  8031. }
  8032. getZ( index ) {
  8033. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8034. if ( this.normalized ) z = denormalize( z, this.array );
  8035. return z;
  8036. }
  8037. getW( index ) {
  8038. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8039. if ( this.normalized ) w = denormalize( w, this.array );
  8040. return w;
  8041. }
  8042. setXY( index, x, y ) {
  8043. index = index * this.data.stride + this.offset;
  8044. if ( this.normalized ) {
  8045. x = normalize$1( x, this.array );
  8046. y = normalize$1( y, this.array );
  8047. }
  8048. this.data.array[ index + 0 ] = x;
  8049. this.data.array[ index + 1 ] = y;
  8050. return this;
  8051. }
  8052. setXYZ( index, x, y, z ) {
  8053. index = index * this.data.stride + this.offset;
  8054. if ( this.normalized ) {
  8055. x = normalize$1( x, this.array );
  8056. y = normalize$1( y, this.array );
  8057. z = normalize$1( z, this.array );
  8058. }
  8059. this.data.array[ index + 0 ] = x;
  8060. this.data.array[ index + 1 ] = y;
  8061. this.data.array[ index + 2 ] = z;
  8062. return this;
  8063. }
  8064. setXYZW( index, x, y, z, w ) {
  8065. index = index * this.data.stride + this.offset;
  8066. if ( this.normalized ) {
  8067. x = normalize$1( x, this.array );
  8068. y = normalize$1( y, this.array );
  8069. z = normalize$1( z, this.array );
  8070. w = normalize$1( w, this.array );
  8071. }
  8072. this.data.array[ index + 0 ] = x;
  8073. this.data.array[ index + 1 ] = y;
  8074. this.data.array[ index + 2 ] = z;
  8075. this.data.array[ index + 3 ] = w;
  8076. return this;
  8077. }
  8078. clone( data ) {
  8079. if ( data === undefined ) {
  8080. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8081. const array = [];
  8082. for ( let i = 0; i < this.count; i ++ ) {
  8083. const index = i * this.data.stride + this.offset;
  8084. for ( let j = 0; j < this.itemSize; j ++ ) {
  8085. array.push( this.data.array[ index + j ] );
  8086. }
  8087. }
  8088. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8089. } else {
  8090. if ( data.interleavedBuffers === undefined ) {
  8091. data.interleavedBuffers = {};
  8092. }
  8093. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8094. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8095. }
  8096. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8097. }
  8098. }
  8099. toJSON( data ) {
  8100. if ( data === undefined ) {
  8101. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8102. const array = [];
  8103. for ( let i = 0; i < this.count; i ++ ) {
  8104. const index = i * this.data.stride + this.offset;
  8105. for ( let j = 0; j < this.itemSize; j ++ ) {
  8106. array.push( this.data.array[ index + j ] );
  8107. }
  8108. }
  8109. // de-interleave data and save it as an ordinary buffer attribute for now
  8110. return {
  8111. itemSize: this.itemSize,
  8112. type: this.array.constructor.name,
  8113. array: array,
  8114. normalized: this.normalized
  8115. };
  8116. } else {
  8117. // save as true interleaved attribute
  8118. if ( data.interleavedBuffers === undefined ) {
  8119. data.interleavedBuffers = {};
  8120. }
  8121. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8122. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8123. }
  8124. return {
  8125. isInterleavedBufferAttribute: true,
  8126. itemSize: this.itemSize,
  8127. data: this.data.uuid,
  8128. offset: this.offset,
  8129. normalized: this.normalized
  8130. };
  8131. }
  8132. }
  8133. }
  8134. class SpriteMaterial extends Material {
  8135. constructor( parameters ) {
  8136. super();
  8137. this.isSpriteMaterial = true;
  8138. this.type = 'SpriteMaterial';
  8139. this.color = new Color( 0xffffff );
  8140. this.map = null;
  8141. this.alphaMap = null;
  8142. this.rotation = 0;
  8143. this.sizeAttenuation = true;
  8144. this.transparent = true;
  8145. this.fog = true;
  8146. this.setValues( parameters );
  8147. }
  8148. copy( source ) {
  8149. super.copy( source );
  8150. this.color.copy( source.color );
  8151. this.map = source.map;
  8152. this.alphaMap = source.alphaMap;
  8153. this.rotation = source.rotation;
  8154. this.sizeAttenuation = source.sizeAttenuation;
  8155. this.fog = source.fog;
  8156. return this;
  8157. }
  8158. }
  8159. let _geometry$1;
  8160. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8161. const _worldScale = /*@__PURE__*/ new Vector3();
  8162. const _mvPosition = /*@__PURE__*/ new Vector3();
  8163. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8164. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8165. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8166. const _vA = /*@__PURE__*/ new Vector3();
  8167. const _vB = /*@__PURE__*/ new Vector3();
  8168. const _vC = /*@__PURE__*/ new Vector3();
  8169. const _uvA = /*@__PURE__*/ new Vector2();
  8170. const _uvB = /*@__PURE__*/ new Vector2();
  8171. const _uvC = /*@__PURE__*/ new Vector2();
  8172. class Sprite extends Object3D {
  8173. constructor( material = new SpriteMaterial() ) {
  8174. super();
  8175. this.isSprite = true;
  8176. this.type = 'Sprite';
  8177. if ( _geometry$1 === undefined ) {
  8178. _geometry$1 = new BufferGeometry();
  8179. const float32Array = new Float32Array( [
  8180. - 0.5, - 0.5, 0, 0, 0,
  8181. 0.5, - 0.5, 0, 1, 0,
  8182. 0.5, 0.5, 0, 1, 1,
  8183. - 0.5, 0.5, 0, 0, 1
  8184. ] );
  8185. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8186. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8187. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8188. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8189. }
  8190. this.geometry = _geometry$1;
  8191. this.material = material;
  8192. this.center = new Vector2( 0.5, 0.5 );
  8193. }
  8194. raycast( raycaster, intersects ) {
  8195. if ( raycaster.camera === null ) {
  8196. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8197. }
  8198. _worldScale.setFromMatrixScale( this.matrixWorld );
  8199. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8200. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8201. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8202. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8203. _worldScale.multiplyScalar( - _mvPosition.z );
  8204. }
  8205. const rotation = this.material.rotation;
  8206. let sin, cos;
  8207. if ( rotation !== 0 ) {
  8208. cos = Math.cos( rotation );
  8209. sin = Math.sin( rotation );
  8210. }
  8211. const center = this.center;
  8212. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8213. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8214. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8215. _uvA.set( 0, 0 );
  8216. _uvB.set( 1, 0 );
  8217. _uvC.set( 1, 1 );
  8218. // check first triangle
  8219. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8220. if ( intersect === null ) {
  8221. // check second triangle
  8222. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8223. _uvB.set( 0, 1 );
  8224. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8225. if ( intersect === null ) {
  8226. return;
  8227. }
  8228. }
  8229. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8230. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8231. intersects.push( {
  8232. distance: distance,
  8233. point: _intersectPoint.clone(),
  8234. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8235. face: null,
  8236. object: this
  8237. } );
  8238. }
  8239. copy( source, recursive ) {
  8240. super.copy( source, recursive );
  8241. if ( source.center !== undefined ) this.center.copy( source.center );
  8242. this.material = source.material;
  8243. return this;
  8244. }
  8245. }
  8246. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8247. // compute position in camera space
  8248. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8249. // to check if rotation is not zero
  8250. if ( sin !== undefined ) {
  8251. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8252. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8253. } else {
  8254. _rotatedPosition.copy( _alignedPosition );
  8255. }
  8256. vertexPosition.copy( mvPosition );
  8257. vertexPosition.x += _rotatedPosition.x;
  8258. vertexPosition.y += _rotatedPosition.y;
  8259. // transform to world space
  8260. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8261. }
  8262. const _v1$2 = /*@__PURE__*/ new Vector3();
  8263. const _v2$1 = /*@__PURE__*/ new Vector3();
  8264. class LOD extends Object3D {
  8265. constructor() {
  8266. super();
  8267. this._currentLevel = 0;
  8268. this.type = 'LOD';
  8269. Object.defineProperties( this, {
  8270. levels: {
  8271. enumerable: true,
  8272. value: []
  8273. },
  8274. isLOD: {
  8275. value: true,
  8276. }
  8277. } );
  8278. this.autoUpdate = true;
  8279. }
  8280. copy( source ) {
  8281. super.copy( source, false );
  8282. const levels = source.levels;
  8283. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8284. const level = levels[ i ];
  8285. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8286. }
  8287. this.autoUpdate = source.autoUpdate;
  8288. return this;
  8289. }
  8290. addLevel( object, distance = 0, hysteresis = 0 ) {
  8291. distance = Math.abs( distance );
  8292. const levels = this.levels;
  8293. let l;
  8294. for ( l = 0; l < levels.length; l ++ ) {
  8295. if ( distance < levels[ l ].distance ) {
  8296. break;
  8297. }
  8298. }
  8299. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8300. this.add( object );
  8301. return this;
  8302. }
  8303. getCurrentLevel() {
  8304. return this._currentLevel;
  8305. }
  8306. getObjectForDistance( distance ) {
  8307. const levels = this.levels;
  8308. if ( levels.length > 0 ) {
  8309. let i, l;
  8310. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8311. let levelDistance = levels[ i ].distance;
  8312. if ( levels[ i ].object.visible ) {
  8313. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8314. }
  8315. if ( distance < levelDistance ) {
  8316. break;
  8317. }
  8318. }
  8319. return levels[ i - 1 ].object;
  8320. }
  8321. return null;
  8322. }
  8323. raycast( raycaster, intersects ) {
  8324. const levels = this.levels;
  8325. if ( levels.length > 0 ) {
  8326. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8327. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8328. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8329. }
  8330. }
  8331. update( camera ) {
  8332. const levels = this.levels;
  8333. if ( levels.length > 1 ) {
  8334. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8335. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8336. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8337. levels[ 0 ].object.visible = true;
  8338. let i, l;
  8339. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8340. let levelDistance = levels[ i ].distance;
  8341. if ( levels[ i ].object.visible ) {
  8342. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8343. }
  8344. if ( distance >= levelDistance ) {
  8345. levels[ i - 1 ].object.visible = false;
  8346. levels[ i ].object.visible = true;
  8347. } else {
  8348. break;
  8349. }
  8350. }
  8351. this._currentLevel = i - 1;
  8352. for ( ; i < l; i ++ ) {
  8353. levels[ i ].object.visible = false;
  8354. }
  8355. }
  8356. }
  8357. toJSON( meta ) {
  8358. const data = super.toJSON( meta );
  8359. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8360. data.object.levels = [];
  8361. const levels = this.levels;
  8362. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8363. const level = levels[ i ];
  8364. data.object.levels.push( {
  8365. object: level.object.uuid,
  8366. distance: level.distance,
  8367. hysteresis: level.hysteresis
  8368. } );
  8369. }
  8370. return data;
  8371. }
  8372. }
  8373. const _basePosition = /*@__PURE__*/ new Vector3();
  8374. const _skinIndex = /*@__PURE__*/ new Vector4();
  8375. const _skinWeight = /*@__PURE__*/ new Vector4();
  8376. const _vector3$1 = /*@__PURE__*/ new Vector3();
  8377. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8378. const _vertex = /*@__PURE__*/ new Vector3();
  8379. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8380. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8381. const _ray$2 = /*@__PURE__*/ new Ray();
  8382. class SkinnedMesh extends Mesh {
  8383. constructor( geometry, material ) {
  8384. super( geometry, material );
  8385. this.isSkinnedMesh = true;
  8386. this.type = 'SkinnedMesh';
  8387. this.bindMode = AttachedBindMode;
  8388. this.bindMatrix = new Matrix4();
  8389. this.bindMatrixInverse = new Matrix4();
  8390. this.boundingBox = null;
  8391. this.boundingSphere = null;
  8392. }
  8393. computeBoundingBox() {
  8394. const geometry = this.geometry;
  8395. if ( this.boundingBox === null ) {
  8396. this.boundingBox = new Box3();
  8397. }
  8398. this.boundingBox.makeEmpty();
  8399. const positionAttribute = geometry.getAttribute( 'position' );
  8400. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8401. this.getVertexPosition( i, _vertex );
  8402. this.boundingBox.expandByPoint( _vertex );
  8403. }
  8404. }
  8405. computeBoundingSphere() {
  8406. const geometry = this.geometry;
  8407. if ( this.boundingSphere === null ) {
  8408. this.boundingSphere = new Sphere();
  8409. }
  8410. this.boundingSphere.makeEmpty();
  8411. const positionAttribute = geometry.getAttribute( 'position' );
  8412. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8413. this.getVertexPosition( i, _vertex );
  8414. this.boundingSphere.expandByPoint( _vertex );
  8415. }
  8416. }
  8417. copy( source, recursive ) {
  8418. super.copy( source, recursive );
  8419. this.bindMode = source.bindMode;
  8420. this.bindMatrix.copy( source.bindMatrix );
  8421. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8422. this.skeleton = source.skeleton;
  8423. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8424. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8425. return this;
  8426. }
  8427. raycast( raycaster, intersects ) {
  8428. const material = this.material;
  8429. const matrixWorld = this.matrixWorld;
  8430. if ( material === undefined ) return;
  8431. // test with bounding sphere in world space
  8432. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8433. _sphere$5.copy( this.boundingSphere );
  8434. _sphere$5.applyMatrix4( matrixWorld );
  8435. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8436. // convert ray to local space of skinned mesh
  8437. _inverseMatrix$2.copy( matrixWorld ).invert();
  8438. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8439. // test with bounding box in local space
  8440. if ( this.boundingBox !== null ) {
  8441. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8442. }
  8443. // test for intersections with geometry
  8444. this._computeIntersections( raycaster, intersects, _ray$2 );
  8445. }
  8446. getVertexPosition( index, target ) {
  8447. super.getVertexPosition( index, target );
  8448. this.applyBoneTransform( index, target );
  8449. return target;
  8450. }
  8451. bind( skeleton, bindMatrix ) {
  8452. this.skeleton = skeleton;
  8453. if ( bindMatrix === undefined ) {
  8454. this.updateMatrixWorld( true );
  8455. this.skeleton.calculateInverses();
  8456. bindMatrix = this.matrixWorld;
  8457. }
  8458. this.bindMatrix.copy( bindMatrix );
  8459. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8460. }
  8461. pose() {
  8462. this.skeleton.pose();
  8463. }
  8464. normalizeSkinWeights() {
  8465. const vector = new Vector4();
  8466. const skinWeight = this.geometry.attributes.skinWeight;
  8467. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8468. vector.fromBufferAttribute( skinWeight, i );
  8469. const scale = 1.0 / vector.manhattanLength();
  8470. if ( scale !== Infinity ) {
  8471. vector.multiplyScalar( scale );
  8472. } else {
  8473. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8474. }
  8475. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8476. }
  8477. }
  8478. updateMatrixWorld( force ) {
  8479. super.updateMatrixWorld( force );
  8480. if ( this.bindMode === AttachedBindMode ) {
  8481. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8482. } else if ( this.bindMode === DetachedBindMode ) {
  8483. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8484. } else {
  8485. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8486. }
  8487. }
  8488. applyBoneTransform( index, vector ) {
  8489. const skeleton = this.skeleton;
  8490. const geometry = this.geometry;
  8491. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8492. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8493. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8494. vector.set( 0, 0, 0 );
  8495. for ( let i = 0; i < 4; i ++ ) {
  8496. const weight = _skinWeight.getComponent( i );
  8497. if ( weight !== 0 ) {
  8498. const boneIndex = _skinIndex.getComponent( i );
  8499. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8500. vector.addScaledVector( _vector3$1.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8501. }
  8502. }
  8503. return vector.applyMatrix4( this.bindMatrixInverse );
  8504. }
  8505. }
  8506. class Bone extends Object3D {
  8507. constructor() {
  8508. super();
  8509. this.isBone = true;
  8510. this.type = 'Bone';
  8511. }
  8512. }
  8513. class DataTexture extends Texture {
  8514. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8515. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8516. this.isDataTexture = true;
  8517. this.image = { data: data, width: width, height: height };
  8518. this.generateMipmaps = false;
  8519. this.flipY = false;
  8520. this.unpackAlignment = 1;
  8521. }
  8522. }
  8523. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8524. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8525. class Skeleton {
  8526. constructor( bones = [], boneInverses = [] ) {
  8527. this.uuid = generateUUID();
  8528. this.bones = bones.slice( 0 );
  8529. this.boneInverses = boneInverses;
  8530. this.boneMatrices = null;
  8531. this.boneTexture = null;
  8532. this.init();
  8533. }
  8534. init() {
  8535. const bones = this.bones;
  8536. const boneInverses = this.boneInverses;
  8537. this.boneMatrices = new Float32Array( bones.length * 16 );
  8538. // calculate inverse bone matrices if necessary
  8539. if ( boneInverses.length === 0 ) {
  8540. this.calculateInverses();
  8541. } else {
  8542. // handle special case
  8543. if ( bones.length !== boneInverses.length ) {
  8544. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8545. this.boneInverses = [];
  8546. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8547. this.boneInverses.push( new Matrix4() );
  8548. }
  8549. }
  8550. }
  8551. }
  8552. calculateInverses() {
  8553. this.boneInverses.length = 0;
  8554. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8555. const inverse = new Matrix4();
  8556. if ( this.bones[ i ] ) {
  8557. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8558. }
  8559. this.boneInverses.push( inverse );
  8560. }
  8561. }
  8562. pose() {
  8563. // recover the bind-time world matrices
  8564. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8565. const bone = this.bones[ i ];
  8566. if ( bone ) {
  8567. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8568. }
  8569. }
  8570. // compute the local matrices, positions, rotations and scales
  8571. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8572. const bone = this.bones[ i ];
  8573. if ( bone ) {
  8574. if ( bone.parent && bone.parent.isBone ) {
  8575. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8576. bone.matrix.multiply( bone.matrixWorld );
  8577. } else {
  8578. bone.matrix.copy( bone.matrixWorld );
  8579. }
  8580. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8581. }
  8582. }
  8583. }
  8584. update() {
  8585. const bones = this.bones;
  8586. const boneInverses = this.boneInverses;
  8587. const boneMatrices = this.boneMatrices;
  8588. const boneTexture = this.boneTexture;
  8589. // flatten bone matrices to array
  8590. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8591. // compute the offset between the current and the original transform
  8592. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8593. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8594. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8595. }
  8596. if ( boneTexture !== null ) {
  8597. boneTexture.needsUpdate = true;
  8598. }
  8599. }
  8600. clone() {
  8601. return new Skeleton( this.bones, this.boneInverses );
  8602. }
  8603. computeBoneTexture() {
  8604. // layout (1 matrix = 4 pixels)
  8605. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8606. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8607. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8608. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8609. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8610. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8611. size = Math.ceil( size / 4 ) * 4;
  8612. size = Math.max( size, 4 );
  8613. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8614. boneMatrices.set( this.boneMatrices ); // copy current values
  8615. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8616. boneTexture.needsUpdate = true;
  8617. this.boneMatrices = boneMatrices;
  8618. this.boneTexture = boneTexture;
  8619. return this;
  8620. }
  8621. getBoneByName( name ) {
  8622. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8623. const bone = this.bones[ i ];
  8624. if ( bone.name === name ) {
  8625. return bone;
  8626. }
  8627. }
  8628. return undefined;
  8629. }
  8630. dispose( ) {
  8631. if ( this.boneTexture !== null ) {
  8632. this.boneTexture.dispose();
  8633. this.boneTexture = null;
  8634. }
  8635. }
  8636. fromJSON( json, bones ) {
  8637. this.uuid = json.uuid;
  8638. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8639. const uuid = json.bones[ i ];
  8640. let bone = bones[ uuid ];
  8641. if ( bone === undefined ) {
  8642. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8643. bone = new Bone();
  8644. }
  8645. this.bones.push( bone );
  8646. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8647. }
  8648. this.init();
  8649. return this;
  8650. }
  8651. toJSON() {
  8652. const data = {
  8653. metadata: {
  8654. version: 4.6,
  8655. type: 'Skeleton',
  8656. generator: 'Skeleton.toJSON'
  8657. },
  8658. bones: [],
  8659. boneInverses: []
  8660. };
  8661. data.uuid = this.uuid;
  8662. const bones = this.bones;
  8663. const boneInverses = this.boneInverses;
  8664. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8665. const bone = bones[ i ];
  8666. data.bones.push( bone.uuid );
  8667. const boneInverse = boneInverses[ i ];
  8668. data.boneInverses.push( boneInverse.toArray() );
  8669. }
  8670. return data;
  8671. }
  8672. }
  8673. class InstancedBufferAttribute extends BufferAttribute {
  8674. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8675. super( array, itemSize, normalized );
  8676. this.isInstancedBufferAttribute = true;
  8677. this.meshPerAttribute = meshPerAttribute;
  8678. }
  8679. copy( source ) {
  8680. super.copy( source );
  8681. this.meshPerAttribute = source.meshPerAttribute;
  8682. return this;
  8683. }
  8684. toJSON() {
  8685. const data = super.toJSON();
  8686. data.meshPerAttribute = this.meshPerAttribute;
  8687. data.isInstancedBufferAttribute = true;
  8688. return data;
  8689. }
  8690. }
  8691. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8692. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8693. const _instanceIntersects = [];
  8694. const _box3 = /*@__PURE__*/ new Box3();
  8695. const _identity = /*@__PURE__*/ new Matrix4();
  8696. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8697. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8698. class InstancedMesh extends Mesh {
  8699. constructor( geometry, material, count ) {
  8700. super( geometry, material );
  8701. this.isInstancedMesh = true;
  8702. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8703. this.instanceColor = null;
  8704. this.morphTexture = null;
  8705. this.count = count;
  8706. this.boundingBox = null;
  8707. this.boundingSphere = null;
  8708. for ( let i = 0; i < count; i ++ ) {
  8709. this.setMatrixAt( i, _identity );
  8710. }
  8711. }
  8712. computeBoundingBox() {
  8713. const geometry = this.geometry;
  8714. const count = this.count;
  8715. if ( this.boundingBox === null ) {
  8716. this.boundingBox = new Box3();
  8717. }
  8718. if ( geometry.boundingBox === null ) {
  8719. geometry.computeBoundingBox();
  8720. }
  8721. this.boundingBox.makeEmpty();
  8722. for ( let i = 0; i < count; i ++ ) {
  8723. this.getMatrixAt( i, _instanceLocalMatrix );
  8724. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8725. this.boundingBox.union( _box3 );
  8726. }
  8727. }
  8728. computeBoundingSphere() {
  8729. const geometry = this.geometry;
  8730. const count = this.count;
  8731. if ( this.boundingSphere === null ) {
  8732. this.boundingSphere = new Sphere();
  8733. }
  8734. if ( geometry.boundingSphere === null ) {
  8735. geometry.computeBoundingSphere();
  8736. }
  8737. this.boundingSphere.makeEmpty();
  8738. for ( let i = 0; i < count; i ++ ) {
  8739. this.getMatrixAt( i, _instanceLocalMatrix );
  8740. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8741. this.boundingSphere.union( _sphere$4 );
  8742. }
  8743. }
  8744. copy( source, recursive ) {
  8745. super.copy( source, recursive );
  8746. this.instanceMatrix.copy( source.instanceMatrix );
  8747. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8748. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8749. this.count = source.count;
  8750. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8751. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8752. return this;
  8753. }
  8754. getColorAt( index, color ) {
  8755. color.fromArray( this.instanceColor.array, index * 3 );
  8756. }
  8757. getMatrixAt( index, matrix ) {
  8758. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8759. }
  8760. getMorphAt( index, object ) {
  8761. const objectInfluences = object.morphTargetInfluences;
  8762. const array = this.morphTexture.source.data.data;
  8763. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8764. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8765. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8766. objectInfluences[ i ] = array[ dataIndex + i ];
  8767. }
  8768. }
  8769. raycast( raycaster, intersects ) {
  8770. const matrixWorld = this.matrixWorld;
  8771. const raycastTimes = this.count;
  8772. _mesh$1.geometry = this.geometry;
  8773. _mesh$1.material = this.material;
  8774. if ( _mesh$1.material === undefined ) return;
  8775. // test with bounding sphere first
  8776. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8777. _sphere$4.copy( this.boundingSphere );
  8778. _sphere$4.applyMatrix4( matrixWorld );
  8779. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8780. // now test each instance
  8781. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8782. // calculate the world matrix for each instance
  8783. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8784. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8785. // the mesh represents this single instance
  8786. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8787. _mesh$1.raycast( raycaster, _instanceIntersects );
  8788. // process the result of raycast
  8789. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8790. const intersect = _instanceIntersects[ i ];
  8791. intersect.instanceId = instanceId;
  8792. intersect.object = this;
  8793. intersects.push( intersect );
  8794. }
  8795. _instanceIntersects.length = 0;
  8796. }
  8797. }
  8798. setColorAt( index, color ) {
  8799. if ( this.instanceColor === null ) {
  8800. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8801. }
  8802. color.toArray( this.instanceColor.array, index * 3 );
  8803. }
  8804. setMatrixAt( index, matrix ) {
  8805. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8806. }
  8807. setMorphAt( index, object ) {
  8808. const objectInfluences = object.morphTargetInfluences;
  8809. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8810. if ( this.morphTexture === null ) {
  8811. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8812. }
  8813. const array = this.morphTexture.source.data.data;
  8814. let morphInfluencesSum = 0;
  8815. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8816. morphInfluencesSum += objectInfluences[ i ];
  8817. }
  8818. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8819. const dataIndex = len * index;
  8820. array[ dataIndex ] = morphBaseInfluence;
  8821. array.set( objectInfluences, dataIndex + 1 );
  8822. }
  8823. updateMorphTargets() {
  8824. }
  8825. dispose() {
  8826. this.dispatchEvent( { type: 'dispose' } );
  8827. if ( this.morphTexture !== null ) {
  8828. this.morphTexture.dispose();
  8829. this.morphTexture = null;
  8830. }
  8831. return this;
  8832. }
  8833. }
  8834. const _vector1 = /*@__PURE__*/ new Vector3();
  8835. const _vector2 = /*@__PURE__*/ new Vector3();
  8836. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8837. class Plane {
  8838. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8839. this.isPlane = true;
  8840. // normal is assumed to be normalized
  8841. this.normal = normal;
  8842. this.constant = constant;
  8843. }
  8844. set( normal, constant ) {
  8845. this.normal.copy( normal );
  8846. this.constant = constant;
  8847. return this;
  8848. }
  8849. setComponents( x, y, z, w ) {
  8850. this.normal.set( x, y, z );
  8851. this.constant = w;
  8852. return this;
  8853. }
  8854. setFromNormalAndCoplanarPoint( normal, point ) {
  8855. this.normal.copy( normal );
  8856. this.constant = - point.dot( this.normal );
  8857. return this;
  8858. }
  8859. setFromCoplanarPoints( a, b, c ) {
  8860. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8861. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8862. this.setFromNormalAndCoplanarPoint( normal, a );
  8863. return this;
  8864. }
  8865. copy( plane ) {
  8866. this.normal.copy( plane.normal );
  8867. this.constant = plane.constant;
  8868. return this;
  8869. }
  8870. normalize() {
  8871. // Note: will lead to a divide by zero if the plane is invalid.
  8872. const inverseNormalLength = 1.0 / this.normal.length();
  8873. this.normal.multiplyScalar( inverseNormalLength );
  8874. this.constant *= inverseNormalLength;
  8875. return this;
  8876. }
  8877. negate() {
  8878. this.constant *= - 1;
  8879. this.normal.negate();
  8880. return this;
  8881. }
  8882. distanceToPoint( point ) {
  8883. return this.normal.dot( point ) + this.constant;
  8884. }
  8885. distanceToSphere( sphere ) {
  8886. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8887. }
  8888. projectPoint( point, target ) {
  8889. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8890. }
  8891. intersectLine( line, target ) {
  8892. const direction = line.delta( _vector1 );
  8893. const denominator = this.normal.dot( direction );
  8894. if ( denominator === 0 ) {
  8895. // line is coplanar, return origin
  8896. if ( this.distanceToPoint( line.start ) === 0 ) {
  8897. return target.copy( line.start );
  8898. }
  8899. // Unsure if this is the correct method to handle this case.
  8900. return null;
  8901. }
  8902. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8903. if ( t < 0 || t > 1 ) {
  8904. return null;
  8905. }
  8906. return target.copy( line.start ).addScaledVector( direction, t );
  8907. }
  8908. intersectsLine( line ) {
  8909. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8910. const startSign = this.distanceToPoint( line.start );
  8911. const endSign = this.distanceToPoint( line.end );
  8912. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8913. }
  8914. intersectsBox( box ) {
  8915. return box.intersectsPlane( this );
  8916. }
  8917. intersectsSphere( sphere ) {
  8918. return sphere.intersectsPlane( this );
  8919. }
  8920. coplanarPoint( target ) {
  8921. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8922. }
  8923. applyMatrix4( matrix, optionalNormalMatrix ) {
  8924. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8925. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8926. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8927. this.constant = - referencePoint.dot( normal );
  8928. return this;
  8929. }
  8930. translate( offset ) {
  8931. this.constant -= offset.dot( this.normal );
  8932. return this;
  8933. }
  8934. equals( plane ) {
  8935. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8936. }
  8937. clone() {
  8938. return new this.constructor().copy( this );
  8939. }
  8940. }
  8941. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8942. const _vector$6 = /*@__PURE__*/ new Vector3();
  8943. class Frustum {
  8944. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8945. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8946. }
  8947. set( p0, p1, p2, p3, p4, p5 ) {
  8948. const planes = this.planes;
  8949. planes[ 0 ].copy( p0 );
  8950. planes[ 1 ].copy( p1 );
  8951. planes[ 2 ].copy( p2 );
  8952. planes[ 3 ].copy( p3 );
  8953. planes[ 4 ].copy( p4 );
  8954. planes[ 5 ].copy( p5 );
  8955. return this;
  8956. }
  8957. copy( frustum ) {
  8958. const planes = this.planes;
  8959. for ( let i = 0; i < 6; i ++ ) {
  8960. planes[ i ].copy( frustum.planes[ i ] );
  8961. }
  8962. return this;
  8963. }
  8964. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8965. const planes = this.planes;
  8966. const me = m.elements;
  8967. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8968. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8969. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8970. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8971. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8972. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8973. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8974. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8975. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8976. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8977. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8978. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8979. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8980. } else {
  8981. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8982. }
  8983. return this;
  8984. }
  8985. intersectsObject( object ) {
  8986. if ( object.boundingSphere !== undefined ) {
  8987. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8988. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8989. } else {
  8990. const geometry = object.geometry;
  8991. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8992. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8993. }
  8994. return this.intersectsSphere( _sphere$3 );
  8995. }
  8996. intersectsSprite( sprite ) {
  8997. _sphere$3.center.set( 0, 0, 0 );
  8998. _sphere$3.radius = 0.7071067811865476;
  8999. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9000. return this.intersectsSphere( _sphere$3 );
  9001. }
  9002. intersectsSphere( sphere ) {
  9003. const planes = this.planes;
  9004. const center = sphere.center;
  9005. const negRadius = - sphere.radius;
  9006. for ( let i = 0; i < 6; i ++ ) {
  9007. const distance = planes[ i ].distanceToPoint( center );
  9008. if ( distance < negRadius ) {
  9009. return false;
  9010. }
  9011. }
  9012. return true;
  9013. }
  9014. intersectsBox( box ) {
  9015. const planes = this.planes;
  9016. for ( let i = 0; i < 6; i ++ ) {
  9017. const plane = planes[ i ];
  9018. // corner at max distance
  9019. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9020. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9021. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9022. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9023. return false;
  9024. }
  9025. }
  9026. return true;
  9027. }
  9028. containsPoint( point ) {
  9029. const planes = this.planes;
  9030. for ( let i = 0; i < 6; i ++ ) {
  9031. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9032. return false;
  9033. }
  9034. }
  9035. return true;
  9036. }
  9037. clone() {
  9038. return new this.constructor().copy( this );
  9039. }
  9040. }
  9041. function sortOpaque( a, b ) {
  9042. return a.z - b.z;
  9043. }
  9044. function sortTransparent( a, b ) {
  9045. return b.z - a.z;
  9046. }
  9047. class MultiDrawRenderList {
  9048. constructor() {
  9049. this.index = 0;
  9050. this.pool = [];
  9051. this.list = [];
  9052. }
  9053. push( drawRange, z, index ) {
  9054. const pool = this.pool;
  9055. const list = this.list;
  9056. if ( this.index >= pool.length ) {
  9057. pool.push( {
  9058. start: - 1,
  9059. count: - 1,
  9060. z: - 1,
  9061. index: - 1,
  9062. } );
  9063. }
  9064. const item = pool[ this.index ];
  9065. list.push( item );
  9066. this.index ++;
  9067. item.start = drawRange.start;
  9068. item.count = drawRange.count;
  9069. item.z = z;
  9070. item.index = index;
  9071. }
  9072. reset() {
  9073. this.list.length = 0;
  9074. this.index = 0;
  9075. }
  9076. }
  9077. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9078. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9079. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9080. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9081. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9082. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9083. const _box$1 = /*@__PURE__*/ new Box3();
  9084. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9085. const _vector$5 = /*@__PURE__*/ new Vector3();
  9086. const _forward = /*@__PURE__*/ new Vector3();
  9087. const _temp = /*@__PURE__*/ new Vector3();
  9088. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9089. const _mesh = /*@__PURE__*/ new Mesh();
  9090. const _batchIntersects = [];
  9091. // @TODO: SkinnedMesh support?
  9092. // @TODO: geometry.groups support?
  9093. // @TODO: geometry.drawRange support?
  9094. // @TODO: geometry.morphAttributes support?
  9095. // @TODO: Support uniform parameter per geometry
  9096. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9097. // copies data from attribute "src" into "target" starting at "targetOffset"
  9098. function copyAttributeData( src, target, targetOffset = 0 ) {
  9099. const itemSize = target.itemSize;
  9100. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9101. // use the component getters and setters if the array data cannot
  9102. // be copied directly
  9103. const vertexCount = src.count;
  9104. for ( let i = 0; i < vertexCount; i ++ ) {
  9105. for ( let c = 0; c < itemSize; c ++ ) {
  9106. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9107. }
  9108. }
  9109. } else {
  9110. // faster copy approach using typed array set function
  9111. target.array.set( src.array, targetOffset * itemSize );
  9112. }
  9113. target.needsUpdate = true;
  9114. }
  9115. class BatchedMesh extends Mesh {
  9116. get maxInstanceCount() {
  9117. return this._maxInstanceCount;
  9118. }
  9119. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9120. super( new BufferGeometry(), material );
  9121. this.isBatchedMesh = true;
  9122. this.perObjectFrustumCulled = true;
  9123. this.sortObjects = true;
  9124. this.boundingBox = null;
  9125. this.boundingSphere = null;
  9126. this.customSort = null;
  9127. // stores visible, active, and geometry id per object
  9128. this._drawInfo = [];
  9129. // geometry information
  9130. this._drawRanges = [];
  9131. this._reservedRanges = [];
  9132. this._bounds = [];
  9133. this._maxInstanceCount = maxInstanceCount;
  9134. this._maxVertexCount = maxVertexCount;
  9135. this._maxIndexCount = maxIndexCount;
  9136. this._geometryInitialized = false;
  9137. this._geometryCount = 0;
  9138. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9139. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9140. this._multiDrawCount = 0;
  9141. this._multiDrawInstances = null;
  9142. this._visibilityChanged = true;
  9143. // Local matrix per geometry by using data texture
  9144. this._matricesTexture = null;
  9145. this._indirectTexture = null;
  9146. this._colorsTexture = null;
  9147. this._initMatricesTexture();
  9148. this._initIndirectTexture();
  9149. }
  9150. _initMatricesTexture() {
  9151. // layout (1 matrix = 4 pixels)
  9152. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9153. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9154. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9155. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9156. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9157. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9158. size = Math.ceil( size / 4 ) * 4;
  9159. size = Math.max( size, 4 );
  9160. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9161. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9162. this._matricesTexture = matricesTexture;
  9163. }
  9164. _initIndirectTexture() {
  9165. let size = Math.sqrt( this._maxInstanceCount );
  9166. size = Math.ceil( size );
  9167. const indirectArray = new Uint32Array( size * size );
  9168. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9169. this._indirectTexture = indirectTexture;
  9170. }
  9171. _initColorsTexture() {
  9172. let size = Math.sqrt( this._maxIndexCount );
  9173. size = Math.ceil( size );
  9174. // 4 floats per RGBA pixel initialized to white
  9175. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9176. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9177. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9178. this._colorsTexture = colorsTexture;
  9179. }
  9180. _initializeGeometry( reference ) {
  9181. const geometry = this.geometry;
  9182. const maxVertexCount = this._maxVertexCount;
  9183. const maxIndexCount = this._maxIndexCount;
  9184. if ( this._geometryInitialized === false ) {
  9185. for ( const attributeName in reference.attributes ) {
  9186. const srcAttribute = reference.getAttribute( attributeName );
  9187. const { array, itemSize, normalized } = srcAttribute;
  9188. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9189. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9190. geometry.setAttribute( attributeName, dstAttribute );
  9191. }
  9192. if ( reference.getIndex() !== null ) {
  9193. // Reserve last u16 index for primitive restart.
  9194. const indexArray = maxVertexCount > 65535
  9195. ? new Uint32Array( maxIndexCount )
  9196. : new Uint16Array( maxIndexCount );
  9197. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9198. }
  9199. this._geometryInitialized = true;
  9200. }
  9201. }
  9202. // Make sure the geometry is compatible with the existing combined geometry attributes
  9203. _validateGeometry( geometry ) {
  9204. // check to ensure the geometries are using consistent attributes and indices
  9205. const batchGeometry = this.geometry;
  9206. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9207. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9208. }
  9209. for ( const attributeName in batchGeometry.attributes ) {
  9210. if ( ! geometry.hasAttribute( attributeName ) ) {
  9211. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9212. }
  9213. const srcAttribute = geometry.getAttribute( attributeName );
  9214. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9215. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9216. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9217. }
  9218. }
  9219. }
  9220. setCustomSort( func ) {
  9221. this.customSort = func;
  9222. return this;
  9223. }
  9224. computeBoundingBox() {
  9225. if ( this.boundingBox === null ) {
  9226. this.boundingBox = new Box3();
  9227. }
  9228. const geometryCount = this._geometryCount;
  9229. const boundingBox = this.boundingBox;
  9230. const drawInfo = this._drawInfo;
  9231. boundingBox.makeEmpty();
  9232. for ( let i = 0; i < geometryCount; i ++ ) {
  9233. if ( drawInfo[ i ].active === false ) continue;
  9234. const geometryId = drawInfo[ i ].geometryIndex;
  9235. this.getMatrixAt( i, _matrix$1 );
  9236. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9237. boundingBox.union( _box$1 );
  9238. }
  9239. }
  9240. computeBoundingSphere() {
  9241. if ( this.boundingSphere === null ) {
  9242. this.boundingSphere = new Sphere();
  9243. }
  9244. const boundingSphere = this.boundingSphere;
  9245. const drawInfo = this._drawInfo;
  9246. boundingSphere.makeEmpty();
  9247. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9248. if ( drawInfo[ i ].active === false ) continue;
  9249. const geometryId = drawInfo[ i ].geometryIndex;
  9250. this.getMatrixAt( i, _matrix$1 );
  9251. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9252. boundingSphere.union( _sphere$2 );
  9253. }
  9254. }
  9255. addInstance( geometryId ) {
  9256. // ensure we're not over geometry
  9257. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9258. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9259. }
  9260. this._drawInfo.push( {
  9261. visible: true,
  9262. active: true,
  9263. geometryIndex: geometryId,
  9264. } );
  9265. // initialize the matrix
  9266. const drawId = this._drawInfo.length - 1;
  9267. const matricesTexture = this._matricesTexture;
  9268. const matricesArray = matricesTexture.image.data;
  9269. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9270. matricesTexture.needsUpdate = true;
  9271. const colorsTexture = this._colorsTexture;
  9272. if ( colorsTexture ) {
  9273. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9274. colorsTexture.needsUpdate = true;
  9275. }
  9276. return drawId;
  9277. }
  9278. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9279. this._initializeGeometry( geometry );
  9280. this._validateGeometry( geometry );
  9281. // ensure we're not over geometry
  9282. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9283. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9284. }
  9285. // get the necessary range fo the geometry
  9286. const reservedRange = {
  9287. vertexStart: - 1,
  9288. vertexCount: - 1,
  9289. indexStart: - 1,
  9290. indexCount: - 1,
  9291. };
  9292. let lastRange = null;
  9293. const reservedRanges = this._reservedRanges;
  9294. const drawRanges = this._drawRanges;
  9295. const bounds = this._bounds;
  9296. if ( this._geometryCount !== 0 ) {
  9297. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9298. }
  9299. if ( vertexCount === - 1 ) {
  9300. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9301. } else {
  9302. reservedRange.vertexCount = vertexCount;
  9303. }
  9304. if ( lastRange === null ) {
  9305. reservedRange.vertexStart = 0;
  9306. } else {
  9307. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9308. }
  9309. const index = geometry.getIndex();
  9310. const hasIndex = index !== null;
  9311. if ( hasIndex ) {
  9312. if ( indexCount === - 1 ) {
  9313. reservedRange.indexCount = index.count;
  9314. } else {
  9315. reservedRange.indexCount = indexCount;
  9316. }
  9317. if ( lastRange === null ) {
  9318. reservedRange.indexStart = 0;
  9319. } else {
  9320. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9321. }
  9322. }
  9323. if (
  9324. reservedRange.indexStart !== - 1 &&
  9325. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9326. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9327. ) {
  9328. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9329. }
  9330. // update id
  9331. const geometryId = this._geometryCount;
  9332. this._geometryCount ++;
  9333. // add the reserved range and draw range objects
  9334. reservedRanges.push( reservedRange );
  9335. drawRanges.push( {
  9336. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9337. count: - 1
  9338. } );
  9339. bounds.push( {
  9340. boxInitialized: false,
  9341. box: new Box3(),
  9342. sphereInitialized: false,
  9343. sphere: new Sphere()
  9344. } );
  9345. // update the geometry
  9346. this.setGeometryAt( geometryId, geometry );
  9347. return geometryId;
  9348. }
  9349. setGeometryAt( geometryId, geometry ) {
  9350. if ( geometryId >= this._geometryCount ) {
  9351. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9352. }
  9353. this._validateGeometry( geometry );
  9354. const batchGeometry = this.geometry;
  9355. const hasIndex = batchGeometry.getIndex() !== null;
  9356. const dstIndex = batchGeometry.getIndex();
  9357. const srcIndex = geometry.getIndex();
  9358. const reservedRange = this._reservedRanges[ geometryId ];
  9359. if (
  9360. hasIndex &&
  9361. srcIndex.count > reservedRange.indexCount ||
  9362. geometry.attributes.position.count > reservedRange.vertexCount
  9363. ) {
  9364. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9365. }
  9366. // copy geometry over
  9367. const vertexStart = reservedRange.vertexStart;
  9368. const vertexCount = reservedRange.vertexCount;
  9369. for ( const attributeName in batchGeometry.attributes ) {
  9370. // copy attribute data
  9371. const srcAttribute = geometry.getAttribute( attributeName );
  9372. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9373. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9374. // fill the rest in with zeroes
  9375. const itemSize = srcAttribute.itemSize;
  9376. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9377. const index = vertexStart + i;
  9378. for ( let c = 0; c < itemSize; c ++ ) {
  9379. dstAttribute.setComponent( index, c, 0 );
  9380. }
  9381. }
  9382. dstAttribute.needsUpdate = true;
  9383. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9384. }
  9385. // copy index
  9386. if ( hasIndex ) {
  9387. const indexStart = reservedRange.indexStart;
  9388. // copy index data over
  9389. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9390. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9391. }
  9392. // fill the rest in with zeroes
  9393. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9394. dstIndex.setX( indexStart + i, vertexStart );
  9395. }
  9396. dstIndex.needsUpdate = true;
  9397. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9398. }
  9399. // store the bounding boxes
  9400. const bound = this._bounds[ geometryId ];
  9401. if ( geometry.boundingBox !== null ) {
  9402. bound.box.copy( geometry.boundingBox );
  9403. bound.boxInitialized = true;
  9404. } else {
  9405. bound.boxInitialized = false;
  9406. }
  9407. if ( geometry.boundingSphere !== null ) {
  9408. bound.sphere.copy( geometry.boundingSphere );
  9409. bound.sphereInitialized = true;
  9410. } else {
  9411. bound.sphereInitialized = false;
  9412. }
  9413. // set drawRange count
  9414. const drawRange = this._drawRanges[ geometryId ];
  9415. const posAttr = geometry.getAttribute( 'position' );
  9416. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9417. this._visibilityChanged = true;
  9418. return geometryId;
  9419. }
  9420. /*
  9421. deleteGeometry( geometryId ) {
  9422. // TODO: delete geometry and associated instances
  9423. }
  9424. */
  9425. /*
  9426. deleteInstance( instanceId ) {
  9427. // Note: User needs to call optimize() afterward to pack the data.
  9428. const drawInfo = this._drawInfo;
  9429. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9430. return this;
  9431. }
  9432. drawInfo[ instanceId ].active = false;
  9433. this._visibilityChanged = true;
  9434. return this;
  9435. }
  9436. */
  9437. // get bounding box and compute it if it doesn't exist
  9438. getBoundingBoxAt( geometryId, target ) {
  9439. if ( geometryId >= this._geometryCount ) {
  9440. return null;
  9441. }
  9442. // compute bounding box
  9443. const bound = this._bounds[ geometryId ];
  9444. const box = bound.box;
  9445. const geometry = this.geometry;
  9446. if ( bound.boxInitialized === false ) {
  9447. box.makeEmpty();
  9448. const index = geometry.index;
  9449. const position = geometry.attributes.position;
  9450. const drawRange = this._drawRanges[ geometryId ];
  9451. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9452. let iv = i;
  9453. if ( index ) {
  9454. iv = index.getX( iv );
  9455. }
  9456. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9457. }
  9458. bound.boxInitialized = true;
  9459. }
  9460. target.copy( box );
  9461. return target;
  9462. }
  9463. // get bounding sphere and compute it if it doesn't exist
  9464. getBoundingSphereAt( geometryId, target ) {
  9465. if ( geometryId >= this._geometryCount ) {
  9466. return null;
  9467. }
  9468. // compute bounding sphere
  9469. const bound = this._bounds[ geometryId ];
  9470. const sphere = bound.sphere;
  9471. const geometry = this.geometry;
  9472. if ( bound.sphereInitialized === false ) {
  9473. sphere.makeEmpty();
  9474. this.getBoundingBoxAt( geometryId, _box$1 );
  9475. _box$1.getCenter( sphere.center );
  9476. const index = geometry.index;
  9477. const position = geometry.attributes.position;
  9478. const drawRange = this._drawRanges[ geometryId ];
  9479. let maxRadiusSq = 0;
  9480. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9481. let iv = i;
  9482. if ( index ) {
  9483. iv = index.getX( iv );
  9484. }
  9485. _vector$5.fromBufferAttribute( position, iv );
  9486. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9487. }
  9488. sphere.radius = Math.sqrt( maxRadiusSq );
  9489. bound.sphereInitialized = true;
  9490. }
  9491. target.copy( sphere );
  9492. return target;
  9493. }
  9494. setMatrixAt( instanceId, matrix ) {
  9495. // @TODO: Map geometryId to index of the arrays because
  9496. // optimize() can make geometryId mismatch the index
  9497. const drawInfo = this._drawInfo;
  9498. const matricesTexture = this._matricesTexture;
  9499. const matricesArray = this._matricesTexture.image.data;
  9500. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9501. return this;
  9502. }
  9503. matrix.toArray( matricesArray, instanceId * 16 );
  9504. matricesTexture.needsUpdate = true;
  9505. return this;
  9506. }
  9507. getMatrixAt( instanceId, matrix ) {
  9508. const drawInfo = this._drawInfo;
  9509. const matricesArray = this._matricesTexture.image.data;
  9510. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9511. return null;
  9512. }
  9513. return matrix.fromArray( matricesArray, instanceId * 16 );
  9514. }
  9515. setColorAt( instanceId, color ) {
  9516. if ( this._colorsTexture === null ) {
  9517. this._initColorsTexture();
  9518. }
  9519. // @TODO: Map id to index of the arrays because
  9520. // optimize() can make id mismatch the index
  9521. const colorsTexture = this._colorsTexture;
  9522. const colorsArray = this._colorsTexture.image.data;
  9523. const drawInfo = this._drawInfo;
  9524. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9525. return this;
  9526. }
  9527. color.toArray( colorsArray, instanceId * 4 );
  9528. colorsTexture.needsUpdate = true;
  9529. return this;
  9530. }
  9531. getColorAt( instanceId, color ) {
  9532. const colorsArray = this._colorsTexture.image.data;
  9533. const drawInfo = this._drawInfo;
  9534. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9535. return null;
  9536. }
  9537. return color.fromArray( colorsArray, instanceId * 4 );
  9538. }
  9539. setVisibleAt( instanceId, value ) {
  9540. // if the geometry is out of range, not active, or visibility state
  9541. // does not change then return early
  9542. const drawInfo = this._drawInfo;
  9543. if (
  9544. instanceId >= drawInfo.length ||
  9545. drawInfo[ instanceId ].active === false ||
  9546. drawInfo[ instanceId ].visible === value
  9547. ) {
  9548. return this;
  9549. }
  9550. drawInfo[ instanceId ].visible = value;
  9551. this._visibilityChanged = true;
  9552. return this;
  9553. }
  9554. getVisibleAt( instanceId ) {
  9555. // return early if the geometry is out of range or not active
  9556. const drawInfo = this._drawInfo;
  9557. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9558. return false;
  9559. }
  9560. return drawInfo[ instanceId ].visible;
  9561. }
  9562. raycast( raycaster, intersects ) {
  9563. const drawInfo = this._drawInfo;
  9564. const drawRanges = this._drawRanges;
  9565. const matrixWorld = this.matrixWorld;
  9566. const batchGeometry = this.geometry;
  9567. // iterate over each geometry
  9568. _mesh.material = this.material;
  9569. _mesh.geometry.index = batchGeometry.index;
  9570. _mesh.geometry.attributes = batchGeometry.attributes;
  9571. if ( _mesh.geometry.boundingBox === null ) {
  9572. _mesh.geometry.boundingBox = new Box3();
  9573. }
  9574. if ( _mesh.geometry.boundingSphere === null ) {
  9575. _mesh.geometry.boundingSphere = new Sphere();
  9576. }
  9577. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9578. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9579. continue;
  9580. }
  9581. const geometryId = drawInfo[ i ].geometryIndex;
  9582. const drawRange = drawRanges[ geometryId ];
  9583. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9584. // ge the intersects
  9585. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9586. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9587. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9588. _mesh.raycast( raycaster, _batchIntersects );
  9589. // add batch id to the intersects
  9590. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9591. const intersect = _batchIntersects[ j ];
  9592. intersect.object = this;
  9593. intersect.batchId = i;
  9594. intersects.push( intersect );
  9595. }
  9596. _batchIntersects.length = 0;
  9597. }
  9598. _mesh.material = null;
  9599. _mesh.geometry.index = null;
  9600. _mesh.geometry.attributes = {};
  9601. _mesh.geometry.setDrawRange( 0, Infinity );
  9602. }
  9603. copy( source ) {
  9604. super.copy( source );
  9605. this.geometry = source.geometry.clone();
  9606. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9607. this.sortObjects = source.sortObjects;
  9608. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9609. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9610. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9611. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9612. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9613. this._bounds = source._bounds.map( bound => ( {
  9614. boxInitialized: bound.boxInitialized,
  9615. box: bound.box.clone(),
  9616. sphereInitialized: bound.sphereInitialized,
  9617. sphere: bound.sphere.clone()
  9618. } ) );
  9619. this._maxInstanceCount = source._maxInstanceCount;
  9620. this._maxVertexCount = source._maxVertexCount;
  9621. this._maxIndexCount = source._maxIndexCount;
  9622. this._geometryInitialized = source._geometryInitialized;
  9623. this._geometryCount = source._geometryCount;
  9624. this._multiDrawCounts = source._multiDrawCounts.slice();
  9625. this._multiDrawStarts = source._multiDrawStarts.slice();
  9626. this._matricesTexture = source._matricesTexture.clone();
  9627. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9628. if ( this._colorsTexture !== null ) {
  9629. this._colorsTexture = source._colorsTexture.clone();
  9630. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9631. }
  9632. return this;
  9633. }
  9634. dispose() {
  9635. // Assuming the geometry is not shared with other meshes
  9636. this.geometry.dispose();
  9637. this._matricesTexture.dispose();
  9638. this._matricesTexture = null;
  9639. this._indirectTexture.dispose();
  9640. this._indirectTexture = null;
  9641. if ( this._colorsTexture !== null ) {
  9642. this._colorsTexture.dispose();
  9643. this._colorsTexture = null;
  9644. }
  9645. return this;
  9646. }
  9647. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9648. // if visibility has not changed and frustum culling and object sorting is not required
  9649. // then skip iterating over all items
  9650. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9651. return;
  9652. }
  9653. // the indexed version of the multi draw function requires specifying the start
  9654. // offset in bytes.
  9655. const index = geometry.getIndex();
  9656. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9657. const drawInfo = this._drawInfo;
  9658. const multiDrawStarts = this._multiDrawStarts;
  9659. const multiDrawCounts = this._multiDrawCounts;
  9660. const drawRanges = this._drawRanges;
  9661. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9662. const indirectTexture = this._indirectTexture;
  9663. const indirectArray = indirectTexture.image.data;
  9664. // prepare the frustum in the local frame
  9665. if ( perObjectFrustumCulled ) {
  9666. _projScreenMatrix$3
  9667. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9668. .multiply( this.matrixWorld );
  9669. _frustum$1.setFromProjectionMatrix(
  9670. _projScreenMatrix$3,
  9671. renderer.coordinateSystem
  9672. );
  9673. }
  9674. let count = 0;
  9675. if ( this.sortObjects ) {
  9676. // get the camera position in the local frame
  9677. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9678. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9679. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9680. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9681. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9682. const geometryId = drawInfo[ i ].geometryIndex;
  9683. // get the bounds in world space
  9684. this.getMatrixAt( i, _matrix$1 );
  9685. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9686. // determine whether the batched geometry is within the frustum
  9687. let culled = false;
  9688. if ( perObjectFrustumCulled ) {
  9689. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9690. }
  9691. if ( ! culled ) {
  9692. // get the distance from camera used for sorting
  9693. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9694. _renderList.push( drawRanges[ geometryId ], z, i );
  9695. }
  9696. }
  9697. }
  9698. // Sort the draw ranges and prep for rendering
  9699. const list = _renderList.list;
  9700. const customSort = this.customSort;
  9701. if ( customSort === null ) {
  9702. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9703. } else {
  9704. customSort.call( this, list, camera );
  9705. }
  9706. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9707. const item = list[ i ];
  9708. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9709. multiDrawCounts[ count ] = item.count;
  9710. indirectArray[ count ] = item.index;
  9711. count ++;
  9712. }
  9713. _renderList.reset();
  9714. } else {
  9715. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9716. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9717. const geometryId = drawInfo[ i ].geometryIndex;
  9718. // determine whether the batched geometry is within the frustum
  9719. let culled = false;
  9720. if ( perObjectFrustumCulled ) {
  9721. // get the bounds in world space
  9722. this.getMatrixAt( i, _matrix$1 );
  9723. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9724. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9725. }
  9726. if ( ! culled ) {
  9727. const range = drawRanges[ geometryId ];
  9728. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9729. multiDrawCounts[ count ] = range.count;
  9730. indirectArray[ count ] = i;
  9731. count ++;
  9732. }
  9733. }
  9734. }
  9735. }
  9736. indirectTexture.needsUpdate = true;
  9737. this._multiDrawCount = count;
  9738. this._visibilityChanged = false;
  9739. }
  9740. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9741. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9742. }
  9743. }
  9744. class LineBasicMaterial extends Material {
  9745. constructor( parameters ) {
  9746. super();
  9747. this.isLineBasicMaterial = true;
  9748. this.type = 'LineBasicMaterial';
  9749. this.color = new Color( 0xffffff );
  9750. this.map = null;
  9751. this.linewidth = 1;
  9752. this.linecap = 'round';
  9753. this.linejoin = 'round';
  9754. this.fog = true;
  9755. this.setValues( parameters );
  9756. }
  9757. copy( source ) {
  9758. super.copy( source );
  9759. this.color.copy( source.color );
  9760. this.map = source.map;
  9761. this.linewidth = source.linewidth;
  9762. this.linecap = source.linecap;
  9763. this.linejoin = source.linejoin;
  9764. this.fog = source.fog;
  9765. return this;
  9766. }
  9767. }
  9768. const _vStart = /*@__PURE__*/ new Vector3();
  9769. const _vEnd = /*@__PURE__*/ new Vector3();
  9770. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9771. const _ray$1 = /*@__PURE__*/ new Ray();
  9772. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9773. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9774. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9775. class Line extends Object3D {
  9776. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9777. super();
  9778. this.isLine = true;
  9779. this.type = 'Line';
  9780. this.geometry = geometry;
  9781. this.material = material;
  9782. this.updateMorphTargets();
  9783. }
  9784. copy( source, recursive ) {
  9785. super.copy( source, recursive );
  9786. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9787. this.geometry = source.geometry;
  9788. return this;
  9789. }
  9790. computeLineDistances() {
  9791. const geometry = this.geometry;
  9792. // we assume non-indexed geometry
  9793. if ( geometry.index === null ) {
  9794. const positionAttribute = geometry.attributes.position;
  9795. const lineDistances = [ 0 ];
  9796. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9797. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9798. _vEnd.fromBufferAttribute( positionAttribute, i );
  9799. lineDistances[ i ] = lineDistances[ i - 1 ];
  9800. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9801. }
  9802. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9803. } else {
  9804. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9805. }
  9806. return this;
  9807. }
  9808. raycast( raycaster, intersects ) {
  9809. const geometry = this.geometry;
  9810. const matrixWorld = this.matrixWorld;
  9811. const threshold = raycaster.params.Line.threshold;
  9812. const drawRange = geometry.drawRange;
  9813. // Checking boundingSphere distance to ray
  9814. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9815. _sphere$1.copy( geometry.boundingSphere );
  9816. _sphere$1.applyMatrix4( matrixWorld );
  9817. _sphere$1.radius += threshold;
  9818. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9819. //
  9820. _inverseMatrix$1.copy( matrixWorld ).invert();
  9821. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9822. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9823. const localThresholdSq = localThreshold * localThreshold;
  9824. const step = this.isLineSegments ? 2 : 1;
  9825. const index = geometry.index;
  9826. const attributes = geometry.attributes;
  9827. const positionAttribute = attributes.position;
  9828. if ( index !== null ) {
  9829. const start = Math.max( 0, drawRange.start );
  9830. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9831. for ( let i = start, l = end - 1; i < l; i += step ) {
  9832. const a = index.getX( i );
  9833. const b = index.getX( i + 1 );
  9834. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9835. if ( intersect ) {
  9836. intersects.push( intersect );
  9837. }
  9838. }
  9839. if ( this.isLineLoop ) {
  9840. const a = index.getX( end - 1 );
  9841. const b = index.getX( start );
  9842. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9843. if ( intersect ) {
  9844. intersects.push( intersect );
  9845. }
  9846. }
  9847. } else {
  9848. const start = Math.max( 0, drawRange.start );
  9849. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9850. for ( let i = start, l = end - 1; i < l; i += step ) {
  9851. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9852. if ( intersect ) {
  9853. intersects.push( intersect );
  9854. }
  9855. }
  9856. if ( this.isLineLoop ) {
  9857. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9858. if ( intersect ) {
  9859. intersects.push( intersect );
  9860. }
  9861. }
  9862. }
  9863. }
  9864. updateMorphTargets() {
  9865. const geometry = this.geometry;
  9866. const morphAttributes = geometry.morphAttributes;
  9867. const keys = Object.keys( morphAttributes );
  9868. if ( keys.length > 0 ) {
  9869. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9870. if ( morphAttribute !== undefined ) {
  9871. this.morphTargetInfluences = [];
  9872. this.morphTargetDictionary = {};
  9873. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9874. const name = morphAttribute[ m ].name || String( m );
  9875. this.morphTargetInfluences.push( 0 );
  9876. this.morphTargetDictionary[ name ] = m;
  9877. }
  9878. }
  9879. }
  9880. }
  9881. }
  9882. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9883. const positionAttribute = object.geometry.attributes.position;
  9884. _vStart.fromBufferAttribute( positionAttribute, a );
  9885. _vEnd.fromBufferAttribute( positionAttribute, b );
  9886. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9887. if ( distSq > thresholdSq ) return;
  9888. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9889. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9890. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9891. return {
  9892. distance: distance,
  9893. // What do we want? intersection point on the ray or on the segment??
  9894. // point: raycaster.ray.at( distance ),
  9895. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9896. index: a,
  9897. face: null,
  9898. faceIndex: null,
  9899. object: object
  9900. };
  9901. }
  9902. const _start = /*@__PURE__*/ new Vector3();
  9903. const _end = /*@__PURE__*/ new Vector3();
  9904. class LineSegments extends Line {
  9905. constructor( geometry, material ) {
  9906. super( geometry, material );
  9907. this.isLineSegments = true;
  9908. this.type = 'LineSegments';
  9909. }
  9910. computeLineDistances() {
  9911. const geometry = this.geometry;
  9912. // we assume non-indexed geometry
  9913. if ( geometry.index === null ) {
  9914. const positionAttribute = geometry.attributes.position;
  9915. const lineDistances = [];
  9916. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9917. _start.fromBufferAttribute( positionAttribute, i );
  9918. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9919. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9920. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9921. }
  9922. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9923. } else {
  9924. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9925. }
  9926. return this;
  9927. }
  9928. }
  9929. class LineLoop extends Line {
  9930. constructor( geometry, material ) {
  9931. super( geometry, material );
  9932. this.isLineLoop = true;
  9933. this.type = 'LineLoop';
  9934. }
  9935. }
  9936. class PointsMaterial extends Material {
  9937. constructor( parameters ) {
  9938. super();
  9939. this.isPointsMaterial = true;
  9940. this.type = 'PointsMaterial';
  9941. this.color = new Color( 0xffffff );
  9942. this.map = null;
  9943. this.alphaMap = null;
  9944. this.size = 1;
  9945. this.sizeAttenuation = true;
  9946. this.fog = true;
  9947. this.setValues( parameters );
  9948. }
  9949. copy( source ) {
  9950. super.copy( source );
  9951. this.color.copy( source.color );
  9952. this.map = source.map;
  9953. this.alphaMap = source.alphaMap;
  9954. this.size = source.size;
  9955. this.sizeAttenuation = source.sizeAttenuation;
  9956. this.fog = source.fog;
  9957. return this;
  9958. }
  9959. }
  9960. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  9961. const _ray = /*@__PURE__*/ new Ray();
  9962. const _sphere = /*@__PURE__*/ new Sphere();
  9963. const _position$2 = /*@__PURE__*/ new Vector3();
  9964. class Points extends Object3D {
  9965. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  9966. super();
  9967. this.isPoints = true;
  9968. this.type = 'Points';
  9969. this.geometry = geometry;
  9970. this.material = material;
  9971. this.updateMorphTargets();
  9972. }
  9973. copy( source, recursive ) {
  9974. super.copy( source, recursive );
  9975. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9976. this.geometry = source.geometry;
  9977. return this;
  9978. }
  9979. raycast( raycaster, intersects ) {
  9980. const geometry = this.geometry;
  9981. const matrixWorld = this.matrixWorld;
  9982. const threshold = raycaster.params.Points.threshold;
  9983. const drawRange = geometry.drawRange;
  9984. // Checking boundingSphere distance to ray
  9985. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9986. _sphere.copy( geometry.boundingSphere );
  9987. _sphere.applyMatrix4( matrixWorld );
  9988. _sphere.radius += threshold;
  9989. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  9990. //
  9991. _inverseMatrix.copy( matrixWorld ).invert();
  9992. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  9993. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9994. const localThresholdSq = localThreshold * localThreshold;
  9995. const index = geometry.index;
  9996. const attributes = geometry.attributes;
  9997. const positionAttribute = attributes.position;
  9998. if ( index !== null ) {
  9999. const start = Math.max( 0, drawRange.start );
  10000. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10001. for ( let i = start, il = end; i < il; i ++ ) {
  10002. const a = index.getX( i );
  10003. _position$2.fromBufferAttribute( positionAttribute, a );
  10004. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10005. }
  10006. } else {
  10007. const start = Math.max( 0, drawRange.start );
  10008. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10009. for ( let i = start, l = end; i < l; i ++ ) {
  10010. _position$2.fromBufferAttribute( positionAttribute, i );
  10011. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10012. }
  10013. }
  10014. }
  10015. updateMorphTargets() {
  10016. const geometry = this.geometry;
  10017. const morphAttributes = geometry.morphAttributes;
  10018. const keys = Object.keys( morphAttributes );
  10019. if ( keys.length > 0 ) {
  10020. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10021. if ( morphAttribute !== undefined ) {
  10022. this.morphTargetInfluences = [];
  10023. this.morphTargetDictionary = {};
  10024. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10025. const name = morphAttribute[ m ].name || String( m );
  10026. this.morphTargetInfluences.push( 0 );
  10027. this.morphTargetDictionary[ name ] = m;
  10028. }
  10029. }
  10030. }
  10031. }
  10032. }
  10033. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10034. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10035. if ( rayPointDistanceSq < localThresholdSq ) {
  10036. const intersectPoint = new Vector3();
  10037. _ray.closestPointToPoint( point, intersectPoint );
  10038. intersectPoint.applyMatrix4( matrixWorld );
  10039. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10040. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10041. intersects.push( {
  10042. distance: distance,
  10043. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10044. point: intersectPoint,
  10045. index: index,
  10046. face: null,
  10047. object: object
  10048. } );
  10049. }
  10050. }
  10051. class Group extends Object3D {
  10052. constructor() {
  10053. super();
  10054. this.isGroup = true;
  10055. this.type = 'Group';
  10056. }
  10057. }
  10058. class VideoTexture extends Texture {
  10059. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10060. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10061. this.isVideoTexture = true;
  10062. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10063. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10064. this.generateMipmaps = false;
  10065. const scope = this;
  10066. function updateVideo() {
  10067. scope.needsUpdate = true;
  10068. video.requestVideoFrameCallback( updateVideo );
  10069. }
  10070. if ( 'requestVideoFrameCallback' in video ) {
  10071. video.requestVideoFrameCallback( updateVideo );
  10072. }
  10073. }
  10074. clone() {
  10075. return new this.constructor( this.image ).copy( this );
  10076. }
  10077. update() {
  10078. const video = this.image;
  10079. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10080. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10081. this.needsUpdate = true;
  10082. }
  10083. }
  10084. }
  10085. class FramebufferTexture extends Texture {
  10086. constructor( width, height ) {
  10087. super( { width, height } );
  10088. this.isFramebufferTexture = true;
  10089. this.magFilter = NearestFilter;
  10090. this.minFilter = NearestFilter;
  10091. this.generateMipmaps = false;
  10092. this.needsUpdate = true;
  10093. }
  10094. }
  10095. class CompressedTexture extends Texture {
  10096. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10097. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10098. this.isCompressedTexture = true;
  10099. this.image = { width: width, height: height };
  10100. this.mipmaps = mipmaps;
  10101. // no flipping for cube textures
  10102. // (also flipping doesn't work for compressed textures )
  10103. this.flipY = false;
  10104. // can't generate mipmaps for compressed textures
  10105. // mips must be embedded in DDS files
  10106. this.generateMipmaps = false;
  10107. }
  10108. }
  10109. class CompressedArrayTexture extends CompressedTexture {
  10110. constructor( mipmaps, width, height, depth, format, type ) {
  10111. super( mipmaps, width, height, format, type );
  10112. this.isCompressedArrayTexture = true;
  10113. this.image.depth = depth;
  10114. this.wrapR = ClampToEdgeWrapping;
  10115. this.layerUpdates = new Set();
  10116. }
  10117. addLayerUpdate( layerIndex ) {
  10118. this.layerUpdates.add( layerIndex );
  10119. }
  10120. clearLayerUpdates() {
  10121. this.layerUpdates.clear();
  10122. }
  10123. }
  10124. class CompressedCubeTexture extends CompressedTexture {
  10125. constructor( images, format, type ) {
  10126. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10127. this.isCompressedCubeTexture = true;
  10128. this.isCubeTexture = true;
  10129. this.image = images;
  10130. }
  10131. }
  10132. class CanvasTexture extends Texture {
  10133. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10134. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10135. this.isCanvasTexture = true;
  10136. this.needsUpdate = true;
  10137. }
  10138. }
  10139. class DepthTexture extends Texture {
  10140. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10141. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10142. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10143. }
  10144. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10145. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10146. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10147. this.isDepthTexture = true;
  10148. this.image = { width: width, height: height };
  10149. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10150. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10151. this.flipY = false;
  10152. this.generateMipmaps = false;
  10153. this.compareFunction = null;
  10154. }
  10155. copy( source ) {
  10156. super.copy( source );
  10157. this.compareFunction = source.compareFunction;
  10158. return this;
  10159. }
  10160. toJSON( meta ) {
  10161. const data = super.toJSON( meta );
  10162. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10163. return data;
  10164. }
  10165. }
  10166. /**
  10167. * Extensible curve object.
  10168. *
  10169. * Some common of curve methods:
  10170. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10171. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10172. * .getPoints(), .getSpacedPoints()
  10173. * .getLength()
  10174. * .updateArcLengths()
  10175. *
  10176. * This following curves inherit from THREE.Curve:
  10177. *
  10178. * -- 2D curves --
  10179. * THREE.ArcCurve
  10180. * THREE.CubicBezierCurve
  10181. * THREE.EllipseCurve
  10182. * THREE.LineCurve
  10183. * THREE.QuadraticBezierCurve
  10184. * THREE.SplineCurve
  10185. *
  10186. * -- 3D curves --
  10187. * THREE.CatmullRomCurve3
  10188. * THREE.CubicBezierCurve3
  10189. * THREE.LineCurve3
  10190. * THREE.QuadraticBezierCurve3
  10191. *
  10192. * A series of curves can be represented as a THREE.CurvePath.
  10193. *
  10194. **/
  10195. class Curve {
  10196. constructor() {
  10197. this.type = 'Curve';
  10198. this.arcLengthDivisions = 200;
  10199. }
  10200. // Virtual base class method to overwrite and implement in subclasses
  10201. // - t [0 .. 1]
  10202. getPoint( /* t, optionalTarget */ ) {
  10203. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10204. return null;
  10205. }
  10206. // Get point at relative position in curve according to arc length
  10207. // - u [0 .. 1]
  10208. getPointAt( u, optionalTarget ) {
  10209. const t = this.getUtoTmapping( u );
  10210. return this.getPoint( t, optionalTarget );
  10211. }
  10212. // Get sequence of points using getPoint( t )
  10213. getPoints( divisions = 5 ) {
  10214. const points = [];
  10215. for ( let d = 0; d <= divisions; d ++ ) {
  10216. points.push( this.getPoint( d / divisions ) );
  10217. }
  10218. return points;
  10219. }
  10220. // Get sequence of points using getPointAt( u )
  10221. getSpacedPoints( divisions = 5 ) {
  10222. const points = [];
  10223. for ( let d = 0; d <= divisions; d ++ ) {
  10224. points.push( this.getPointAt( d / divisions ) );
  10225. }
  10226. return points;
  10227. }
  10228. // Get total curve arc length
  10229. getLength() {
  10230. const lengths = this.getLengths();
  10231. return lengths[ lengths.length - 1 ];
  10232. }
  10233. // Get list of cumulative segment lengths
  10234. getLengths( divisions = this.arcLengthDivisions ) {
  10235. if ( this.cacheArcLengths &&
  10236. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10237. ! this.needsUpdate ) {
  10238. return this.cacheArcLengths;
  10239. }
  10240. this.needsUpdate = false;
  10241. const cache = [];
  10242. let current, last = this.getPoint( 0 );
  10243. let sum = 0;
  10244. cache.push( 0 );
  10245. for ( let p = 1; p <= divisions; p ++ ) {
  10246. current = this.getPoint( p / divisions );
  10247. sum += current.distanceTo( last );
  10248. cache.push( sum );
  10249. last = current;
  10250. }
  10251. this.cacheArcLengths = cache;
  10252. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10253. }
  10254. updateArcLengths() {
  10255. this.needsUpdate = true;
  10256. this.getLengths();
  10257. }
  10258. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10259. getUtoTmapping( u, distance ) {
  10260. const arcLengths = this.getLengths();
  10261. let i = 0;
  10262. const il = arcLengths.length;
  10263. let targetArcLength; // The targeted u distance value to get
  10264. if ( distance ) {
  10265. targetArcLength = distance;
  10266. } else {
  10267. targetArcLength = u * arcLengths[ il - 1 ];
  10268. }
  10269. // binary search for the index with largest value smaller than target u distance
  10270. let low = 0, high = il - 1, comparison;
  10271. while ( low <= high ) {
  10272. 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
  10273. comparison = arcLengths[ i ] - targetArcLength;
  10274. if ( comparison < 0 ) {
  10275. low = i + 1;
  10276. } else if ( comparison > 0 ) {
  10277. high = i - 1;
  10278. } else {
  10279. high = i;
  10280. break;
  10281. // DONE
  10282. }
  10283. }
  10284. i = high;
  10285. if ( arcLengths[ i ] === targetArcLength ) {
  10286. return i / ( il - 1 );
  10287. }
  10288. // we could get finer grain at lengths, or use simple interpolation between two points
  10289. const lengthBefore = arcLengths[ i ];
  10290. const lengthAfter = arcLengths[ i + 1 ];
  10291. const segmentLength = lengthAfter - lengthBefore;
  10292. // determine where we are between the 'before' and 'after' points
  10293. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10294. // add that fractional amount to t
  10295. const t = ( i + segmentFraction ) / ( il - 1 );
  10296. return t;
  10297. }
  10298. // Returns a unit vector tangent at t
  10299. // In case any sub curve does not implement its tangent derivation,
  10300. // 2 points a small delta apart will be used to find its gradient
  10301. // which seems to give a reasonable approximation
  10302. getTangent( t, optionalTarget ) {
  10303. const delta = 0.0001;
  10304. let t1 = t - delta;
  10305. let t2 = t + delta;
  10306. // Capping in case of danger
  10307. if ( t1 < 0 ) t1 = 0;
  10308. if ( t2 > 1 ) t2 = 1;
  10309. const pt1 = this.getPoint( t1 );
  10310. const pt2 = this.getPoint( t2 );
  10311. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10312. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10313. return tangent;
  10314. }
  10315. getTangentAt( u, optionalTarget ) {
  10316. const t = this.getUtoTmapping( u );
  10317. return this.getTangent( t, optionalTarget );
  10318. }
  10319. computeFrenetFrames( segments, closed ) {
  10320. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10321. const normal = new Vector3();
  10322. const tangents = [];
  10323. const normals = [];
  10324. const binormals = [];
  10325. const vec = new Vector3();
  10326. const mat = new Matrix4();
  10327. // compute the tangent vectors for each segment on the curve
  10328. for ( let i = 0; i <= segments; i ++ ) {
  10329. const u = i / segments;
  10330. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10331. }
  10332. // select an initial normal vector perpendicular to the first tangent vector,
  10333. // and in the direction of the minimum tangent xyz component
  10334. normals[ 0 ] = new Vector3();
  10335. binormals[ 0 ] = new Vector3();
  10336. let min = Number.MAX_VALUE;
  10337. const tx = Math.abs( tangents[ 0 ].x );
  10338. const ty = Math.abs( tangents[ 0 ].y );
  10339. const tz = Math.abs( tangents[ 0 ].z );
  10340. if ( tx <= min ) {
  10341. min = tx;
  10342. normal.set( 1, 0, 0 );
  10343. }
  10344. if ( ty <= min ) {
  10345. min = ty;
  10346. normal.set( 0, 1, 0 );
  10347. }
  10348. if ( tz <= min ) {
  10349. normal.set( 0, 0, 1 );
  10350. }
  10351. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10352. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10353. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10354. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10355. for ( let i = 1; i <= segments; i ++ ) {
  10356. normals[ i ] = normals[ i - 1 ].clone();
  10357. binormals[ i ] = binormals[ i - 1 ].clone();
  10358. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10359. if ( vec.length() > Number.EPSILON ) {
  10360. vec.normalize();
  10361. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10362. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10363. }
  10364. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10365. }
  10366. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10367. if ( closed === true ) {
  10368. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10369. theta /= segments;
  10370. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10371. theta = - theta;
  10372. }
  10373. for ( let i = 1; i <= segments; i ++ ) {
  10374. // twist a little...
  10375. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10376. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10377. }
  10378. }
  10379. return {
  10380. tangents: tangents,
  10381. normals: normals,
  10382. binormals: binormals
  10383. };
  10384. }
  10385. clone() {
  10386. return new this.constructor().copy( this );
  10387. }
  10388. copy( source ) {
  10389. this.arcLengthDivisions = source.arcLengthDivisions;
  10390. return this;
  10391. }
  10392. toJSON() {
  10393. const data = {
  10394. metadata: {
  10395. version: 4.6,
  10396. type: 'Curve',
  10397. generator: 'Curve.toJSON'
  10398. }
  10399. };
  10400. data.arcLengthDivisions = this.arcLengthDivisions;
  10401. data.type = this.type;
  10402. return data;
  10403. }
  10404. fromJSON( json ) {
  10405. this.arcLengthDivisions = json.arcLengthDivisions;
  10406. return this;
  10407. }
  10408. }
  10409. class EllipseCurve extends Curve {
  10410. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10411. super();
  10412. this.isEllipseCurve = true;
  10413. this.type = 'EllipseCurve';
  10414. this.aX = aX;
  10415. this.aY = aY;
  10416. this.xRadius = xRadius;
  10417. this.yRadius = yRadius;
  10418. this.aStartAngle = aStartAngle;
  10419. this.aEndAngle = aEndAngle;
  10420. this.aClockwise = aClockwise;
  10421. this.aRotation = aRotation;
  10422. }
  10423. getPoint( t, optionalTarget = new Vector2() ) {
  10424. const point = optionalTarget;
  10425. const twoPi = Math.PI * 2;
  10426. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10427. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10428. // ensures that deltaAngle is 0 .. 2 PI
  10429. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10430. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10431. if ( deltaAngle < Number.EPSILON ) {
  10432. if ( samePoints ) {
  10433. deltaAngle = 0;
  10434. } else {
  10435. deltaAngle = twoPi;
  10436. }
  10437. }
  10438. if ( this.aClockwise === true && ! samePoints ) {
  10439. if ( deltaAngle === twoPi ) {
  10440. deltaAngle = - twoPi;
  10441. } else {
  10442. deltaAngle = deltaAngle - twoPi;
  10443. }
  10444. }
  10445. const angle = this.aStartAngle + t * deltaAngle;
  10446. let x = this.aX + this.xRadius * Math.cos( angle );
  10447. let y = this.aY + this.yRadius * Math.sin( angle );
  10448. if ( this.aRotation !== 0 ) {
  10449. const cos = Math.cos( this.aRotation );
  10450. const sin = Math.sin( this.aRotation );
  10451. const tx = x - this.aX;
  10452. const ty = y - this.aY;
  10453. // Rotate the point about the center of the ellipse.
  10454. x = tx * cos - ty * sin + this.aX;
  10455. y = tx * sin + ty * cos + this.aY;
  10456. }
  10457. return point.set( x, y );
  10458. }
  10459. copy( source ) {
  10460. super.copy( source );
  10461. this.aX = source.aX;
  10462. this.aY = source.aY;
  10463. this.xRadius = source.xRadius;
  10464. this.yRadius = source.yRadius;
  10465. this.aStartAngle = source.aStartAngle;
  10466. this.aEndAngle = source.aEndAngle;
  10467. this.aClockwise = source.aClockwise;
  10468. this.aRotation = source.aRotation;
  10469. return this;
  10470. }
  10471. toJSON() {
  10472. const data = super.toJSON();
  10473. data.aX = this.aX;
  10474. data.aY = this.aY;
  10475. data.xRadius = this.xRadius;
  10476. data.yRadius = this.yRadius;
  10477. data.aStartAngle = this.aStartAngle;
  10478. data.aEndAngle = this.aEndAngle;
  10479. data.aClockwise = this.aClockwise;
  10480. data.aRotation = this.aRotation;
  10481. return data;
  10482. }
  10483. fromJSON( json ) {
  10484. super.fromJSON( json );
  10485. this.aX = json.aX;
  10486. this.aY = json.aY;
  10487. this.xRadius = json.xRadius;
  10488. this.yRadius = json.yRadius;
  10489. this.aStartAngle = json.aStartAngle;
  10490. this.aEndAngle = json.aEndAngle;
  10491. this.aClockwise = json.aClockwise;
  10492. this.aRotation = json.aRotation;
  10493. return this;
  10494. }
  10495. }
  10496. class ArcCurve extends EllipseCurve {
  10497. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10498. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10499. this.isArcCurve = true;
  10500. this.type = 'ArcCurve';
  10501. }
  10502. }
  10503. /**
  10504. * Centripetal CatmullRom Curve - which is useful for avoiding
  10505. * cusps and self-intersections in non-uniform catmull rom curves.
  10506. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10507. *
  10508. * curve.type accepts centripetal(default), chordal and catmullrom
  10509. * curve.tension is used for catmullrom which defaults to 0.5
  10510. */
  10511. /*
  10512. Based on an optimized c++ solution in
  10513. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10514. - http://ideone.com/NoEbVM
  10515. This CubicPoly class could be used for reusing some variables and calculations,
  10516. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10517. which can be placed in CurveUtils.
  10518. */
  10519. function CubicPoly() {
  10520. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10521. /*
  10522. * Compute coefficients for a cubic polynomial
  10523. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10524. * such that
  10525. * p(0) = x0, p(1) = x1
  10526. * and
  10527. * p'(0) = t0, p'(1) = t1.
  10528. */
  10529. function init( x0, x1, t0, t1 ) {
  10530. c0 = x0;
  10531. c1 = t0;
  10532. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10533. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10534. }
  10535. return {
  10536. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10537. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10538. },
  10539. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10540. // compute tangents when parameterized in [t1,t2]
  10541. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10542. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10543. // rescale tangents for parametrization in [0,1]
  10544. t1 *= dt1;
  10545. t2 *= dt1;
  10546. init( x1, x2, t1, t2 );
  10547. },
  10548. calc: function ( t ) {
  10549. const t2 = t * t;
  10550. const t3 = t2 * t;
  10551. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10552. }
  10553. };
  10554. }
  10555. //
  10556. const tmp = /*@__PURE__*/ new Vector3();
  10557. const px = /*@__PURE__*/ new CubicPoly();
  10558. const py = /*@__PURE__*/ new CubicPoly();
  10559. const pz = /*@__PURE__*/ new CubicPoly();
  10560. class CatmullRomCurve3 extends Curve {
  10561. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10562. super();
  10563. this.isCatmullRomCurve3 = true;
  10564. this.type = 'CatmullRomCurve3';
  10565. this.points = points;
  10566. this.closed = closed;
  10567. this.curveType = curveType;
  10568. this.tension = tension;
  10569. }
  10570. getPoint( t, optionalTarget = new Vector3() ) {
  10571. const point = optionalTarget;
  10572. const points = this.points;
  10573. const l = points.length;
  10574. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10575. let intPoint = Math.floor( p );
  10576. let weight = p - intPoint;
  10577. if ( this.closed ) {
  10578. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10579. } else if ( weight === 0 && intPoint === l - 1 ) {
  10580. intPoint = l - 2;
  10581. weight = 1;
  10582. }
  10583. let p0, p3; // 4 points (p1 & p2 defined below)
  10584. if ( this.closed || intPoint > 0 ) {
  10585. p0 = points[ ( intPoint - 1 ) % l ];
  10586. } else {
  10587. // extrapolate first point
  10588. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10589. p0 = tmp;
  10590. }
  10591. const p1 = points[ intPoint % l ];
  10592. const p2 = points[ ( intPoint + 1 ) % l ];
  10593. if ( this.closed || intPoint + 2 < l ) {
  10594. p3 = points[ ( intPoint + 2 ) % l ];
  10595. } else {
  10596. // extrapolate last point
  10597. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10598. p3 = tmp;
  10599. }
  10600. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10601. // init Centripetal / Chordal Catmull-Rom
  10602. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10603. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10604. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10605. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10606. // safety check for repeated points
  10607. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10608. if ( dt0 < 1e-4 ) dt0 = dt1;
  10609. if ( dt2 < 1e-4 ) dt2 = dt1;
  10610. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10611. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10612. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10613. } else if ( this.curveType === 'catmullrom' ) {
  10614. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10615. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10616. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10617. }
  10618. point.set(
  10619. px.calc( weight ),
  10620. py.calc( weight ),
  10621. pz.calc( weight )
  10622. );
  10623. return point;
  10624. }
  10625. copy( source ) {
  10626. super.copy( source );
  10627. this.points = [];
  10628. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10629. const point = source.points[ i ];
  10630. this.points.push( point.clone() );
  10631. }
  10632. this.closed = source.closed;
  10633. this.curveType = source.curveType;
  10634. this.tension = source.tension;
  10635. return this;
  10636. }
  10637. toJSON() {
  10638. const data = super.toJSON();
  10639. data.points = [];
  10640. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10641. const point = this.points[ i ];
  10642. data.points.push( point.toArray() );
  10643. }
  10644. data.closed = this.closed;
  10645. data.curveType = this.curveType;
  10646. data.tension = this.tension;
  10647. return data;
  10648. }
  10649. fromJSON( json ) {
  10650. super.fromJSON( json );
  10651. this.points = [];
  10652. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10653. const point = json.points[ i ];
  10654. this.points.push( new Vector3().fromArray( point ) );
  10655. }
  10656. this.closed = json.closed;
  10657. this.curveType = json.curveType;
  10658. this.tension = json.tension;
  10659. return this;
  10660. }
  10661. }
  10662. /**
  10663. * Bezier Curves formulas obtained from
  10664. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10665. */
  10666. function CatmullRom( t, p0, p1, p2, p3 ) {
  10667. const v0 = ( p2 - p0 ) * 0.5;
  10668. const v1 = ( p3 - p1 ) * 0.5;
  10669. const t2 = t * t;
  10670. const t3 = t * t2;
  10671. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10672. }
  10673. //
  10674. function QuadraticBezierP0( t, p ) {
  10675. const k = 1 - t;
  10676. return k * k * p;
  10677. }
  10678. function QuadraticBezierP1( t, p ) {
  10679. return 2 * ( 1 - t ) * t * p;
  10680. }
  10681. function QuadraticBezierP2( t, p ) {
  10682. return t * t * p;
  10683. }
  10684. function QuadraticBezier( t, p0, p1, p2 ) {
  10685. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10686. QuadraticBezierP2( t, p2 );
  10687. }
  10688. //
  10689. function CubicBezierP0( t, p ) {
  10690. const k = 1 - t;
  10691. return k * k * k * p;
  10692. }
  10693. function CubicBezierP1( t, p ) {
  10694. const k = 1 - t;
  10695. return 3 * k * k * t * p;
  10696. }
  10697. function CubicBezierP2( t, p ) {
  10698. return 3 * ( 1 - t ) * t * t * p;
  10699. }
  10700. function CubicBezierP3( t, p ) {
  10701. return t * t * t * p;
  10702. }
  10703. function CubicBezier( t, p0, p1, p2, p3 ) {
  10704. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10705. CubicBezierP3( t, p3 );
  10706. }
  10707. class CubicBezierCurve extends Curve {
  10708. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10709. super();
  10710. this.isCubicBezierCurve = true;
  10711. this.type = 'CubicBezierCurve';
  10712. this.v0 = v0;
  10713. this.v1 = v1;
  10714. this.v2 = v2;
  10715. this.v3 = v3;
  10716. }
  10717. getPoint( t, optionalTarget = new Vector2() ) {
  10718. const point = optionalTarget;
  10719. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10720. point.set(
  10721. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10722. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10723. );
  10724. return point;
  10725. }
  10726. copy( source ) {
  10727. super.copy( source );
  10728. this.v0.copy( source.v0 );
  10729. this.v1.copy( source.v1 );
  10730. this.v2.copy( source.v2 );
  10731. this.v3.copy( source.v3 );
  10732. return this;
  10733. }
  10734. toJSON() {
  10735. const data = super.toJSON();
  10736. data.v0 = this.v0.toArray();
  10737. data.v1 = this.v1.toArray();
  10738. data.v2 = this.v2.toArray();
  10739. data.v3 = this.v3.toArray();
  10740. return data;
  10741. }
  10742. fromJSON( json ) {
  10743. super.fromJSON( json );
  10744. this.v0.fromArray( json.v0 );
  10745. this.v1.fromArray( json.v1 );
  10746. this.v2.fromArray( json.v2 );
  10747. this.v3.fromArray( json.v3 );
  10748. return this;
  10749. }
  10750. }
  10751. class CubicBezierCurve3 extends Curve {
  10752. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10753. super();
  10754. this.isCubicBezierCurve3 = true;
  10755. this.type = 'CubicBezierCurve3';
  10756. this.v0 = v0;
  10757. this.v1 = v1;
  10758. this.v2 = v2;
  10759. this.v3 = v3;
  10760. }
  10761. getPoint( t, optionalTarget = new Vector3() ) {
  10762. const point = optionalTarget;
  10763. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10764. point.set(
  10765. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10766. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10767. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10768. );
  10769. return point;
  10770. }
  10771. copy( source ) {
  10772. super.copy( source );
  10773. this.v0.copy( source.v0 );
  10774. this.v1.copy( source.v1 );
  10775. this.v2.copy( source.v2 );
  10776. this.v3.copy( source.v3 );
  10777. return this;
  10778. }
  10779. toJSON() {
  10780. const data = super.toJSON();
  10781. data.v0 = this.v0.toArray();
  10782. data.v1 = this.v1.toArray();
  10783. data.v2 = this.v2.toArray();
  10784. data.v3 = this.v3.toArray();
  10785. return data;
  10786. }
  10787. fromJSON( json ) {
  10788. super.fromJSON( json );
  10789. this.v0.fromArray( json.v0 );
  10790. this.v1.fromArray( json.v1 );
  10791. this.v2.fromArray( json.v2 );
  10792. this.v3.fromArray( json.v3 );
  10793. return this;
  10794. }
  10795. }
  10796. class LineCurve extends Curve {
  10797. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10798. super();
  10799. this.isLineCurve = true;
  10800. this.type = 'LineCurve';
  10801. this.v1 = v1;
  10802. this.v2 = v2;
  10803. }
  10804. getPoint( t, optionalTarget = new Vector2() ) {
  10805. const point = optionalTarget;
  10806. if ( t === 1 ) {
  10807. point.copy( this.v2 );
  10808. } else {
  10809. point.copy( this.v2 ).sub( this.v1 );
  10810. point.multiplyScalar( t ).add( this.v1 );
  10811. }
  10812. return point;
  10813. }
  10814. // Line curve is linear, so we can overwrite default getPointAt
  10815. getPointAt( u, optionalTarget ) {
  10816. return this.getPoint( u, optionalTarget );
  10817. }
  10818. getTangent( t, optionalTarget = new Vector2() ) {
  10819. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10820. }
  10821. getTangentAt( u, optionalTarget ) {
  10822. return this.getTangent( u, optionalTarget );
  10823. }
  10824. copy( source ) {
  10825. super.copy( source );
  10826. this.v1.copy( source.v1 );
  10827. this.v2.copy( source.v2 );
  10828. return this;
  10829. }
  10830. toJSON() {
  10831. const data = super.toJSON();
  10832. data.v1 = this.v1.toArray();
  10833. data.v2 = this.v2.toArray();
  10834. return data;
  10835. }
  10836. fromJSON( json ) {
  10837. super.fromJSON( json );
  10838. this.v1.fromArray( json.v1 );
  10839. this.v2.fromArray( json.v2 );
  10840. return this;
  10841. }
  10842. }
  10843. class LineCurve3 extends Curve {
  10844. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10845. super();
  10846. this.isLineCurve3 = true;
  10847. this.type = 'LineCurve3';
  10848. this.v1 = v1;
  10849. this.v2 = v2;
  10850. }
  10851. getPoint( t, optionalTarget = new Vector3() ) {
  10852. const point = optionalTarget;
  10853. if ( t === 1 ) {
  10854. point.copy( this.v2 );
  10855. } else {
  10856. point.copy( this.v2 ).sub( this.v1 );
  10857. point.multiplyScalar( t ).add( this.v1 );
  10858. }
  10859. return point;
  10860. }
  10861. // Line curve is linear, so we can overwrite default getPointAt
  10862. getPointAt( u, optionalTarget ) {
  10863. return this.getPoint( u, optionalTarget );
  10864. }
  10865. getTangent( t, optionalTarget = new Vector3() ) {
  10866. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10867. }
  10868. getTangentAt( u, optionalTarget ) {
  10869. return this.getTangent( u, optionalTarget );
  10870. }
  10871. copy( source ) {
  10872. super.copy( source );
  10873. this.v1.copy( source.v1 );
  10874. this.v2.copy( source.v2 );
  10875. return this;
  10876. }
  10877. toJSON() {
  10878. const data = super.toJSON();
  10879. data.v1 = this.v1.toArray();
  10880. data.v2 = this.v2.toArray();
  10881. return data;
  10882. }
  10883. fromJSON( json ) {
  10884. super.fromJSON( json );
  10885. this.v1.fromArray( json.v1 );
  10886. this.v2.fromArray( json.v2 );
  10887. return this;
  10888. }
  10889. }
  10890. class QuadraticBezierCurve extends Curve {
  10891. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10892. super();
  10893. this.isQuadraticBezierCurve = true;
  10894. this.type = 'QuadraticBezierCurve';
  10895. this.v0 = v0;
  10896. this.v1 = v1;
  10897. this.v2 = v2;
  10898. }
  10899. getPoint( t, optionalTarget = new Vector2() ) {
  10900. const point = optionalTarget;
  10901. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10902. point.set(
  10903. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10904. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10905. );
  10906. return point;
  10907. }
  10908. copy( source ) {
  10909. super.copy( source );
  10910. this.v0.copy( source.v0 );
  10911. this.v1.copy( source.v1 );
  10912. this.v2.copy( source.v2 );
  10913. return this;
  10914. }
  10915. toJSON() {
  10916. const data = super.toJSON();
  10917. data.v0 = this.v0.toArray();
  10918. data.v1 = this.v1.toArray();
  10919. data.v2 = this.v2.toArray();
  10920. return data;
  10921. }
  10922. fromJSON( json ) {
  10923. super.fromJSON( json );
  10924. this.v0.fromArray( json.v0 );
  10925. this.v1.fromArray( json.v1 );
  10926. this.v2.fromArray( json.v2 );
  10927. return this;
  10928. }
  10929. }
  10930. class QuadraticBezierCurve3 extends Curve {
  10931. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10932. super();
  10933. this.isQuadraticBezierCurve3 = true;
  10934. this.type = 'QuadraticBezierCurve3';
  10935. this.v0 = v0;
  10936. this.v1 = v1;
  10937. this.v2 = v2;
  10938. }
  10939. getPoint( t, optionalTarget = new Vector3() ) {
  10940. const point = optionalTarget;
  10941. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10942. point.set(
  10943. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10944. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10945. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10946. );
  10947. return point;
  10948. }
  10949. copy( source ) {
  10950. super.copy( source );
  10951. this.v0.copy( source.v0 );
  10952. this.v1.copy( source.v1 );
  10953. this.v2.copy( source.v2 );
  10954. return this;
  10955. }
  10956. toJSON() {
  10957. const data = super.toJSON();
  10958. data.v0 = this.v0.toArray();
  10959. data.v1 = this.v1.toArray();
  10960. data.v2 = this.v2.toArray();
  10961. return data;
  10962. }
  10963. fromJSON( json ) {
  10964. super.fromJSON( json );
  10965. this.v0.fromArray( json.v0 );
  10966. this.v1.fromArray( json.v1 );
  10967. this.v2.fromArray( json.v2 );
  10968. return this;
  10969. }
  10970. }
  10971. class SplineCurve extends Curve {
  10972. constructor( points = [] ) {
  10973. super();
  10974. this.isSplineCurve = true;
  10975. this.type = 'SplineCurve';
  10976. this.points = points;
  10977. }
  10978. getPoint( t, optionalTarget = new Vector2() ) {
  10979. const point = optionalTarget;
  10980. const points = this.points;
  10981. const p = ( points.length - 1 ) * t;
  10982. const intPoint = Math.floor( p );
  10983. const weight = p - intPoint;
  10984. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  10985. const p1 = points[ intPoint ];
  10986. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  10987. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  10988. point.set(
  10989. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  10990. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  10991. );
  10992. return point;
  10993. }
  10994. copy( source ) {
  10995. super.copy( source );
  10996. this.points = [];
  10997. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10998. const point = source.points[ i ];
  10999. this.points.push( point.clone() );
  11000. }
  11001. return this;
  11002. }
  11003. toJSON() {
  11004. const data = super.toJSON();
  11005. data.points = [];
  11006. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11007. const point = this.points[ i ];
  11008. data.points.push( point.toArray() );
  11009. }
  11010. return data;
  11011. }
  11012. fromJSON( json ) {
  11013. super.fromJSON( json );
  11014. this.points = [];
  11015. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11016. const point = json.points[ i ];
  11017. this.points.push( new Vector2().fromArray( point ) );
  11018. }
  11019. return this;
  11020. }
  11021. }
  11022. var Curves = /*#__PURE__*/Object.freeze({
  11023. __proto__: null,
  11024. ArcCurve: ArcCurve,
  11025. CatmullRomCurve3: CatmullRomCurve3,
  11026. CubicBezierCurve: CubicBezierCurve,
  11027. CubicBezierCurve3: CubicBezierCurve3,
  11028. EllipseCurve: EllipseCurve,
  11029. LineCurve: LineCurve,
  11030. LineCurve3: LineCurve3,
  11031. QuadraticBezierCurve: QuadraticBezierCurve,
  11032. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11033. SplineCurve: SplineCurve
  11034. });
  11035. /**************************************************************
  11036. * Curved Path - a curve path is simply a array of connected
  11037. * curves, but retains the api of a curve
  11038. **************************************************************/
  11039. class CurvePath extends Curve {
  11040. constructor() {
  11041. super();
  11042. this.type = 'CurvePath';
  11043. this.curves = [];
  11044. this.autoClose = false; // Automatically closes the path
  11045. }
  11046. add( curve ) {
  11047. this.curves.push( curve );
  11048. }
  11049. closePath() {
  11050. // Add a line curve if start and end of lines are not connected
  11051. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11052. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11053. if ( ! startPoint.equals( endPoint ) ) {
  11054. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11055. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11056. }
  11057. return this;
  11058. }
  11059. // To get accurate point with reference to
  11060. // entire path distance at time t,
  11061. // following has to be done:
  11062. // 1. Length of each sub path have to be known
  11063. // 2. Locate and identify type of curve
  11064. // 3. Get t for the curve
  11065. // 4. Return curve.getPointAt(t')
  11066. getPoint( t, optionalTarget ) {
  11067. const d = t * this.getLength();
  11068. const curveLengths = this.getCurveLengths();
  11069. let i = 0;
  11070. // To think about boundaries points.
  11071. while ( i < curveLengths.length ) {
  11072. if ( curveLengths[ i ] >= d ) {
  11073. const diff = curveLengths[ i ] - d;
  11074. const curve = this.curves[ i ];
  11075. const segmentLength = curve.getLength();
  11076. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11077. return curve.getPointAt( u, optionalTarget );
  11078. }
  11079. i ++;
  11080. }
  11081. return null;
  11082. // loop where sum != 0, sum > d , sum+1 <d
  11083. }
  11084. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11085. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11086. // getPoint() depends on getLength
  11087. getLength() {
  11088. const lens = this.getCurveLengths();
  11089. return lens[ lens.length - 1 ];
  11090. }
  11091. // cacheLengths must be recalculated.
  11092. updateArcLengths() {
  11093. this.needsUpdate = true;
  11094. this.cacheLengths = null;
  11095. this.getCurveLengths();
  11096. }
  11097. // Compute lengths and cache them
  11098. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11099. getCurveLengths() {
  11100. // We use cache values if curves and cache array are same length
  11101. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11102. return this.cacheLengths;
  11103. }
  11104. // Get length of sub-curve
  11105. // Push sums into cached array
  11106. const lengths = [];
  11107. let sums = 0;
  11108. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11109. sums += this.curves[ i ].getLength();
  11110. lengths.push( sums );
  11111. }
  11112. this.cacheLengths = lengths;
  11113. return lengths;
  11114. }
  11115. getSpacedPoints( divisions = 40 ) {
  11116. const points = [];
  11117. for ( let i = 0; i <= divisions; i ++ ) {
  11118. points.push( this.getPoint( i / divisions ) );
  11119. }
  11120. if ( this.autoClose ) {
  11121. points.push( points[ 0 ] );
  11122. }
  11123. return points;
  11124. }
  11125. getPoints( divisions = 12 ) {
  11126. const points = [];
  11127. let last;
  11128. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11129. const curve = curves[ i ];
  11130. const resolution = curve.isEllipseCurve ? divisions * 2
  11131. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11132. : curve.isSplineCurve ? divisions * curve.points.length
  11133. : divisions;
  11134. const pts = curve.getPoints( resolution );
  11135. for ( let j = 0; j < pts.length; j ++ ) {
  11136. const point = pts[ j ];
  11137. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11138. points.push( point );
  11139. last = point;
  11140. }
  11141. }
  11142. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11143. points.push( points[ 0 ] );
  11144. }
  11145. return points;
  11146. }
  11147. copy( source ) {
  11148. super.copy( source );
  11149. this.curves = [];
  11150. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11151. const curve = source.curves[ i ];
  11152. this.curves.push( curve.clone() );
  11153. }
  11154. this.autoClose = source.autoClose;
  11155. return this;
  11156. }
  11157. toJSON() {
  11158. const data = super.toJSON();
  11159. data.autoClose = this.autoClose;
  11160. data.curves = [];
  11161. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11162. const curve = this.curves[ i ];
  11163. data.curves.push( curve.toJSON() );
  11164. }
  11165. return data;
  11166. }
  11167. fromJSON( json ) {
  11168. super.fromJSON( json );
  11169. this.autoClose = json.autoClose;
  11170. this.curves = [];
  11171. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11172. const curve = json.curves[ i ];
  11173. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11174. }
  11175. return this;
  11176. }
  11177. }
  11178. class Path extends CurvePath {
  11179. constructor( points ) {
  11180. super();
  11181. this.type = 'Path';
  11182. this.currentPoint = new Vector2();
  11183. if ( points ) {
  11184. this.setFromPoints( points );
  11185. }
  11186. }
  11187. setFromPoints( points ) {
  11188. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11189. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11190. this.lineTo( points[ i ].x, points[ i ].y );
  11191. }
  11192. return this;
  11193. }
  11194. moveTo( x, y ) {
  11195. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11196. return this;
  11197. }
  11198. lineTo( x, y ) {
  11199. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11200. this.curves.push( curve );
  11201. this.currentPoint.set( x, y );
  11202. return this;
  11203. }
  11204. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11205. const curve = new QuadraticBezierCurve(
  11206. this.currentPoint.clone(),
  11207. new Vector2( aCPx, aCPy ),
  11208. new Vector2( aX, aY )
  11209. );
  11210. this.curves.push( curve );
  11211. this.currentPoint.set( aX, aY );
  11212. return this;
  11213. }
  11214. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11215. const curve = new CubicBezierCurve(
  11216. this.currentPoint.clone(),
  11217. new Vector2( aCP1x, aCP1y ),
  11218. new Vector2( aCP2x, aCP2y ),
  11219. new Vector2( aX, aY )
  11220. );
  11221. this.curves.push( curve );
  11222. this.currentPoint.set( aX, aY );
  11223. return this;
  11224. }
  11225. splineThru( pts /*Array of Vector*/ ) {
  11226. const npts = [ this.currentPoint.clone() ].concat( pts );
  11227. const curve = new SplineCurve( npts );
  11228. this.curves.push( curve );
  11229. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11230. return this;
  11231. }
  11232. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11233. const x0 = this.currentPoint.x;
  11234. const y0 = this.currentPoint.y;
  11235. this.absarc( aX + x0, aY + y0, aRadius,
  11236. aStartAngle, aEndAngle, aClockwise );
  11237. return this;
  11238. }
  11239. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11240. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11241. return this;
  11242. }
  11243. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11244. const x0 = this.currentPoint.x;
  11245. const y0 = this.currentPoint.y;
  11246. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11247. return this;
  11248. }
  11249. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11250. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11251. if ( this.curves.length > 0 ) {
  11252. // if a previous curve is present, attempt to join
  11253. const firstPoint = curve.getPoint( 0 );
  11254. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11255. this.lineTo( firstPoint.x, firstPoint.y );
  11256. }
  11257. }
  11258. this.curves.push( curve );
  11259. const lastPoint = curve.getPoint( 1 );
  11260. this.currentPoint.copy( lastPoint );
  11261. return this;
  11262. }
  11263. copy( source ) {
  11264. super.copy( source );
  11265. this.currentPoint.copy( source.currentPoint );
  11266. return this;
  11267. }
  11268. toJSON() {
  11269. const data = super.toJSON();
  11270. data.currentPoint = this.currentPoint.toArray();
  11271. return data;
  11272. }
  11273. fromJSON( json ) {
  11274. super.fromJSON( json );
  11275. this.currentPoint.fromArray( json.currentPoint );
  11276. return this;
  11277. }
  11278. }
  11279. class LatheGeometry extends BufferGeometry {
  11280. 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 ) {
  11281. super();
  11282. this.type = 'LatheGeometry';
  11283. this.parameters = {
  11284. points: points,
  11285. segments: segments,
  11286. phiStart: phiStart,
  11287. phiLength: phiLength
  11288. };
  11289. segments = Math.floor( segments );
  11290. // clamp phiLength so it's in range of [ 0, 2PI ]
  11291. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11292. // buffers
  11293. const indices = [];
  11294. const vertices = [];
  11295. const uvs = [];
  11296. const initNormals = [];
  11297. const normals = [];
  11298. // helper variables
  11299. const inverseSegments = 1.0 / segments;
  11300. const vertex = new Vector3();
  11301. const uv = new Vector2();
  11302. const normal = new Vector3();
  11303. const curNormal = new Vector3();
  11304. const prevNormal = new Vector3();
  11305. let dx = 0;
  11306. let dy = 0;
  11307. // pre-compute normals for initial "meridian"
  11308. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11309. switch ( j ) {
  11310. case 0: // special handling for 1st vertex on path
  11311. dx = points[ j + 1 ].x - points[ j ].x;
  11312. dy = points[ j + 1 ].y - points[ j ].y;
  11313. normal.x = dy * 1.0;
  11314. normal.y = - dx;
  11315. normal.z = dy * 0.0;
  11316. prevNormal.copy( normal );
  11317. normal.normalize();
  11318. initNormals.push( normal.x, normal.y, normal.z );
  11319. break;
  11320. case ( points.length - 1 ): // special handling for last Vertex on path
  11321. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11322. break;
  11323. default: // default handling for all vertices in between
  11324. dx = points[ j + 1 ].x - points[ j ].x;
  11325. dy = points[ j + 1 ].y - points[ j ].y;
  11326. normal.x = dy * 1.0;
  11327. normal.y = - dx;
  11328. normal.z = dy * 0.0;
  11329. curNormal.copy( normal );
  11330. normal.x += prevNormal.x;
  11331. normal.y += prevNormal.y;
  11332. normal.z += prevNormal.z;
  11333. normal.normalize();
  11334. initNormals.push( normal.x, normal.y, normal.z );
  11335. prevNormal.copy( curNormal );
  11336. }
  11337. }
  11338. // generate vertices, uvs and normals
  11339. for ( let i = 0; i <= segments; i ++ ) {
  11340. const phi = phiStart + i * inverseSegments * phiLength;
  11341. const sin = Math.sin( phi );
  11342. const cos = Math.cos( phi );
  11343. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11344. // vertex
  11345. vertex.x = points[ j ].x * sin;
  11346. vertex.y = points[ j ].y;
  11347. vertex.z = points[ j ].x * cos;
  11348. vertices.push( vertex.x, vertex.y, vertex.z );
  11349. // uv
  11350. uv.x = i / segments;
  11351. uv.y = j / ( points.length - 1 );
  11352. uvs.push( uv.x, uv.y );
  11353. // normal
  11354. const x = initNormals[ 3 * j + 0 ] * sin;
  11355. const y = initNormals[ 3 * j + 1 ];
  11356. const z = initNormals[ 3 * j + 0 ] * cos;
  11357. normals.push( x, y, z );
  11358. }
  11359. }
  11360. // indices
  11361. for ( let i = 0; i < segments; i ++ ) {
  11362. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11363. const base = j + i * points.length;
  11364. const a = base;
  11365. const b = base + points.length;
  11366. const c = base + points.length + 1;
  11367. const d = base + 1;
  11368. // faces
  11369. indices.push( a, b, d );
  11370. indices.push( c, d, b );
  11371. }
  11372. }
  11373. // build geometry
  11374. this.setIndex( indices );
  11375. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11376. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11377. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11378. }
  11379. copy( source ) {
  11380. super.copy( source );
  11381. this.parameters = Object.assign( {}, source.parameters );
  11382. return this;
  11383. }
  11384. static fromJSON( data ) {
  11385. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11386. }
  11387. }
  11388. class CapsuleGeometry extends LatheGeometry {
  11389. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11390. const path = new Path();
  11391. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11392. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11393. super( path.getPoints( capSegments ), radialSegments );
  11394. this.type = 'CapsuleGeometry';
  11395. this.parameters = {
  11396. radius: radius,
  11397. length: length,
  11398. capSegments: capSegments,
  11399. radialSegments: radialSegments,
  11400. };
  11401. }
  11402. static fromJSON( data ) {
  11403. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11404. }
  11405. }
  11406. class CircleGeometry extends BufferGeometry {
  11407. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11408. super();
  11409. this.type = 'CircleGeometry';
  11410. this.parameters = {
  11411. radius: radius,
  11412. segments: segments,
  11413. thetaStart: thetaStart,
  11414. thetaLength: thetaLength
  11415. };
  11416. segments = Math.max( 3, segments );
  11417. // buffers
  11418. const indices = [];
  11419. const vertices = [];
  11420. const normals = [];
  11421. const uvs = [];
  11422. // helper variables
  11423. const vertex = new Vector3();
  11424. const uv = new Vector2();
  11425. // center point
  11426. vertices.push( 0, 0, 0 );
  11427. normals.push( 0, 0, 1 );
  11428. uvs.push( 0.5, 0.5 );
  11429. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11430. const segment = thetaStart + s / segments * thetaLength;
  11431. // vertex
  11432. vertex.x = radius * Math.cos( segment );
  11433. vertex.y = radius * Math.sin( segment );
  11434. vertices.push( vertex.x, vertex.y, vertex.z );
  11435. // normal
  11436. normals.push( 0, 0, 1 );
  11437. // uvs
  11438. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11439. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11440. uvs.push( uv.x, uv.y );
  11441. }
  11442. // indices
  11443. for ( let i = 1; i <= segments; i ++ ) {
  11444. indices.push( i, i + 1, 0 );
  11445. }
  11446. // build geometry
  11447. this.setIndex( indices );
  11448. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11449. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11450. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11451. }
  11452. copy( source ) {
  11453. super.copy( source );
  11454. this.parameters = Object.assign( {}, source.parameters );
  11455. return this;
  11456. }
  11457. static fromJSON( data ) {
  11458. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11459. }
  11460. }
  11461. class CylinderGeometry extends BufferGeometry {
  11462. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11463. super();
  11464. this.type = 'CylinderGeometry';
  11465. this.parameters = {
  11466. radiusTop: radiusTop,
  11467. radiusBottom: radiusBottom,
  11468. height: height,
  11469. radialSegments: radialSegments,
  11470. heightSegments: heightSegments,
  11471. openEnded: openEnded,
  11472. thetaStart: thetaStart,
  11473. thetaLength: thetaLength
  11474. };
  11475. const scope = this;
  11476. radialSegments = Math.floor( radialSegments );
  11477. heightSegments = Math.floor( heightSegments );
  11478. // buffers
  11479. const indices = [];
  11480. const vertices = [];
  11481. const normals = [];
  11482. const uvs = [];
  11483. // helper variables
  11484. let index = 0;
  11485. const indexArray = [];
  11486. const halfHeight = height / 2;
  11487. let groupStart = 0;
  11488. // generate geometry
  11489. generateTorso();
  11490. if ( openEnded === false ) {
  11491. if ( radiusTop > 0 ) generateCap( true );
  11492. if ( radiusBottom > 0 ) generateCap( false );
  11493. }
  11494. // build geometry
  11495. this.setIndex( indices );
  11496. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11497. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11498. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11499. function generateTorso() {
  11500. const normal = new Vector3();
  11501. const vertex = new Vector3();
  11502. let groupCount = 0;
  11503. // this will be used to calculate the normal
  11504. const slope = ( radiusBottom - radiusTop ) / height;
  11505. // generate vertices, normals and uvs
  11506. for ( let y = 0; y <= heightSegments; y ++ ) {
  11507. const indexRow = [];
  11508. const v = y / heightSegments;
  11509. // calculate the radius of the current row
  11510. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11511. for ( let x = 0; x <= radialSegments; x ++ ) {
  11512. const u = x / radialSegments;
  11513. const theta = u * thetaLength + thetaStart;
  11514. const sinTheta = Math.sin( theta );
  11515. const cosTheta = Math.cos( theta );
  11516. // vertex
  11517. vertex.x = radius * sinTheta;
  11518. vertex.y = - v * height + halfHeight;
  11519. vertex.z = radius * cosTheta;
  11520. vertices.push( vertex.x, vertex.y, vertex.z );
  11521. // normal
  11522. normal.set( sinTheta, slope, cosTheta ).normalize();
  11523. normals.push( normal.x, normal.y, normal.z );
  11524. // uv
  11525. uvs.push( u, 1 - v );
  11526. // save index of vertex in respective row
  11527. indexRow.push( index ++ );
  11528. }
  11529. // now save vertices of the row in our index array
  11530. indexArray.push( indexRow );
  11531. }
  11532. // generate indices
  11533. for ( let x = 0; x < radialSegments; x ++ ) {
  11534. for ( let y = 0; y < heightSegments; y ++ ) {
  11535. // we use the index array to access the correct indices
  11536. const a = indexArray[ y ][ x ];
  11537. const b = indexArray[ y + 1 ][ x ];
  11538. const c = indexArray[ y + 1 ][ x + 1 ];
  11539. const d = indexArray[ y ][ x + 1 ];
  11540. // faces
  11541. indices.push( a, b, d );
  11542. indices.push( b, c, d );
  11543. // update group counter
  11544. groupCount += 6;
  11545. }
  11546. }
  11547. // add a group to the geometry. this will ensure multi material support
  11548. scope.addGroup( groupStart, groupCount, 0 );
  11549. // calculate new start value for groups
  11550. groupStart += groupCount;
  11551. }
  11552. function generateCap( top ) {
  11553. // save the index of the first center vertex
  11554. const centerIndexStart = index;
  11555. const uv = new Vector2();
  11556. const vertex = new Vector3();
  11557. let groupCount = 0;
  11558. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11559. const sign = ( top === true ) ? 1 : - 1;
  11560. // first we generate the center vertex data of the cap.
  11561. // because the geometry needs one set of uvs per face,
  11562. // we must generate a center vertex per face/segment
  11563. for ( let x = 1; x <= radialSegments; x ++ ) {
  11564. // vertex
  11565. vertices.push( 0, halfHeight * sign, 0 );
  11566. // normal
  11567. normals.push( 0, sign, 0 );
  11568. // uv
  11569. uvs.push( 0.5, 0.5 );
  11570. // increase index
  11571. index ++;
  11572. }
  11573. // save the index of the last center vertex
  11574. const centerIndexEnd = index;
  11575. // now we generate the surrounding vertices, normals and uvs
  11576. for ( let x = 0; x <= radialSegments; x ++ ) {
  11577. const u = x / radialSegments;
  11578. const theta = u * thetaLength + thetaStart;
  11579. const cosTheta = Math.cos( theta );
  11580. const sinTheta = Math.sin( theta );
  11581. // vertex
  11582. vertex.x = radius * sinTheta;
  11583. vertex.y = halfHeight * sign;
  11584. vertex.z = radius * cosTheta;
  11585. vertices.push( vertex.x, vertex.y, vertex.z );
  11586. // normal
  11587. normals.push( 0, sign, 0 );
  11588. // uv
  11589. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11590. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11591. uvs.push( uv.x, uv.y );
  11592. // increase index
  11593. index ++;
  11594. }
  11595. // generate indices
  11596. for ( let x = 0; x < radialSegments; x ++ ) {
  11597. const c = centerIndexStart + x;
  11598. const i = centerIndexEnd + x;
  11599. if ( top === true ) {
  11600. // face top
  11601. indices.push( i, i + 1, c );
  11602. } else {
  11603. // face bottom
  11604. indices.push( i + 1, i, c );
  11605. }
  11606. groupCount += 3;
  11607. }
  11608. // add a group to the geometry. this will ensure multi material support
  11609. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11610. // calculate new start value for groups
  11611. groupStart += groupCount;
  11612. }
  11613. }
  11614. copy( source ) {
  11615. super.copy( source );
  11616. this.parameters = Object.assign( {}, source.parameters );
  11617. return this;
  11618. }
  11619. static fromJSON( data ) {
  11620. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11621. }
  11622. }
  11623. class ConeGeometry extends CylinderGeometry {
  11624. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11625. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11626. this.type = 'ConeGeometry';
  11627. this.parameters = {
  11628. radius: radius,
  11629. height: height,
  11630. radialSegments: radialSegments,
  11631. heightSegments: heightSegments,
  11632. openEnded: openEnded,
  11633. thetaStart: thetaStart,
  11634. thetaLength: thetaLength
  11635. };
  11636. }
  11637. static fromJSON( data ) {
  11638. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11639. }
  11640. }
  11641. class PolyhedronGeometry extends BufferGeometry {
  11642. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11643. super();
  11644. this.type = 'PolyhedronGeometry';
  11645. this.parameters = {
  11646. vertices: vertices,
  11647. indices: indices,
  11648. radius: radius,
  11649. detail: detail
  11650. };
  11651. // default buffer data
  11652. const vertexBuffer = [];
  11653. const uvBuffer = [];
  11654. // the subdivision creates the vertex buffer data
  11655. subdivide( detail );
  11656. // all vertices should lie on a conceptual sphere with a given radius
  11657. applyRadius( radius );
  11658. // finally, create the uv data
  11659. generateUVs();
  11660. // build non-indexed geometry
  11661. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11662. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11663. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11664. if ( detail === 0 ) {
  11665. this.computeVertexNormals(); // flat normals
  11666. } else {
  11667. this.normalizeNormals(); // smooth normals
  11668. }
  11669. // helper functions
  11670. function subdivide( detail ) {
  11671. const a = new Vector3();
  11672. const b = new Vector3();
  11673. const c = new Vector3();
  11674. // iterate over all faces and apply a subdivision with the given detail value
  11675. for ( let i = 0; i < indices.length; i += 3 ) {
  11676. // get the vertices of the face
  11677. getVertexByIndex( indices[ i + 0 ], a );
  11678. getVertexByIndex( indices[ i + 1 ], b );
  11679. getVertexByIndex( indices[ i + 2 ], c );
  11680. // perform subdivision
  11681. subdivideFace( a, b, c, detail );
  11682. }
  11683. }
  11684. function subdivideFace( a, b, c, detail ) {
  11685. const cols = detail + 1;
  11686. // we use this multidimensional array as a data structure for creating the subdivision
  11687. const v = [];
  11688. // construct all of the vertices for this subdivision
  11689. for ( let i = 0; i <= cols; i ++ ) {
  11690. v[ i ] = [];
  11691. const aj = a.clone().lerp( c, i / cols );
  11692. const bj = b.clone().lerp( c, i / cols );
  11693. const rows = cols - i;
  11694. for ( let j = 0; j <= rows; j ++ ) {
  11695. if ( j === 0 && i === cols ) {
  11696. v[ i ][ j ] = aj;
  11697. } else {
  11698. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11699. }
  11700. }
  11701. }
  11702. // construct all of the faces
  11703. for ( let i = 0; i < cols; i ++ ) {
  11704. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11705. const k = Math.floor( j / 2 );
  11706. if ( j % 2 === 0 ) {
  11707. pushVertex( v[ i ][ k + 1 ] );
  11708. pushVertex( v[ i + 1 ][ k ] );
  11709. pushVertex( v[ i ][ k ] );
  11710. } else {
  11711. pushVertex( v[ i ][ k + 1 ] );
  11712. pushVertex( v[ i + 1 ][ k + 1 ] );
  11713. pushVertex( v[ i + 1 ][ k ] );
  11714. }
  11715. }
  11716. }
  11717. }
  11718. function applyRadius( radius ) {
  11719. const vertex = new Vector3();
  11720. // iterate over the entire buffer and apply the radius to each vertex
  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. vertex.normalize().multiplyScalar( radius );
  11726. vertexBuffer[ i + 0 ] = vertex.x;
  11727. vertexBuffer[ i + 1 ] = vertex.y;
  11728. vertexBuffer[ i + 2 ] = vertex.z;
  11729. }
  11730. }
  11731. function generateUVs() {
  11732. const vertex = new Vector3();
  11733. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11734. vertex.x = vertexBuffer[ i + 0 ];
  11735. vertex.y = vertexBuffer[ i + 1 ];
  11736. vertex.z = vertexBuffer[ i + 2 ];
  11737. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11738. const v = inclination( vertex ) / Math.PI + 0.5;
  11739. uvBuffer.push( u, 1 - v );
  11740. }
  11741. correctUVs();
  11742. correctSeam();
  11743. }
  11744. function correctSeam() {
  11745. // handle case when face straddles the seam, see #3269
  11746. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11747. // uv data of a single face
  11748. const x0 = uvBuffer[ i + 0 ];
  11749. const x1 = uvBuffer[ i + 2 ];
  11750. const x2 = uvBuffer[ i + 4 ];
  11751. const max = Math.max( x0, x1, x2 );
  11752. const min = Math.min( x0, x1, x2 );
  11753. // 0.9 is somewhat arbitrary
  11754. if ( max > 0.9 && min < 0.1 ) {
  11755. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11756. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11757. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11758. }
  11759. }
  11760. }
  11761. function pushVertex( vertex ) {
  11762. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11763. }
  11764. function getVertexByIndex( index, vertex ) {
  11765. const stride = index * 3;
  11766. vertex.x = vertices[ stride + 0 ];
  11767. vertex.y = vertices[ stride + 1 ];
  11768. vertex.z = vertices[ stride + 2 ];
  11769. }
  11770. function correctUVs() {
  11771. const a = new Vector3();
  11772. const b = new Vector3();
  11773. const c = new Vector3();
  11774. const centroid = new Vector3();
  11775. const uvA = new Vector2();
  11776. const uvB = new Vector2();
  11777. const uvC = new Vector2();
  11778. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11779. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11780. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11781. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11782. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11783. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11784. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11785. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11786. const azi = azimuth( centroid );
  11787. correctUV( uvA, j + 0, a, azi );
  11788. correctUV( uvB, j + 2, b, azi );
  11789. correctUV( uvC, j + 4, c, azi );
  11790. }
  11791. }
  11792. function correctUV( uv, stride, vector, azimuth ) {
  11793. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11794. uvBuffer[ stride ] = uv.x - 1;
  11795. }
  11796. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11797. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11798. }
  11799. }
  11800. // Angle around the Y axis, counter-clockwise when looking from above.
  11801. function azimuth( vector ) {
  11802. return Math.atan2( vector.z, - vector.x );
  11803. }
  11804. // Angle above the XZ plane.
  11805. function inclination( vector ) {
  11806. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11807. }
  11808. }
  11809. copy( source ) {
  11810. super.copy( source );
  11811. this.parameters = Object.assign( {}, source.parameters );
  11812. return this;
  11813. }
  11814. static fromJSON( data ) {
  11815. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11816. }
  11817. }
  11818. class DodecahedronGeometry extends PolyhedronGeometry {
  11819. constructor( radius = 1, detail = 0 ) {
  11820. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11821. const r = 1 / t;
  11822. const vertices = [
  11823. // (±1, ±1, ±1)
  11824. - 1, - 1, - 1, - 1, - 1, 1,
  11825. - 1, 1, - 1, - 1, 1, 1,
  11826. 1, - 1, - 1, 1, - 1, 1,
  11827. 1, 1, - 1, 1, 1, 1,
  11828. // (0, ±1/φ, ±φ)
  11829. 0, - r, - t, 0, - r, t,
  11830. 0, r, - t, 0, r, t,
  11831. // (±1/φ, ±φ, 0)
  11832. - r, - t, 0, - r, t, 0,
  11833. r, - t, 0, r, t, 0,
  11834. // (±φ, 0, ±1/φ)
  11835. - t, 0, - r, t, 0, - r,
  11836. - t, 0, r, t, 0, r
  11837. ];
  11838. const indices = [
  11839. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11840. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11841. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11842. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11843. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11844. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11845. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11846. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11847. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11848. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11849. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11850. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11851. ];
  11852. super( vertices, indices, radius, detail );
  11853. this.type = 'DodecahedronGeometry';
  11854. this.parameters = {
  11855. radius: radius,
  11856. detail: detail
  11857. };
  11858. }
  11859. static fromJSON( data ) {
  11860. return new DodecahedronGeometry( data.radius, data.detail );
  11861. }
  11862. }
  11863. const _v0 = /*@__PURE__*/ new Vector3();
  11864. const _v1$1 = /*@__PURE__*/ new Vector3();
  11865. const _normal$1 = /*@__PURE__*/ new Vector3();
  11866. const _triangle = /*@__PURE__*/ new Triangle();
  11867. class EdgesGeometry extends BufferGeometry {
  11868. constructor( geometry = null, thresholdAngle = 1 ) {
  11869. super();
  11870. this.type = 'EdgesGeometry';
  11871. this.parameters = {
  11872. geometry: geometry,
  11873. thresholdAngle: thresholdAngle
  11874. };
  11875. if ( geometry !== null ) {
  11876. const precisionPoints = 4;
  11877. const precision = Math.pow( 10, precisionPoints );
  11878. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11879. const indexAttr = geometry.getIndex();
  11880. const positionAttr = geometry.getAttribute( 'position' );
  11881. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11882. const indexArr = [ 0, 0, 0 ];
  11883. const vertKeys = [ 'a', 'b', 'c' ];
  11884. const hashes = new Array( 3 );
  11885. const edgeData = {};
  11886. const vertices = [];
  11887. for ( let i = 0; i < indexCount; i += 3 ) {
  11888. if ( indexAttr ) {
  11889. indexArr[ 0 ] = indexAttr.getX( i );
  11890. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11891. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11892. } else {
  11893. indexArr[ 0 ] = i;
  11894. indexArr[ 1 ] = i + 1;
  11895. indexArr[ 2 ] = i + 2;
  11896. }
  11897. const { a, b, c } = _triangle;
  11898. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11899. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11900. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11901. _triangle.getNormal( _normal$1 );
  11902. // create hashes for the edge from the vertices
  11903. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11904. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11905. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11906. // skip degenerate triangles
  11907. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11908. continue;
  11909. }
  11910. // iterate over every edge
  11911. for ( let j = 0; j < 3; j ++ ) {
  11912. // get the first and next vertex making up the edge
  11913. const jNext = ( j + 1 ) % 3;
  11914. const vecHash0 = hashes[ j ];
  11915. const vecHash1 = hashes[ jNext ];
  11916. const v0 = _triangle[ vertKeys[ j ] ];
  11917. const v1 = _triangle[ vertKeys[ jNext ] ];
  11918. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11919. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11920. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11921. // if we found a sibling edge add it into the vertex array if
  11922. // it meets the angle threshold and delete the edge from the map.
  11923. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11924. vertices.push( v0.x, v0.y, v0.z );
  11925. vertices.push( v1.x, v1.y, v1.z );
  11926. }
  11927. edgeData[ reverseHash ] = null;
  11928. } else if ( ! ( hash in edgeData ) ) {
  11929. // if we've already got an edge here then skip adding a new one
  11930. edgeData[ hash ] = {
  11931. index0: indexArr[ j ],
  11932. index1: indexArr[ jNext ],
  11933. normal: _normal$1.clone(),
  11934. };
  11935. }
  11936. }
  11937. }
  11938. // iterate over all remaining, unmatched edges and add them to the vertex array
  11939. for ( const key in edgeData ) {
  11940. if ( edgeData[ key ] ) {
  11941. const { index0, index1 } = edgeData[ key ];
  11942. _v0.fromBufferAttribute( positionAttr, index0 );
  11943. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11944. vertices.push( _v0.x, _v0.y, _v0.z );
  11945. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11946. }
  11947. }
  11948. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11949. }
  11950. }
  11951. copy( source ) {
  11952. super.copy( source );
  11953. this.parameters = Object.assign( {}, source.parameters );
  11954. return this;
  11955. }
  11956. }
  11957. class Shape extends Path {
  11958. constructor( points ) {
  11959. super( points );
  11960. this.uuid = generateUUID();
  11961. this.type = 'Shape';
  11962. this.holes = [];
  11963. }
  11964. getPointsHoles( divisions ) {
  11965. const holesPts = [];
  11966. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11967. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  11968. }
  11969. return holesPts;
  11970. }
  11971. // get points of shape and holes (keypoints based on segments parameter)
  11972. extractPoints( divisions ) {
  11973. return {
  11974. shape: this.getPoints( divisions ),
  11975. holes: this.getPointsHoles( divisions )
  11976. };
  11977. }
  11978. copy( source ) {
  11979. super.copy( source );
  11980. this.holes = [];
  11981. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  11982. const hole = source.holes[ i ];
  11983. this.holes.push( hole.clone() );
  11984. }
  11985. return this;
  11986. }
  11987. toJSON() {
  11988. const data = super.toJSON();
  11989. data.uuid = this.uuid;
  11990. data.holes = [];
  11991. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11992. const hole = this.holes[ i ];
  11993. data.holes.push( hole.toJSON() );
  11994. }
  11995. return data;
  11996. }
  11997. fromJSON( json ) {
  11998. super.fromJSON( json );
  11999. this.uuid = json.uuid;
  12000. this.holes = [];
  12001. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12002. const hole = json.holes[ i ];
  12003. this.holes.push( new Path().fromJSON( hole ) );
  12004. }
  12005. return this;
  12006. }
  12007. }
  12008. /**
  12009. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12010. */
  12011. const Earcut = {
  12012. triangulate: function ( data, holeIndices, dim = 2 ) {
  12013. const hasHoles = holeIndices && holeIndices.length;
  12014. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12015. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12016. const triangles = [];
  12017. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12018. let minX, minY, maxX, maxY, x, y, invSize;
  12019. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12020. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12021. if ( data.length > 80 * dim ) {
  12022. minX = maxX = data[ 0 ];
  12023. minY = maxY = data[ 1 ];
  12024. for ( let i = dim; i < outerLen; i += dim ) {
  12025. x = data[ i ];
  12026. y = data[ i + 1 ];
  12027. if ( x < minX ) minX = x;
  12028. if ( y < minY ) minY = y;
  12029. if ( x > maxX ) maxX = x;
  12030. if ( y > maxY ) maxY = y;
  12031. }
  12032. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12033. invSize = Math.max( maxX - minX, maxY - minY );
  12034. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12035. }
  12036. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12037. return triangles;
  12038. }
  12039. };
  12040. // create a circular doubly linked list from polygon points in the specified winding order
  12041. function linkedList( data, start, end, dim, clockwise ) {
  12042. let i, last;
  12043. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12044. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12045. } else {
  12046. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12047. }
  12048. if ( last && equals$1( last, last.next ) ) {
  12049. removeNode( last );
  12050. last = last.next;
  12051. }
  12052. return last;
  12053. }
  12054. // eliminate colinear or duplicate points
  12055. function filterPoints( start, end ) {
  12056. if ( ! start ) return start;
  12057. if ( ! end ) end = start;
  12058. let p = start,
  12059. again;
  12060. do {
  12061. again = false;
  12062. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12063. removeNode( p );
  12064. p = end = p.prev;
  12065. if ( p === p.next ) break;
  12066. again = true;
  12067. } else {
  12068. p = p.next;
  12069. }
  12070. } while ( again || p !== end );
  12071. return end;
  12072. }
  12073. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12074. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12075. if ( ! ear ) return;
  12076. // interlink polygon nodes in z-order
  12077. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12078. let stop = ear,
  12079. prev, next;
  12080. // iterate through ears, slicing them one by one
  12081. while ( ear.prev !== ear.next ) {
  12082. prev = ear.prev;
  12083. next = ear.next;
  12084. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12085. // cut off the triangle
  12086. triangles.push( prev.i / dim | 0 );
  12087. triangles.push( ear.i / dim | 0 );
  12088. triangles.push( next.i / dim | 0 );
  12089. removeNode( ear );
  12090. // skipping the next vertex leads to less sliver triangles
  12091. ear = next.next;
  12092. stop = next.next;
  12093. continue;
  12094. }
  12095. ear = next;
  12096. // if we looped through the whole remaining polygon and can't find any more ears
  12097. if ( ear === stop ) {
  12098. // try filtering points and slicing again
  12099. if ( ! pass ) {
  12100. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12101. // if this didn't work, try curing all small self-intersections locally
  12102. } else if ( pass === 1 ) {
  12103. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12104. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12105. // as a last resort, try splitting the remaining polygon into two
  12106. } else if ( pass === 2 ) {
  12107. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12108. }
  12109. break;
  12110. }
  12111. }
  12112. }
  12113. // check whether a polygon node forms a valid ear with adjacent nodes
  12114. function isEar( ear ) {
  12115. const a = ear.prev,
  12116. b = ear,
  12117. c = ear.next;
  12118. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12119. // now make sure we don't have other points inside the potential ear
  12120. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12121. // triangle bbox; min & max are calculated like this for speed
  12122. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12123. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12124. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12125. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12126. let p = c.next;
  12127. while ( p !== a ) {
  12128. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12129. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12130. area( p.prev, p, p.next ) >= 0 ) return false;
  12131. p = p.next;
  12132. }
  12133. return true;
  12134. }
  12135. function isEarHashed( ear, minX, minY, invSize ) {
  12136. const a = ear.prev,
  12137. b = ear,
  12138. c = ear.next;
  12139. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12140. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12141. // triangle bbox; min & max are calculated like this for speed
  12142. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12143. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12144. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12145. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12146. // z-order range for the current triangle bbox;
  12147. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12148. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12149. let p = ear.prevZ,
  12150. n = ear.nextZ;
  12151. // look for points inside the triangle in both directions
  12152. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12153. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12154. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12155. p = p.prevZ;
  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. // look for remaining points in decreasing z-order
  12161. while ( p && p.z >= minZ ) {
  12162. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12163. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12164. p = p.prevZ;
  12165. }
  12166. // look for remaining points in increasing z-order
  12167. while ( n && n.z <= maxZ ) {
  12168. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12169. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12170. n = n.nextZ;
  12171. }
  12172. return true;
  12173. }
  12174. // go through all polygon nodes and cure small local self-intersections
  12175. function cureLocalIntersections( start, triangles, dim ) {
  12176. let p = start;
  12177. do {
  12178. const a = p.prev,
  12179. b = p.next.next;
  12180. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12181. triangles.push( a.i / dim | 0 );
  12182. triangles.push( p.i / dim | 0 );
  12183. triangles.push( b.i / dim | 0 );
  12184. // remove two nodes involved
  12185. removeNode( p );
  12186. removeNode( p.next );
  12187. p = start = b;
  12188. }
  12189. p = p.next;
  12190. } while ( p !== start );
  12191. return filterPoints( p );
  12192. }
  12193. // try splitting polygon into two and triangulate them independently
  12194. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12195. // look for a valid diagonal that divides the polygon into two
  12196. let a = start;
  12197. do {
  12198. let b = a.next.next;
  12199. while ( b !== a.prev ) {
  12200. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12201. // split the polygon in two by the diagonal
  12202. let c = splitPolygon( a, b );
  12203. // filter colinear points around the cuts
  12204. a = filterPoints( a, a.next );
  12205. c = filterPoints( c, c.next );
  12206. // run earcut on each half
  12207. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12208. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12209. return;
  12210. }
  12211. b = b.next;
  12212. }
  12213. a = a.next;
  12214. } while ( a !== start );
  12215. }
  12216. // link every hole into the outer loop, producing a single-ring polygon without holes
  12217. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12218. const queue = [];
  12219. let i, len, start, end, list;
  12220. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12221. start = holeIndices[ i ] * dim;
  12222. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12223. list = linkedList( data, start, end, dim, false );
  12224. if ( list === list.next ) list.steiner = true;
  12225. queue.push( getLeftmost( list ) );
  12226. }
  12227. queue.sort( compareX );
  12228. // process holes from left to right
  12229. for ( i = 0; i < queue.length; i ++ ) {
  12230. outerNode = eliminateHole( queue[ i ], outerNode );
  12231. }
  12232. return outerNode;
  12233. }
  12234. function compareX( a, b ) {
  12235. return a.x - b.x;
  12236. }
  12237. // find a bridge between vertices that connects hole with an outer ring and link it
  12238. function eliminateHole( hole, outerNode ) {
  12239. const bridge = findHoleBridge( hole, outerNode );
  12240. if ( ! bridge ) {
  12241. return outerNode;
  12242. }
  12243. const bridgeReverse = splitPolygon( bridge, hole );
  12244. // filter collinear points around the cuts
  12245. filterPoints( bridgeReverse, bridgeReverse.next );
  12246. return filterPoints( bridge, bridge.next );
  12247. }
  12248. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12249. function findHoleBridge( hole, outerNode ) {
  12250. let p = outerNode,
  12251. qx = - Infinity,
  12252. m;
  12253. const hx = hole.x, hy = hole.y;
  12254. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12255. // segment's endpoint with lesser x will be potential connection point
  12256. do {
  12257. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12258. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12259. if ( x <= hx && x > qx ) {
  12260. qx = x;
  12261. m = p.x < p.next.x ? p : p.next;
  12262. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12263. }
  12264. }
  12265. p = p.next;
  12266. } while ( p !== outerNode );
  12267. if ( ! m ) return null;
  12268. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12269. // if there are no points found, we have a valid connection;
  12270. // otherwise choose the point of the minimum angle with the ray as connection point
  12271. const stop = m,
  12272. mx = m.x,
  12273. my = m.y;
  12274. let tanMin = Infinity, tan;
  12275. p = m;
  12276. do {
  12277. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12278. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12279. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12280. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12281. m = p;
  12282. tanMin = tan;
  12283. }
  12284. }
  12285. p = p.next;
  12286. } while ( p !== stop );
  12287. return m;
  12288. }
  12289. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12290. function sectorContainsSector( m, p ) {
  12291. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12292. }
  12293. // interlink polygon nodes in z-order
  12294. function indexCurve( start, minX, minY, invSize ) {
  12295. let p = start;
  12296. do {
  12297. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12298. p.prevZ = p.prev;
  12299. p.nextZ = p.next;
  12300. p = p.next;
  12301. } while ( p !== start );
  12302. p.prevZ.nextZ = null;
  12303. p.prevZ = null;
  12304. sortLinked( p );
  12305. }
  12306. // Simon Tatham's linked list merge sort algorithm
  12307. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12308. function sortLinked( list ) {
  12309. let i, p, q, e, tail, numMerges, pSize, qSize,
  12310. inSize = 1;
  12311. do {
  12312. p = list;
  12313. list = null;
  12314. tail = null;
  12315. numMerges = 0;
  12316. while ( p ) {
  12317. numMerges ++;
  12318. q = p;
  12319. pSize = 0;
  12320. for ( i = 0; i < inSize; i ++ ) {
  12321. pSize ++;
  12322. q = q.nextZ;
  12323. if ( ! q ) break;
  12324. }
  12325. qSize = inSize;
  12326. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12327. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12328. e = p;
  12329. p = p.nextZ;
  12330. pSize --;
  12331. } else {
  12332. e = q;
  12333. q = q.nextZ;
  12334. qSize --;
  12335. }
  12336. if ( tail ) tail.nextZ = e;
  12337. else list = e;
  12338. e.prevZ = tail;
  12339. tail = e;
  12340. }
  12341. p = q;
  12342. }
  12343. tail.nextZ = null;
  12344. inSize *= 2;
  12345. } while ( numMerges > 1 );
  12346. return list;
  12347. }
  12348. // z-order of a point given coords and inverse of the longer side of data bbox
  12349. function zOrder( x, y, minX, minY, invSize ) {
  12350. // coords are transformed into non-negative 15-bit integer range
  12351. x = ( x - minX ) * invSize | 0;
  12352. y = ( y - minY ) * invSize | 0;
  12353. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12354. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12355. x = ( x | ( x << 2 ) ) & 0x33333333;
  12356. x = ( x | ( x << 1 ) ) & 0x55555555;
  12357. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12358. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12359. y = ( y | ( y << 2 ) ) & 0x33333333;
  12360. y = ( y | ( y << 1 ) ) & 0x55555555;
  12361. return x | ( y << 1 );
  12362. }
  12363. // find the leftmost node of a polygon ring
  12364. function getLeftmost( start ) {
  12365. let p = start,
  12366. leftmost = start;
  12367. do {
  12368. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12369. p = p.next;
  12370. } while ( p !== start );
  12371. return leftmost;
  12372. }
  12373. // check if a point lies within a convex triangle
  12374. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12375. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12376. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12377. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12378. }
  12379. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12380. function isValidDiagonal( a, b ) {
  12381. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12382. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12383. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12384. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12385. }
  12386. // signed area of a triangle
  12387. function area( p, q, r ) {
  12388. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12389. }
  12390. // check if two points are equal
  12391. function equals$1( p1, p2 ) {
  12392. return p1.x === p2.x && p1.y === p2.y;
  12393. }
  12394. // check if two segments intersect
  12395. function intersects( p1, q1, p2, q2 ) {
  12396. const o1 = sign$1( area( p1, q1, p2 ) );
  12397. const o2 = sign$1( area( p1, q1, q2 ) );
  12398. const o3 = sign$1( area( p2, q2, p1 ) );
  12399. const o4 = sign$1( area( p2, q2, q1 ) );
  12400. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12401. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12402. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12403. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12404. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12405. return false;
  12406. }
  12407. // for collinear points p, q, r, check if point q lies on segment pr
  12408. function onSegment( p, q, r ) {
  12409. 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 );
  12410. }
  12411. function sign$1( num ) {
  12412. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12413. }
  12414. // check if a polygon diagonal intersects any polygon segments
  12415. function intersectsPolygon( a, b ) {
  12416. let p = a;
  12417. do {
  12418. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12419. intersects( p, p.next, a, b ) ) return true;
  12420. p = p.next;
  12421. } while ( p !== a );
  12422. return false;
  12423. }
  12424. // check if a polygon diagonal is locally inside the polygon
  12425. function locallyInside( a, b ) {
  12426. return area( a.prev, a, a.next ) < 0 ?
  12427. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12428. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12429. }
  12430. // check if the middle point of a polygon diagonal is inside the polygon
  12431. function middleInside( a, b ) {
  12432. let p = a,
  12433. inside = false;
  12434. const px = ( a.x + b.x ) / 2,
  12435. py = ( a.y + b.y ) / 2;
  12436. do {
  12437. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12438. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12439. inside = ! inside;
  12440. p = p.next;
  12441. } while ( p !== a );
  12442. return inside;
  12443. }
  12444. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12445. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12446. function splitPolygon( a, b ) {
  12447. const a2 = new Node$1( a.i, a.x, a.y ),
  12448. b2 = new Node$1( b.i, b.x, b.y ),
  12449. an = a.next,
  12450. bp = b.prev;
  12451. a.next = b;
  12452. b.prev = a;
  12453. a2.next = an;
  12454. an.prev = a2;
  12455. b2.next = a2;
  12456. a2.prev = b2;
  12457. bp.next = b2;
  12458. b2.prev = bp;
  12459. return b2;
  12460. }
  12461. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12462. function insertNode( i, x, y, last ) {
  12463. const p = new Node$1( i, x, y );
  12464. if ( ! last ) {
  12465. p.prev = p;
  12466. p.next = p;
  12467. } else {
  12468. p.next = last.next;
  12469. p.prev = last;
  12470. last.next.prev = p;
  12471. last.next = p;
  12472. }
  12473. return p;
  12474. }
  12475. function removeNode( p ) {
  12476. p.next.prev = p.prev;
  12477. p.prev.next = p.next;
  12478. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12479. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12480. }
  12481. function Node$1( i, x, y ) {
  12482. // vertex index in coordinates array
  12483. this.i = i;
  12484. // vertex coordinates
  12485. this.x = x;
  12486. this.y = y;
  12487. // previous and next vertex nodes in a polygon ring
  12488. this.prev = null;
  12489. this.next = null;
  12490. // z-order curve value
  12491. this.z = 0;
  12492. // previous and next nodes in z-order
  12493. this.prevZ = null;
  12494. this.nextZ = null;
  12495. // indicates whether this is a steiner point
  12496. this.steiner = false;
  12497. }
  12498. function signedArea( data, start, end, dim ) {
  12499. let sum = 0;
  12500. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12501. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12502. j = i;
  12503. }
  12504. return sum;
  12505. }
  12506. class ShapeUtils {
  12507. // calculate area of the contour polygon
  12508. static area( contour ) {
  12509. const n = contour.length;
  12510. let a = 0.0;
  12511. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12512. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12513. }
  12514. return a * 0.5;
  12515. }
  12516. static isClockWise( pts ) {
  12517. return ShapeUtils.area( pts ) < 0;
  12518. }
  12519. static triangulateShape( contour, holes ) {
  12520. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12521. const holeIndices = []; // array of hole indices
  12522. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12523. removeDupEndPts( contour );
  12524. addContour( vertices, contour );
  12525. //
  12526. let holeIndex = contour.length;
  12527. holes.forEach( removeDupEndPts );
  12528. for ( let i = 0; i < holes.length; i ++ ) {
  12529. holeIndices.push( holeIndex );
  12530. holeIndex += holes[ i ].length;
  12531. addContour( vertices, holes[ i ] );
  12532. }
  12533. //
  12534. const triangles = Earcut.triangulate( vertices, holeIndices );
  12535. //
  12536. for ( let i = 0; i < triangles.length; i += 3 ) {
  12537. faces.push( triangles.slice( i, i + 3 ) );
  12538. }
  12539. return faces;
  12540. }
  12541. }
  12542. function removeDupEndPts( points ) {
  12543. const l = points.length;
  12544. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12545. points.pop();
  12546. }
  12547. }
  12548. function addContour( vertices, contour ) {
  12549. for ( let i = 0; i < contour.length; i ++ ) {
  12550. vertices.push( contour[ i ].x );
  12551. vertices.push( contour[ i ].y );
  12552. }
  12553. }
  12554. /**
  12555. * Creates extruded geometry from a path shape.
  12556. *
  12557. * parameters = {
  12558. *
  12559. * curveSegments: <int>, // number of points on the curves
  12560. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12561. * depth: <float>, // Depth to extrude the shape
  12562. *
  12563. * bevelEnabled: <bool>, // turn on bevel
  12564. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12565. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12566. * bevelOffset: <float>, // how far from shape outline does bevel start
  12567. * bevelSegments: <int>, // number of bevel layers
  12568. *
  12569. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12570. *
  12571. * UVGenerator: <Object> // object that provides UV generator functions
  12572. *
  12573. * }
  12574. */
  12575. class ExtrudeGeometry extends BufferGeometry {
  12576. 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 = {} ) {
  12577. super();
  12578. this.type = 'ExtrudeGeometry';
  12579. this.parameters = {
  12580. shapes: shapes,
  12581. options: options
  12582. };
  12583. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12584. const scope = this;
  12585. const verticesArray = [];
  12586. const uvArray = [];
  12587. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12588. const shape = shapes[ i ];
  12589. addShape( shape );
  12590. }
  12591. // build geometry
  12592. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12593. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12594. this.computeVertexNormals();
  12595. // functions
  12596. function addShape( shape ) {
  12597. const placeholder = [];
  12598. // options
  12599. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12600. const steps = options.steps !== undefined ? options.steps : 1;
  12601. const depth = options.depth !== undefined ? options.depth : 1;
  12602. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12603. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12604. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12605. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12606. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12607. const extrudePath = options.extrudePath;
  12608. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12609. //
  12610. let extrudePts, extrudeByPath = false;
  12611. let splineTube, binormal, normal, position2;
  12612. if ( extrudePath ) {
  12613. extrudePts = extrudePath.getSpacedPoints( steps );
  12614. extrudeByPath = true;
  12615. bevelEnabled = false; // bevels not supported for path extrusion
  12616. // SETUP TNB variables
  12617. // TODO1 - have a .isClosed in spline?
  12618. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12619. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12620. binormal = new Vector3();
  12621. normal = new Vector3();
  12622. position2 = new Vector3();
  12623. }
  12624. // Safeguards if bevels are not enabled
  12625. if ( ! bevelEnabled ) {
  12626. bevelSegments = 0;
  12627. bevelThickness = 0;
  12628. bevelSize = 0;
  12629. bevelOffset = 0;
  12630. }
  12631. // Variables initialization
  12632. const shapePoints = shape.extractPoints( curveSegments );
  12633. let vertices = shapePoints.shape;
  12634. const holes = shapePoints.holes;
  12635. const reverse = ! ShapeUtils.isClockWise( vertices );
  12636. if ( reverse ) {
  12637. vertices = vertices.reverse();
  12638. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12639. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12640. const ahole = holes[ h ];
  12641. if ( ShapeUtils.isClockWise( ahole ) ) {
  12642. holes[ h ] = ahole.reverse();
  12643. }
  12644. }
  12645. }
  12646. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12647. /* Vertices */
  12648. const contour = vertices; // vertices has all points but contour has only points of circumference
  12649. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12650. const ahole = holes[ h ];
  12651. vertices = vertices.concat( ahole );
  12652. }
  12653. function scalePt2( pt, vec, size ) {
  12654. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12655. return pt.clone().addScaledVector( vec, size );
  12656. }
  12657. const vlen = vertices.length, flen = faces.length;
  12658. // Find directions for point movement
  12659. function getBevelVec( inPt, inPrev, inNext ) {
  12660. // computes for inPt the corresponding point inPt' on a new contour
  12661. // shifted by 1 unit (length of normalized vector) to the left
  12662. // if we walk along contour clockwise, this new contour is outside the old one
  12663. //
  12664. // inPt' is the intersection of the two lines parallel to the two
  12665. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12666. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12667. // good reading for geometry algorithms (here: line-line intersection)
  12668. // http://geomalgorithms.com/a05-_intersect-1.html
  12669. const v_prev_x = inPt.x - inPrev.x,
  12670. v_prev_y = inPt.y - inPrev.y;
  12671. const v_next_x = inNext.x - inPt.x,
  12672. v_next_y = inNext.y - inPt.y;
  12673. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12674. // check for collinear edges
  12675. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12676. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12677. // not collinear
  12678. // length of vectors for normalizing
  12679. const v_prev_len = Math.sqrt( v_prev_lensq );
  12680. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12681. // shift adjacent points by unit vectors to the left
  12682. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12683. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12684. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12685. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12686. // scaling factor for v_prev to intersection point
  12687. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12688. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12689. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12690. // vector from inPt to intersection point
  12691. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12692. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12693. // Don't normalize!, otherwise sharp corners become ugly
  12694. // but prevent crazy spikes
  12695. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12696. if ( v_trans_lensq <= 2 ) {
  12697. return new Vector2( v_trans_x, v_trans_y );
  12698. } else {
  12699. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12700. }
  12701. } else {
  12702. // handle special case of collinear edges
  12703. let direction_eq = false; // assumes: opposite
  12704. if ( v_prev_x > Number.EPSILON ) {
  12705. if ( v_next_x > Number.EPSILON ) {
  12706. direction_eq = true;
  12707. }
  12708. } else {
  12709. if ( v_prev_x < - Number.EPSILON ) {
  12710. if ( v_next_x < - Number.EPSILON ) {
  12711. direction_eq = true;
  12712. }
  12713. } else {
  12714. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12715. direction_eq = true;
  12716. }
  12717. }
  12718. }
  12719. if ( direction_eq ) {
  12720. // console.log("Warning: lines are a straight sequence");
  12721. v_trans_x = - v_prev_y;
  12722. v_trans_y = v_prev_x;
  12723. shrink_by = Math.sqrt( v_prev_lensq );
  12724. } else {
  12725. // console.log("Warning: lines are a straight spike");
  12726. v_trans_x = v_prev_x;
  12727. v_trans_y = v_prev_y;
  12728. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12729. }
  12730. }
  12731. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12732. }
  12733. const contourMovements = [];
  12734. for ( let i = 0, il = contour.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. // console.log('i,j,k', i, j , k)
  12739. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12740. }
  12741. const holesMovements = [];
  12742. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12743. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12744. const ahole = holes[ h ];
  12745. oneHoleMovements = [];
  12746. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12747. if ( j === il ) j = 0;
  12748. if ( k === il ) k = 0;
  12749. // (j)---(i)---(k)
  12750. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12751. }
  12752. holesMovements.push( oneHoleMovements );
  12753. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12754. }
  12755. // Loop bevelSegments, 1 for the front, 1 for the back
  12756. for ( let b = 0; b < bevelSegments; b ++ ) {
  12757. //for ( b = bevelSegments; b > 0; b -- ) {
  12758. const t = b / bevelSegments;
  12759. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12760. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12761. // contract shape
  12762. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12763. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12764. v( vert.x, vert.y, - z );
  12765. }
  12766. // expand holes
  12767. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12768. const ahole = holes[ h ];
  12769. oneHoleMovements = holesMovements[ h ];
  12770. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12771. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12772. v( vert.x, vert.y, - z );
  12773. }
  12774. }
  12775. }
  12776. const bs = bevelSize + bevelOffset;
  12777. // Back facing vertices
  12778. for ( let i = 0; i < vlen; i ++ ) {
  12779. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12780. if ( ! extrudeByPath ) {
  12781. v( vert.x, vert.y, 0 );
  12782. } else {
  12783. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12784. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12785. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12786. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12787. v( position2.x, position2.y, position2.z );
  12788. }
  12789. }
  12790. // Add stepped vertices...
  12791. // Including front facing vertices
  12792. for ( let s = 1; s <= steps; s ++ ) {
  12793. for ( let i = 0; i < vlen; i ++ ) {
  12794. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12795. if ( ! extrudeByPath ) {
  12796. v( vert.x, vert.y, depth / steps * s );
  12797. } else {
  12798. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12799. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12800. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12801. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12802. v( position2.x, position2.y, position2.z );
  12803. }
  12804. }
  12805. }
  12806. // Add bevel segments planes
  12807. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12808. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12809. const t = b / bevelSegments;
  12810. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12811. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12812. // contract shape
  12813. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12814. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12815. v( vert.x, vert.y, depth + z );
  12816. }
  12817. // expand holes
  12818. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12819. const ahole = holes[ h ];
  12820. oneHoleMovements = holesMovements[ h ];
  12821. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12822. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12823. if ( ! extrudeByPath ) {
  12824. v( vert.x, vert.y, depth + z );
  12825. } else {
  12826. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12827. }
  12828. }
  12829. }
  12830. }
  12831. /* Faces */
  12832. // Top and bottom faces
  12833. buildLidFaces();
  12834. // Sides faces
  12835. buildSideFaces();
  12836. ///// Internal functions
  12837. function buildLidFaces() {
  12838. const start = verticesArray.length / 3;
  12839. if ( bevelEnabled ) {
  12840. let layer = 0; // steps + 1
  12841. let offset = vlen * layer;
  12842. // Bottom faces
  12843. for ( let i = 0; i < flen; i ++ ) {
  12844. const face = faces[ i ];
  12845. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12846. }
  12847. layer = steps + bevelSegments * 2;
  12848. offset = vlen * layer;
  12849. // Top faces
  12850. for ( let i = 0; i < flen; i ++ ) {
  12851. const face = faces[ i ];
  12852. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12853. }
  12854. } else {
  12855. // Bottom faces
  12856. for ( let i = 0; i < flen; i ++ ) {
  12857. const face = faces[ i ];
  12858. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12859. }
  12860. // Top faces
  12861. for ( let i = 0; i < flen; i ++ ) {
  12862. const face = faces[ i ];
  12863. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12864. }
  12865. }
  12866. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12867. }
  12868. // Create faces for the z-sides of the shape
  12869. function buildSideFaces() {
  12870. const start = verticesArray.length / 3;
  12871. let layeroffset = 0;
  12872. sidewalls( contour, layeroffset );
  12873. layeroffset += contour.length;
  12874. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12875. const ahole = holes[ h ];
  12876. sidewalls( ahole, layeroffset );
  12877. //, true
  12878. layeroffset += ahole.length;
  12879. }
  12880. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12881. }
  12882. function sidewalls( contour, layeroffset ) {
  12883. let i = contour.length;
  12884. while ( -- i >= 0 ) {
  12885. const j = i;
  12886. let k = i - 1;
  12887. if ( k < 0 ) k = contour.length - 1;
  12888. //console.log('b', i,j, i-1, k,vertices.length);
  12889. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12890. const slen1 = vlen * s;
  12891. const slen2 = vlen * ( s + 1 );
  12892. const a = layeroffset + j + slen1,
  12893. b = layeroffset + k + slen1,
  12894. c = layeroffset + k + slen2,
  12895. d = layeroffset + j + slen2;
  12896. f4( a, b, c, d );
  12897. }
  12898. }
  12899. }
  12900. function v( x, y, z ) {
  12901. placeholder.push( x );
  12902. placeholder.push( y );
  12903. placeholder.push( z );
  12904. }
  12905. function f3( a, b, c ) {
  12906. addVertex( a );
  12907. addVertex( b );
  12908. addVertex( c );
  12909. const nextIndex = verticesArray.length / 3;
  12910. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12911. addUV( uvs[ 0 ] );
  12912. addUV( uvs[ 1 ] );
  12913. addUV( uvs[ 2 ] );
  12914. }
  12915. function f4( a, b, c, d ) {
  12916. addVertex( a );
  12917. addVertex( b );
  12918. addVertex( d );
  12919. addVertex( b );
  12920. addVertex( c );
  12921. addVertex( d );
  12922. const nextIndex = verticesArray.length / 3;
  12923. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12924. addUV( uvs[ 0 ] );
  12925. addUV( uvs[ 1 ] );
  12926. addUV( uvs[ 3 ] );
  12927. addUV( uvs[ 1 ] );
  12928. addUV( uvs[ 2 ] );
  12929. addUV( uvs[ 3 ] );
  12930. }
  12931. function addVertex( index ) {
  12932. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12933. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12934. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12935. }
  12936. function addUV( vector2 ) {
  12937. uvArray.push( vector2.x );
  12938. uvArray.push( vector2.y );
  12939. }
  12940. }
  12941. }
  12942. copy( source ) {
  12943. super.copy( source );
  12944. this.parameters = Object.assign( {}, source.parameters );
  12945. return this;
  12946. }
  12947. toJSON() {
  12948. const data = super.toJSON();
  12949. const shapes = this.parameters.shapes;
  12950. const options = this.parameters.options;
  12951. return toJSON$1( shapes, options, data );
  12952. }
  12953. static fromJSON( data, shapes ) {
  12954. const geometryShapes = [];
  12955. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  12956. const shape = shapes[ data.shapes[ j ] ];
  12957. geometryShapes.push( shape );
  12958. }
  12959. const extrudePath = data.options.extrudePath;
  12960. if ( extrudePath !== undefined ) {
  12961. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  12962. }
  12963. return new ExtrudeGeometry( geometryShapes, data.options );
  12964. }
  12965. }
  12966. const WorldUVGenerator = {
  12967. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  12968. const a_x = vertices[ indexA * 3 ];
  12969. const a_y = vertices[ indexA * 3 + 1 ];
  12970. const b_x = vertices[ indexB * 3 ];
  12971. const b_y = vertices[ indexB * 3 + 1 ];
  12972. const c_x = vertices[ indexC * 3 ];
  12973. const c_y = vertices[ indexC * 3 + 1 ];
  12974. return [
  12975. new Vector2( a_x, a_y ),
  12976. new Vector2( b_x, b_y ),
  12977. new Vector2( c_x, c_y )
  12978. ];
  12979. },
  12980. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  12981. const a_x = vertices[ indexA * 3 ];
  12982. const a_y = vertices[ indexA * 3 + 1 ];
  12983. const a_z = vertices[ indexA * 3 + 2 ];
  12984. const b_x = vertices[ indexB * 3 ];
  12985. const b_y = vertices[ indexB * 3 + 1 ];
  12986. const b_z = vertices[ indexB * 3 + 2 ];
  12987. const c_x = vertices[ indexC * 3 ];
  12988. const c_y = vertices[ indexC * 3 + 1 ];
  12989. const c_z = vertices[ indexC * 3 + 2 ];
  12990. const d_x = vertices[ indexD * 3 ];
  12991. const d_y = vertices[ indexD * 3 + 1 ];
  12992. const d_z = vertices[ indexD * 3 + 2 ];
  12993. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  12994. return [
  12995. new Vector2( a_x, 1 - a_z ),
  12996. new Vector2( b_x, 1 - b_z ),
  12997. new Vector2( c_x, 1 - c_z ),
  12998. new Vector2( d_x, 1 - d_z )
  12999. ];
  13000. } else {
  13001. return [
  13002. new Vector2( a_y, 1 - a_z ),
  13003. new Vector2( b_y, 1 - b_z ),
  13004. new Vector2( c_y, 1 - c_z ),
  13005. new Vector2( d_y, 1 - d_z )
  13006. ];
  13007. }
  13008. }
  13009. };
  13010. function toJSON$1( shapes, options, data ) {
  13011. data.shapes = [];
  13012. if ( Array.isArray( shapes ) ) {
  13013. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13014. const shape = shapes[ i ];
  13015. data.shapes.push( shape.uuid );
  13016. }
  13017. } else {
  13018. data.shapes.push( shapes.uuid );
  13019. }
  13020. data.options = Object.assign( {}, options );
  13021. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13022. return data;
  13023. }
  13024. class IcosahedronGeometry extends PolyhedronGeometry {
  13025. constructor( radius = 1, detail = 0 ) {
  13026. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13027. const vertices = [
  13028. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13029. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13030. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13031. ];
  13032. const indices = [
  13033. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13034. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13035. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13036. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13037. ];
  13038. super( vertices, indices, radius, detail );
  13039. this.type = 'IcosahedronGeometry';
  13040. this.parameters = {
  13041. radius: radius,
  13042. detail: detail
  13043. };
  13044. }
  13045. static fromJSON( data ) {
  13046. return new IcosahedronGeometry( data.radius, data.detail );
  13047. }
  13048. }
  13049. class OctahedronGeometry extends PolyhedronGeometry {
  13050. constructor( radius = 1, detail = 0 ) {
  13051. const vertices = [
  13052. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13053. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13054. ];
  13055. const indices = [
  13056. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13057. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13058. 1, 3, 4, 1, 4, 2
  13059. ];
  13060. super( vertices, indices, radius, detail );
  13061. this.type = 'OctahedronGeometry';
  13062. this.parameters = {
  13063. radius: radius,
  13064. detail: detail
  13065. };
  13066. }
  13067. static fromJSON( data ) {
  13068. return new OctahedronGeometry( data.radius, data.detail );
  13069. }
  13070. }
  13071. class PlaneGeometry extends BufferGeometry {
  13072. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13073. super();
  13074. this.type = 'PlaneGeometry';
  13075. this.parameters = {
  13076. width: width,
  13077. height: height,
  13078. widthSegments: widthSegments,
  13079. heightSegments: heightSegments
  13080. };
  13081. const width_half = width / 2;
  13082. const height_half = height / 2;
  13083. const gridX = Math.floor( widthSegments );
  13084. const gridY = Math.floor( heightSegments );
  13085. const gridX1 = gridX + 1;
  13086. const gridY1 = gridY + 1;
  13087. const segment_width = width / gridX;
  13088. const segment_height = height / gridY;
  13089. //
  13090. const indices = [];
  13091. const vertices = [];
  13092. const normals = [];
  13093. const uvs = [];
  13094. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13095. const y = iy * segment_height - height_half;
  13096. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13097. const x = ix * segment_width - width_half;
  13098. vertices.push( x, - y, 0 );
  13099. normals.push( 0, 0, 1 );
  13100. uvs.push( ix / gridX );
  13101. uvs.push( 1 - ( iy / gridY ) );
  13102. }
  13103. }
  13104. for ( let iy = 0; iy < gridY; iy ++ ) {
  13105. for ( let ix = 0; ix < gridX; ix ++ ) {
  13106. const a = ix + gridX1 * iy;
  13107. const b = ix + gridX1 * ( iy + 1 );
  13108. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13109. const d = ( ix + 1 ) + gridX1 * iy;
  13110. indices.push( a, b, d );
  13111. indices.push( b, c, d );
  13112. }
  13113. }
  13114. this.setIndex( indices );
  13115. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13116. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13117. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13118. }
  13119. copy( source ) {
  13120. super.copy( source );
  13121. this.parameters = Object.assign( {}, source.parameters );
  13122. return this;
  13123. }
  13124. static fromJSON( data ) {
  13125. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13126. }
  13127. }
  13128. class RingGeometry extends BufferGeometry {
  13129. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13130. super();
  13131. this.type = 'RingGeometry';
  13132. this.parameters = {
  13133. innerRadius: innerRadius,
  13134. outerRadius: outerRadius,
  13135. thetaSegments: thetaSegments,
  13136. phiSegments: phiSegments,
  13137. thetaStart: thetaStart,
  13138. thetaLength: thetaLength
  13139. };
  13140. thetaSegments = Math.max( 3, thetaSegments );
  13141. phiSegments = Math.max( 1, phiSegments );
  13142. // buffers
  13143. const indices = [];
  13144. const vertices = [];
  13145. const normals = [];
  13146. const uvs = [];
  13147. // some helper variables
  13148. let radius = innerRadius;
  13149. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13150. const vertex = new Vector3();
  13151. const uv = new Vector2();
  13152. // generate vertices, normals and uvs
  13153. for ( let j = 0; j <= phiSegments; j ++ ) {
  13154. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13155. // values are generate from the inside of the ring to the outside
  13156. const segment = thetaStart + i / thetaSegments * thetaLength;
  13157. // vertex
  13158. vertex.x = radius * Math.cos( segment );
  13159. vertex.y = radius * Math.sin( segment );
  13160. vertices.push( vertex.x, vertex.y, vertex.z );
  13161. // normal
  13162. normals.push( 0, 0, 1 );
  13163. // uv
  13164. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13165. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13166. uvs.push( uv.x, uv.y );
  13167. }
  13168. // increase the radius for next row of vertices
  13169. radius += radiusStep;
  13170. }
  13171. // indices
  13172. for ( let j = 0; j < phiSegments; j ++ ) {
  13173. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13174. for ( let i = 0; i < thetaSegments; i ++ ) {
  13175. const segment = i + thetaSegmentLevel;
  13176. const a = segment;
  13177. const b = segment + thetaSegments + 1;
  13178. const c = segment + thetaSegments + 2;
  13179. const d = segment + 1;
  13180. // faces
  13181. indices.push( a, b, d );
  13182. indices.push( b, c, d );
  13183. }
  13184. }
  13185. // build geometry
  13186. this.setIndex( indices );
  13187. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13188. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13189. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13190. }
  13191. copy( source ) {
  13192. super.copy( source );
  13193. this.parameters = Object.assign( {}, source.parameters );
  13194. return this;
  13195. }
  13196. static fromJSON( data ) {
  13197. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13198. }
  13199. }
  13200. class ShapeGeometry extends BufferGeometry {
  13201. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13202. super();
  13203. this.type = 'ShapeGeometry';
  13204. this.parameters = {
  13205. shapes: shapes,
  13206. curveSegments: curveSegments
  13207. };
  13208. // buffers
  13209. const indices = [];
  13210. const vertices = [];
  13211. const normals = [];
  13212. const uvs = [];
  13213. // helper variables
  13214. let groupStart = 0;
  13215. let groupCount = 0;
  13216. // allow single and array values for "shapes" parameter
  13217. if ( Array.isArray( shapes ) === false ) {
  13218. addShape( shapes );
  13219. } else {
  13220. for ( let i = 0; i < shapes.length; i ++ ) {
  13221. addShape( shapes[ i ] );
  13222. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13223. groupStart += groupCount;
  13224. groupCount = 0;
  13225. }
  13226. }
  13227. // build geometry
  13228. this.setIndex( indices );
  13229. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13230. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13231. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13232. // helper functions
  13233. function addShape( shape ) {
  13234. const indexOffset = vertices.length / 3;
  13235. const points = shape.extractPoints( curveSegments );
  13236. let shapeVertices = points.shape;
  13237. const shapeHoles = points.holes;
  13238. // check direction of vertices
  13239. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13240. shapeVertices = shapeVertices.reverse();
  13241. }
  13242. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13243. const shapeHole = shapeHoles[ i ];
  13244. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13245. shapeHoles[ i ] = shapeHole.reverse();
  13246. }
  13247. }
  13248. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13249. // join vertices of inner and outer paths to a single array
  13250. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13251. const shapeHole = shapeHoles[ i ];
  13252. shapeVertices = shapeVertices.concat( shapeHole );
  13253. }
  13254. // vertices, normals, uvs
  13255. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13256. const vertex = shapeVertices[ i ];
  13257. vertices.push( vertex.x, vertex.y, 0 );
  13258. normals.push( 0, 0, 1 );
  13259. uvs.push( vertex.x, vertex.y ); // world uvs
  13260. }
  13261. // indices
  13262. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13263. const face = faces[ i ];
  13264. const a = face[ 0 ] + indexOffset;
  13265. const b = face[ 1 ] + indexOffset;
  13266. const c = face[ 2 ] + indexOffset;
  13267. indices.push( a, b, c );
  13268. groupCount += 3;
  13269. }
  13270. }
  13271. }
  13272. copy( source ) {
  13273. super.copy( source );
  13274. this.parameters = Object.assign( {}, source.parameters );
  13275. return this;
  13276. }
  13277. toJSON() {
  13278. const data = super.toJSON();
  13279. const shapes = this.parameters.shapes;
  13280. return toJSON( shapes, data );
  13281. }
  13282. static fromJSON( data, shapes ) {
  13283. const geometryShapes = [];
  13284. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13285. const shape = shapes[ data.shapes[ j ] ];
  13286. geometryShapes.push( shape );
  13287. }
  13288. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13289. }
  13290. }
  13291. function toJSON( shapes, data ) {
  13292. data.shapes = [];
  13293. if ( Array.isArray( shapes ) ) {
  13294. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13295. const shape = shapes[ i ];
  13296. data.shapes.push( shape.uuid );
  13297. }
  13298. } else {
  13299. data.shapes.push( shapes.uuid );
  13300. }
  13301. return data;
  13302. }
  13303. class SphereGeometry extends BufferGeometry {
  13304. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13305. super();
  13306. this.type = 'SphereGeometry';
  13307. this.parameters = {
  13308. radius: radius,
  13309. widthSegments: widthSegments,
  13310. heightSegments: heightSegments,
  13311. phiStart: phiStart,
  13312. phiLength: phiLength,
  13313. thetaStart: thetaStart,
  13314. thetaLength: thetaLength
  13315. };
  13316. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13317. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13318. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13319. let index = 0;
  13320. const grid = [];
  13321. const vertex = new Vector3();
  13322. const normal = new Vector3();
  13323. // buffers
  13324. const indices = [];
  13325. const vertices = [];
  13326. const normals = [];
  13327. const uvs = [];
  13328. // generate vertices, normals and uvs
  13329. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13330. const verticesRow = [];
  13331. const v = iy / heightSegments;
  13332. // special case for the poles
  13333. let uOffset = 0;
  13334. if ( iy === 0 && thetaStart === 0 ) {
  13335. uOffset = 0.5 / widthSegments;
  13336. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13337. uOffset = - 0.5 / widthSegments;
  13338. }
  13339. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13340. const u = ix / widthSegments;
  13341. // vertex
  13342. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13343. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13344. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13345. vertices.push( vertex.x, vertex.y, vertex.z );
  13346. // normal
  13347. normal.copy( vertex ).normalize();
  13348. normals.push( normal.x, normal.y, normal.z );
  13349. // uv
  13350. uvs.push( u + uOffset, 1 - v );
  13351. verticesRow.push( index ++ );
  13352. }
  13353. grid.push( verticesRow );
  13354. }
  13355. // indices
  13356. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13357. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13358. const a = grid[ iy ][ ix + 1 ];
  13359. const b = grid[ iy ][ ix ];
  13360. const c = grid[ iy + 1 ][ ix ];
  13361. const d = grid[ iy + 1 ][ ix + 1 ];
  13362. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13363. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13364. }
  13365. }
  13366. // build geometry
  13367. this.setIndex( indices );
  13368. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13369. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13370. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13371. }
  13372. copy( source ) {
  13373. super.copy( source );
  13374. this.parameters = Object.assign( {}, source.parameters );
  13375. return this;
  13376. }
  13377. static fromJSON( data ) {
  13378. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13379. }
  13380. }
  13381. class TetrahedronGeometry extends PolyhedronGeometry {
  13382. constructor( radius = 1, detail = 0 ) {
  13383. const vertices = [
  13384. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13385. ];
  13386. const indices = [
  13387. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13388. ];
  13389. super( vertices, indices, radius, detail );
  13390. this.type = 'TetrahedronGeometry';
  13391. this.parameters = {
  13392. radius: radius,
  13393. detail: detail
  13394. };
  13395. }
  13396. static fromJSON( data ) {
  13397. return new TetrahedronGeometry( data.radius, data.detail );
  13398. }
  13399. }
  13400. class TorusGeometry extends BufferGeometry {
  13401. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13402. super();
  13403. this.type = 'TorusGeometry';
  13404. this.parameters = {
  13405. radius: radius,
  13406. tube: tube,
  13407. radialSegments: radialSegments,
  13408. tubularSegments: tubularSegments,
  13409. arc: arc
  13410. };
  13411. radialSegments = Math.floor( radialSegments );
  13412. tubularSegments = Math.floor( tubularSegments );
  13413. // buffers
  13414. const indices = [];
  13415. const vertices = [];
  13416. const normals = [];
  13417. const uvs = [];
  13418. // helper variables
  13419. const center = new Vector3();
  13420. const vertex = new Vector3();
  13421. const normal = new Vector3();
  13422. // generate vertices, normals and uvs
  13423. for ( let j = 0; j <= radialSegments; j ++ ) {
  13424. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13425. const u = i / tubularSegments * arc;
  13426. const v = j / radialSegments * Math.PI * 2;
  13427. // vertex
  13428. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13429. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13430. vertex.z = tube * Math.sin( v );
  13431. vertices.push( vertex.x, vertex.y, vertex.z );
  13432. // normal
  13433. center.x = radius * Math.cos( u );
  13434. center.y = radius * Math.sin( u );
  13435. normal.subVectors( vertex, center ).normalize();
  13436. normals.push( normal.x, normal.y, normal.z );
  13437. // uv
  13438. uvs.push( i / tubularSegments );
  13439. uvs.push( j / radialSegments );
  13440. }
  13441. }
  13442. // generate indices
  13443. for ( let j = 1; j <= radialSegments; j ++ ) {
  13444. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13445. // indices
  13446. const a = ( tubularSegments + 1 ) * j + i - 1;
  13447. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13448. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13449. const d = ( tubularSegments + 1 ) * j + i;
  13450. // faces
  13451. indices.push( a, b, d );
  13452. indices.push( b, c, d );
  13453. }
  13454. }
  13455. // build geometry
  13456. this.setIndex( indices );
  13457. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13458. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13459. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13460. }
  13461. copy( source ) {
  13462. super.copy( source );
  13463. this.parameters = Object.assign( {}, source.parameters );
  13464. return this;
  13465. }
  13466. static fromJSON( data ) {
  13467. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13468. }
  13469. }
  13470. class TorusKnotGeometry extends BufferGeometry {
  13471. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13472. super();
  13473. this.type = 'TorusKnotGeometry';
  13474. this.parameters = {
  13475. radius: radius,
  13476. tube: tube,
  13477. tubularSegments: tubularSegments,
  13478. radialSegments: radialSegments,
  13479. p: p,
  13480. q: q
  13481. };
  13482. tubularSegments = Math.floor( tubularSegments );
  13483. radialSegments = Math.floor( radialSegments );
  13484. // buffers
  13485. const indices = [];
  13486. const vertices = [];
  13487. const normals = [];
  13488. const uvs = [];
  13489. // helper variables
  13490. const vertex = new Vector3();
  13491. const normal = new Vector3();
  13492. const P1 = new Vector3();
  13493. const P2 = new Vector3();
  13494. const B = new Vector3();
  13495. const T = new Vector3();
  13496. const N = new Vector3();
  13497. // generate vertices, normals and uvs
  13498. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13499. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13500. const u = i / tubularSegments * p * Math.PI * 2;
  13501. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13502. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13503. calculatePositionOnCurve( u, p, q, radius, P1 );
  13504. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13505. // calculate orthonormal basis
  13506. T.subVectors( P2, P1 );
  13507. N.addVectors( P2, P1 );
  13508. B.crossVectors( T, N );
  13509. N.crossVectors( B, T );
  13510. // normalize B, N. T can be ignored, we don't use it
  13511. B.normalize();
  13512. N.normalize();
  13513. for ( let j = 0; j <= radialSegments; ++ j ) {
  13514. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13515. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13516. const v = j / radialSegments * Math.PI * 2;
  13517. const cx = - tube * Math.cos( v );
  13518. const cy = tube * Math.sin( v );
  13519. // now calculate the final vertex position.
  13520. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13521. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13522. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13523. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13524. vertices.push( vertex.x, vertex.y, vertex.z );
  13525. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13526. normal.subVectors( vertex, P1 ).normalize();
  13527. normals.push( normal.x, normal.y, normal.z );
  13528. // uv
  13529. uvs.push( i / tubularSegments );
  13530. uvs.push( j / radialSegments );
  13531. }
  13532. }
  13533. // generate indices
  13534. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13535. for ( let i = 1; i <= radialSegments; i ++ ) {
  13536. // indices
  13537. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13538. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13539. const c = ( radialSegments + 1 ) * j + i;
  13540. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13541. // faces
  13542. indices.push( a, b, d );
  13543. indices.push( b, c, d );
  13544. }
  13545. }
  13546. // build geometry
  13547. this.setIndex( indices );
  13548. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13549. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13550. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13551. // this function calculates the current position on the torus curve
  13552. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13553. const cu = Math.cos( u );
  13554. const su = Math.sin( u );
  13555. const quOverP = q / p * u;
  13556. const cs = Math.cos( quOverP );
  13557. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13558. position.y = radius * ( 2 + cs ) * su * 0.5;
  13559. position.z = radius * Math.sin( quOverP ) * 0.5;
  13560. }
  13561. }
  13562. copy( source ) {
  13563. super.copy( source );
  13564. this.parameters = Object.assign( {}, source.parameters );
  13565. return this;
  13566. }
  13567. static fromJSON( data ) {
  13568. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13569. }
  13570. }
  13571. class TubeGeometry extends BufferGeometry {
  13572. 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 ) {
  13573. super();
  13574. this.type = 'TubeGeometry';
  13575. this.parameters = {
  13576. path: path,
  13577. tubularSegments: tubularSegments,
  13578. radius: radius,
  13579. radialSegments: radialSegments,
  13580. closed: closed
  13581. };
  13582. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13583. // expose internals
  13584. this.tangents = frames.tangents;
  13585. this.normals = frames.normals;
  13586. this.binormals = frames.binormals;
  13587. // helper variables
  13588. const vertex = new Vector3();
  13589. const normal = new Vector3();
  13590. const uv = new Vector2();
  13591. let P = new Vector3();
  13592. // buffer
  13593. const vertices = [];
  13594. const normals = [];
  13595. const uvs = [];
  13596. const indices = [];
  13597. // create buffer data
  13598. generateBufferData();
  13599. // build geometry
  13600. this.setIndex( indices );
  13601. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13602. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13603. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13604. // functions
  13605. function generateBufferData() {
  13606. for ( let i = 0; i < tubularSegments; i ++ ) {
  13607. generateSegment( i );
  13608. }
  13609. // if the geometry is not closed, generate the last row of vertices and normals
  13610. // at the regular position on the given path
  13611. //
  13612. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13613. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13614. // uvs are generated in a separate function.
  13615. // this makes it easy compute correct values for closed geometries
  13616. generateUVs();
  13617. // finally create faces
  13618. generateIndices();
  13619. }
  13620. function generateSegment( i ) {
  13621. // we use getPointAt to sample evenly distributed points from the given path
  13622. P = path.getPointAt( i / tubularSegments, P );
  13623. // retrieve corresponding normal and binormal
  13624. const N = frames.normals[ i ];
  13625. const B = frames.binormals[ i ];
  13626. // generate normals and vertices for the current segment
  13627. for ( let j = 0; j <= radialSegments; j ++ ) {
  13628. const v = j / radialSegments * Math.PI * 2;
  13629. const sin = Math.sin( v );
  13630. const cos = - Math.cos( v );
  13631. // normal
  13632. normal.x = ( cos * N.x + sin * B.x );
  13633. normal.y = ( cos * N.y + sin * B.y );
  13634. normal.z = ( cos * N.z + sin * B.z );
  13635. normal.normalize();
  13636. normals.push( normal.x, normal.y, normal.z );
  13637. // vertex
  13638. vertex.x = P.x + radius * normal.x;
  13639. vertex.y = P.y + radius * normal.y;
  13640. vertex.z = P.z + radius * normal.z;
  13641. vertices.push( vertex.x, vertex.y, vertex.z );
  13642. }
  13643. }
  13644. function generateIndices() {
  13645. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13646. for ( let i = 1; i <= radialSegments; i ++ ) {
  13647. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13648. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13649. const c = ( radialSegments + 1 ) * j + i;
  13650. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13651. // faces
  13652. indices.push( a, b, d );
  13653. indices.push( b, c, d );
  13654. }
  13655. }
  13656. }
  13657. function generateUVs() {
  13658. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13659. for ( let j = 0; j <= radialSegments; j ++ ) {
  13660. uv.x = i / tubularSegments;
  13661. uv.y = j / radialSegments;
  13662. uvs.push( uv.x, uv.y );
  13663. }
  13664. }
  13665. }
  13666. }
  13667. copy( source ) {
  13668. super.copy( source );
  13669. this.parameters = Object.assign( {}, source.parameters );
  13670. return this;
  13671. }
  13672. toJSON() {
  13673. const data = super.toJSON();
  13674. data.path = this.parameters.path.toJSON();
  13675. return data;
  13676. }
  13677. static fromJSON( data ) {
  13678. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13679. // User defined curves or instances of CurvePath will not be deserialized.
  13680. return new TubeGeometry(
  13681. new Curves[ data.path.type ]().fromJSON( data.path ),
  13682. data.tubularSegments,
  13683. data.radius,
  13684. data.radialSegments,
  13685. data.closed
  13686. );
  13687. }
  13688. }
  13689. class WireframeGeometry extends BufferGeometry {
  13690. constructor( geometry = null ) {
  13691. super();
  13692. this.type = 'WireframeGeometry';
  13693. this.parameters = {
  13694. geometry: geometry
  13695. };
  13696. if ( geometry !== null ) {
  13697. // buffer
  13698. const vertices = [];
  13699. const edges = new Set();
  13700. // helper variables
  13701. const start = new Vector3();
  13702. const end = new Vector3();
  13703. if ( geometry.index !== null ) {
  13704. // indexed BufferGeometry
  13705. const position = geometry.attributes.position;
  13706. const indices = geometry.index;
  13707. let groups = geometry.groups;
  13708. if ( groups.length === 0 ) {
  13709. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13710. }
  13711. // create a data structure that contains all edges without duplicates
  13712. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13713. const group = groups[ o ];
  13714. const groupStart = group.start;
  13715. const groupCount = group.count;
  13716. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13717. for ( let j = 0; j < 3; j ++ ) {
  13718. const index1 = indices.getX( i + j );
  13719. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13720. start.fromBufferAttribute( position, index1 );
  13721. end.fromBufferAttribute( position, index2 );
  13722. if ( isUniqueEdge( start, end, edges ) === true ) {
  13723. vertices.push( start.x, start.y, start.z );
  13724. vertices.push( end.x, end.y, end.z );
  13725. }
  13726. }
  13727. }
  13728. }
  13729. } else {
  13730. // non-indexed BufferGeometry
  13731. const position = geometry.attributes.position;
  13732. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13733. for ( let j = 0; j < 3; j ++ ) {
  13734. // three edges per triangle, an edge is represented as (index1, index2)
  13735. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13736. const index1 = 3 * i + j;
  13737. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13738. start.fromBufferAttribute( position, index1 );
  13739. end.fromBufferAttribute( position, index2 );
  13740. if ( isUniqueEdge( start, end, edges ) === true ) {
  13741. vertices.push( start.x, start.y, start.z );
  13742. vertices.push( end.x, end.y, end.z );
  13743. }
  13744. }
  13745. }
  13746. }
  13747. // build geometry
  13748. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13749. }
  13750. }
  13751. copy( source ) {
  13752. super.copy( source );
  13753. this.parameters = Object.assign( {}, source.parameters );
  13754. return this;
  13755. }
  13756. }
  13757. function isUniqueEdge( start, end, edges ) {
  13758. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13759. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13760. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13761. return false;
  13762. } else {
  13763. edges.add( hash1 );
  13764. edges.add( hash2 );
  13765. return true;
  13766. }
  13767. }
  13768. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13769. __proto__: null,
  13770. BoxGeometry: BoxGeometry,
  13771. CapsuleGeometry: CapsuleGeometry,
  13772. CircleGeometry: CircleGeometry,
  13773. ConeGeometry: ConeGeometry,
  13774. CylinderGeometry: CylinderGeometry,
  13775. DodecahedronGeometry: DodecahedronGeometry,
  13776. EdgesGeometry: EdgesGeometry,
  13777. ExtrudeGeometry: ExtrudeGeometry,
  13778. IcosahedronGeometry: IcosahedronGeometry,
  13779. LatheGeometry: LatheGeometry,
  13780. OctahedronGeometry: OctahedronGeometry,
  13781. PlaneGeometry: PlaneGeometry,
  13782. PolyhedronGeometry: PolyhedronGeometry,
  13783. RingGeometry: RingGeometry,
  13784. ShapeGeometry: ShapeGeometry,
  13785. SphereGeometry: SphereGeometry,
  13786. TetrahedronGeometry: TetrahedronGeometry,
  13787. TorusGeometry: TorusGeometry,
  13788. TorusKnotGeometry: TorusKnotGeometry,
  13789. TubeGeometry: TubeGeometry,
  13790. WireframeGeometry: WireframeGeometry
  13791. });
  13792. class ShadowMaterial extends Material {
  13793. constructor( parameters ) {
  13794. super();
  13795. this.isShadowMaterial = true;
  13796. this.type = 'ShadowMaterial';
  13797. this.color = new Color( 0x000000 );
  13798. this.transparent = true;
  13799. this.fog = true;
  13800. this.setValues( parameters );
  13801. }
  13802. copy( source ) {
  13803. super.copy( source );
  13804. this.color.copy( source.color );
  13805. this.fog = source.fog;
  13806. return this;
  13807. }
  13808. }
  13809. class RawShaderMaterial extends ShaderMaterial {
  13810. constructor( parameters ) {
  13811. super( parameters );
  13812. this.isRawShaderMaterial = true;
  13813. this.type = 'RawShaderMaterial';
  13814. }
  13815. }
  13816. class MeshStandardMaterial extends Material {
  13817. constructor( parameters ) {
  13818. super();
  13819. this.isMeshStandardMaterial = true;
  13820. this.defines = { 'STANDARD': '' };
  13821. this.type = 'MeshStandardMaterial';
  13822. this.color = new Color( 0xffffff ); // diffuse
  13823. this.roughness = 1.0;
  13824. this.metalness = 0.0;
  13825. this.map = null;
  13826. this.lightMap = null;
  13827. this.lightMapIntensity = 1.0;
  13828. this.aoMap = null;
  13829. this.aoMapIntensity = 1.0;
  13830. this.emissive = new Color( 0x000000 );
  13831. this.emissiveIntensity = 1.0;
  13832. this.emissiveMap = null;
  13833. this.bumpMap = null;
  13834. this.bumpScale = 1;
  13835. this.normalMap = null;
  13836. this.normalMapType = TangentSpaceNormalMap;
  13837. this.normalScale = new Vector2( 1, 1 );
  13838. this.displacementMap = null;
  13839. this.displacementScale = 1;
  13840. this.displacementBias = 0;
  13841. this.roughnessMap = null;
  13842. this.metalnessMap = null;
  13843. this.alphaMap = null;
  13844. this.envMap = null;
  13845. this.envMapRotation = new Euler();
  13846. this.envMapIntensity = 1.0;
  13847. this.wireframe = false;
  13848. this.wireframeLinewidth = 1;
  13849. this.wireframeLinecap = 'round';
  13850. this.wireframeLinejoin = 'round';
  13851. this.flatShading = false;
  13852. this.fog = true;
  13853. this.setValues( parameters );
  13854. }
  13855. copy( source ) {
  13856. super.copy( source );
  13857. this.defines = { 'STANDARD': '' };
  13858. this.color.copy( source.color );
  13859. this.roughness = source.roughness;
  13860. this.metalness = source.metalness;
  13861. this.map = source.map;
  13862. this.lightMap = source.lightMap;
  13863. this.lightMapIntensity = source.lightMapIntensity;
  13864. this.aoMap = source.aoMap;
  13865. this.aoMapIntensity = source.aoMapIntensity;
  13866. this.emissive.copy( source.emissive );
  13867. this.emissiveMap = source.emissiveMap;
  13868. this.emissiveIntensity = source.emissiveIntensity;
  13869. this.bumpMap = source.bumpMap;
  13870. this.bumpScale = source.bumpScale;
  13871. this.normalMap = source.normalMap;
  13872. this.normalMapType = source.normalMapType;
  13873. this.normalScale.copy( source.normalScale );
  13874. this.displacementMap = source.displacementMap;
  13875. this.displacementScale = source.displacementScale;
  13876. this.displacementBias = source.displacementBias;
  13877. this.roughnessMap = source.roughnessMap;
  13878. this.metalnessMap = source.metalnessMap;
  13879. this.alphaMap = source.alphaMap;
  13880. this.envMap = source.envMap;
  13881. this.envMapRotation.copy( source.envMapRotation );
  13882. this.envMapIntensity = source.envMapIntensity;
  13883. this.wireframe = source.wireframe;
  13884. this.wireframeLinewidth = source.wireframeLinewidth;
  13885. this.wireframeLinecap = source.wireframeLinecap;
  13886. this.wireframeLinejoin = source.wireframeLinejoin;
  13887. this.flatShading = source.flatShading;
  13888. this.fog = source.fog;
  13889. return this;
  13890. }
  13891. }
  13892. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13893. constructor( parameters ) {
  13894. super();
  13895. this.isMeshPhysicalMaterial = true;
  13896. this.defines = {
  13897. 'STANDARD': '',
  13898. 'PHYSICAL': ''
  13899. };
  13900. this.type = 'MeshPhysicalMaterial';
  13901. this.anisotropyRotation = 0;
  13902. this.anisotropyMap = null;
  13903. this.clearcoatMap = null;
  13904. this.clearcoatRoughness = 0.0;
  13905. this.clearcoatRoughnessMap = null;
  13906. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13907. this.clearcoatNormalMap = null;
  13908. this.ior = 1.5;
  13909. Object.defineProperty( this, 'reflectivity', {
  13910. get: function () {
  13911. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13912. },
  13913. set: function ( reflectivity ) {
  13914. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13915. }
  13916. } );
  13917. this.iridescenceMap = null;
  13918. this.iridescenceIOR = 1.3;
  13919. this.iridescenceThicknessRange = [ 100, 400 ];
  13920. this.iridescenceThicknessMap = null;
  13921. this.sheenColor = new Color( 0x000000 );
  13922. this.sheenColorMap = null;
  13923. this.sheenRoughness = 1.0;
  13924. this.sheenRoughnessMap = null;
  13925. this.transmissionMap = null;
  13926. this.thickness = 0;
  13927. this.thicknessMap = null;
  13928. this.attenuationDistance = Infinity;
  13929. this.attenuationColor = new Color( 1, 1, 1 );
  13930. this.specularIntensity = 1.0;
  13931. this.specularIntensityMap = null;
  13932. this.specularColor = new Color( 1, 1, 1 );
  13933. this.specularColorMap = null;
  13934. this._anisotropy = 0;
  13935. this._clearcoat = 0;
  13936. this._dispersion = 0;
  13937. this._iridescence = 0;
  13938. this._sheen = 0.0;
  13939. this._transmission = 0;
  13940. this.setValues( parameters );
  13941. }
  13942. get anisotropy() {
  13943. return this._anisotropy;
  13944. }
  13945. set anisotropy( value ) {
  13946. if ( this._anisotropy > 0 !== value > 0 ) {
  13947. this.version ++;
  13948. }
  13949. this._anisotropy = value;
  13950. }
  13951. get clearcoat() {
  13952. return this._clearcoat;
  13953. }
  13954. set clearcoat( value ) {
  13955. if ( this._clearcoat > 0 !== value > 0 ) {
  13956. this.version ++;
  13957. }
  13958. this._clearcoat = value;
  13959. }
  13960. get iridescence() {
  13961. return this._iridescence;
  13962. }
  13963. set iridescence( value ) {
  13964. if ( this._iridescence > 0 !== value > 0 ) {
  13965. this.version ++;
  13966. }
  13967. this._iridescence = value;
  13968. }
  13969. get dispersion() {
  13970. return this._dispersion;
  13971. }
  13972. set dispersion( value ) {
  13973. if ( this._dispersion > 0 !== value > 0 ) {
  13974. this.version ++;
  13975. }
  13976. this._dispersion = value;
  13977. }
  13978. get sheen() {
  13979. return this._sheen;
  13980. }
  13981. set sheen( value ) {
  13982. if ( this._sheen > 0 !== value > 0 ) {
  13983. this.version ++;
  13984. }
  13985. this._sheen = value;
  13986. }
  13987. get transmission() {
  13988. return this._transmission;
  13989. }
  13990. set transmission( value ) {
  13991. if ( this._transmission > 0 !== value > 0 ) {
  13992. this.version ++;
  13993. }
  13994. this._transmission = value;
  13995. }
  13996. copy( source ) {
  13997. super.copy( source );
  13998. this.defines = {
  13999. 'STANDARD': '',
  14000. 'PHYSICAL': ''
  14001. };
  14002. this.anisotropy = source.anisotropy;
  14003. this.anisotropyRotation = source.anisotropyRotation;
  14004. this.anisotropyMap = source.anisotropyMap;
  14005. this.clearcoat = source.clearcoat;
  14006. this.clearcoatMap = source.clearcoatMap;
  14007. this.clearcoatRoughness = source.clearcoatRoughness;
  14008. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14009. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14010. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14011. this.dispersion = source.dispersion;
  14012. this.ior = source.ior;
  14013. this.iridescence = source.iridescence;
  14014. this.iridescenceMap = source.iridescenceMap;
  14015. this.iridescenceIOR = source.iridescenceIOR;
  14016. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14017. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14018. this.sheen = source.sheen;
  14019. this.sheenColor.copy( source.sheenColor );
  14020. this.sheenColorMap = source.sheenColorMap;
  14021. this.sheenRoughness = source.sheenRoughness;
  14022. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14023. this.transmission = source.transmission;
  14024. this.transmissionMap = source.transmissionMap;
  14025. this.thickness = source.thickness;
  14026. this.thicknessMap = source.thicknessMap;
  14027. this.attenuationDistance = source.attenuationDistance;
  14028. this.attenuationColor.copy( source.attenuationColor );
  14029. this.specularIntensity = source.specularIntensity;
  14030. this.specularIntensityMap = source.specularIntensityMap;
  14031. this.specularColor.copy( source.specularColor );
  14032. this.specularColorMap = source.specularColorMap;
  14033. return this;
  14034. }
  14035. }
  14036. class MeshPhongMaterial extends Material {
  14037. constructor( parameters ) {
  14038. super();
  14039. this.isMeshPhongMaterial = true;
  14040. this.type = 'MeshPhongMaterial';
  14041. this.color = new Color( 0xffffff ); // diffuse
  14042. this.specular = new Color( 0x111111 );
  14043. this.shininess = 30;
  14044. this.map = null;
  14045. this.lightMap = null;
  14046. this.lightMapIntensity = 1.0;
  14047. this.aoMap = null;
  14048. this.aoMapIntensity = 1.0;
  14049. this.emissive = new Color( 0x000000 );
  14050. this.emissiveIntensity = 1.0;
  14051. this.emissiveMap = null;
  14052. this.bumpMap = null;
  14053. this.bumpScale = 1;
  14054. this.normalMap = null;
  14055. this.normalMapType = TangentSpaceNormalMap;
  14056. this.normalScale = new Vector2( 1, 1 );
  14057. this.displacementMap = null;
  14058. this.displacementScale = 1;
  14059. this.displacementBias = 0;
  14060. this.specularMap = null;
  14061. this.alphaMap = null;
  14062. this.envMap = null;
  14063. this.envMapRotation = new Euler();
  14064. this.combine = MultiplyOperation;
  14065. this.reflectivity = 1;
  14066. this.refractionRatio = 0.98;
  14067. this.wireframe = false;
  14068. this.wireframeLinewidth = 1;
  14069. this.wireframeLinecap = 'round';
  14070. this.wireframeLinejoin = 'round';
  14071. this.flatShading = false;
  14072. this.fog = true;
  14073. this.setValues( parameters );
  14074. }
  14075. copy( source ) {
  14076. super.copy( source );
  14077. this.color.copy( source.color );
  14078. this.specular.copy( source.specular );
  14079. this.shininess = source.shininess;
  14080. this.map = source.map;
  14081. this.lightMap = source.lightMap;
  14082. this.lightMapIntensity = source.lightMapIntensity;
  14083. this.aoMap = source.aoMap;
  14084. this.aoMapIntensity = source.aoMapIntensity;
  14085. this.emissive.copy( source.emissive );
  14086. this.emissiveMap = source.emissiveMap;
  14087. this.emissiveIntensity = source.emissiveIntensity;
  14088. this.bumpMap = source.bumpMap;
  14089. this.bumpScale = source.bumpScale;
  14090. this.normalMap = source.normalMap;
  14091. this.normalMapType = source.normalMapType;
  14092. this.normalScale.copy( source.normalScale );
  14093. this.displacementMap = source.displacementMap;
  14094. this.displacementScale = source.displacementScale;
  14095. this.displacementBias = source.displacementBias;
  14096. this.specularMap = source.specularMap;
  14097. this.alphaMap = source.alphaMap;
  14098. this.envMap = source.envMap;
  14099. this.envMapRotation.copy( source.envMapRotation );
  14100. this.combine = source.combine;
  14101. this.reflectivity = source.reflectivity;
  14102. this.refractionRatio = source.refractionRatio;
  14103. this.wireframe = source.wireframe;
  14104. this.wireframeLinewidth = source.wireframeLinewidth;
  14105. this.wireframeLinecap = source.wireframeLinecap;
  14106. this.wireframeLinejoin = source.wireframeLinejoin;
  14107. this.flatShading = source.flatShading;
  14108. this.fog = source.fog;
  14109. return this;
  14110. }
  14111. }
  14112. class MeshToonMaterial extends Material {
  14113. constructor( parameters ) {
  14114. super();
  14115. this.isMeshToonMaterial = true;
  14116. this.defines = { 'TOON': '' };
  14117. this.type = 'MeshToonMaterial';
  14118. this.color = new Color( 0xffffff );
  14119. this.map = null;
  14120. this.gradientMap = null;
  14121. this.lightMap = null;
  14122. this.lightMapIntensity = 1.0;
  14123. this.aoMap = null;
  14124. this.aoMapIntensity = 1.0;
  14125. this.emissive = new Color( 0x000000 );
  14126. this.emissiveIntensity = 1.0;
  14127. this.emissiveMap = null;
  14128. this.bumpMap = null;
  14129. this.bumpScale = 1;
  14130. this.normalMap = null;
  14131. this.normalMapType = TangentSpaceNormalMap;
  14132. this.normalScale = new Vector2( 1, 1 );
  14133. this.displacementMap = null;
  14134. this.displacementScale = 1;
  14135. this.displacementBias = 0;
  14136. this.alphaMap = null;
  14137. this.wireframe = false;
  14138. this.wireframeLinewidth = 1;
  14139. this.wireframeLinecap = 'round';
  14140. this.wireframeLinejoin = 'round';
  14141. this.fog = true;
  14142. this.setValues( parameters );
  14143. }
  14144. copy( source ) {
  14145. super.copy( source );
  14146. this.color.copy( source.color );
  14147. this.map = source.map;
  14148. this.gradientMap = source.gradientMap;
  14149. this.lightMap = source.lightMap;
  14150. this.lightMapIntensity = source.lightMapIntensity;
  14151. this.aoMap = source.aoMap;
  14152. this.aoMapIntensity = source.aoMapIntensity;
  14153. this.emissive.copy( source.emissive );
  14154. this.emissiveMap = source.emissiveMap;
  14155. this.emissiveIntensity = source.emissiveIntensity;
  14156. this.bumpMap = source.bumpMap;
  14157. this.bumpScale = source.bumpScale;
  14158. this.normalMap = source.normalMap;
  14159. this.normalMapType = source.normalMapType;
  14160. this.normalScale.copy( source.normalScale );
  14161. this.displacementMap = source.displacementMap;
  14162. this.displacementScale = source.displacementScale;
  14163. this.displacementBias = source.displacementBias;
  14164. this.alphaMap = source.alphaMap;
  14165. this.wireframe = source.wireframe;
  14166. this.wireframeLinewidth = source.wireframeLinewidth;
  14167. this.wireframeLinecap = source.wireframeLinecap;
  14168. this.wireframeLinejoin = source.wireframeLinejoin;
  14169. this.fog = source.fog;
  14170. return this;
  14171. }
  14172. }
  14173. class MeshNormalMaterial extends Material {
  14174. constructor( parameters ) {
  14175. super();
  14176. this.isMeshNormalMaterial = true;
  14177. this.type = 'MeshNormalMaterial';
  14178. this.bumpMap = null;
  14179. this.bumpScale = 1;
  14180. this.normalMap = null;
  14181. this.normalMapType = TangentSpaceNormalMap;
  14182. this.normalScale = new Vector2( 1, 1 );
  14183. this.displacementMap = null;
  14184. this.displacementScale = 1;
  14185. this.displacementBias = 0;
  14186. this.wireframe = false;
  14187. this.wireframeLinewidth = 1;
  14188. this.flatShading = false;
  14189. this.setValues( parameters );
  14190. }
  14191. copy( source ) {
  14192. super.copy( source );
  14193. this.bumpMap = source.bumpMap;
  14194. this.bumpScale = source.bumpScale;
  14195. this.normalMap = source.normalMap;
  14196. this.normalMapType = source.normalMapType;
  14197. this.normalScale.copy( source.normalScale );
  14198. this.displacementMap = source.displacementMap;
  14199. this.displacementScale = source.displacementScale;
  14200. this.displacementBias = source.displacementBias;
  14201. this.wireframe = source.wireframe;
  14202. this.wireframeLinewidth = source.wireframeLinewidth;
  14203. this.flatShading = source.flatShading;
  14204. return this;
  14205. }
  14206. }
  14207. class MeshLambertMaterial extends Material {
  14208. constructor( parameters ) {
  14209. super();
  14210. this.isMeshLambertMaterial = true;
  14211. this.type = 'MeshLambertMaterial';
  14212. this.color = new Color( 0xffffff ); // diffuse
  14213. this.map = null;
  14214. this.lightMap = null;
  14215. this.lightMapIntensity = 1.0;
  14216. this.aoMap = null;
  14217. this.aoMapIntensity = 1.0;
  14218. this.emissive = new Color( 0x000000 );
  14219. this.emissiveIntensity = 1.0;
  14220. this.emissiveMap = null;
  14221. this.bumpMap = null;
  14222. this.bumpScale = 1;
  14223. this.normalMap = null;
  14224. this.normalMapType = TangentSpaceNormalMap;
  14225. this.normalScale = new Vector2( 1, 1 );
  14226. this.displacementMap = null;
  14227. this.displacementScale = 1;
  14228. this.displacementBias = 0;
  14229. this.specularMap = null;
  14230. this.alphaMap = null;
  14231. this.envMap = null;
  14232. this.envMapRotation = new Euler();
  14233. this.combine = MultiplyOperation;
  14234. this.reflectivity = 1;
  14235. this.refractionRatio = 0.98;
  14236. this.wireframe = false;
  14237. this.wireframeLinewidth = 1;
  14238. this.wireframeLinecap = 'round';
  14239. this.wireframeLinejoin = 'round';
  14240. this.flatShading = false;
  14241. this.fog = true;
  14242. this.setValues( parameters );
  14243. }
  14244. copy( source ) {
  14245. super.copy( source );
  14246. this.color.copy( source.color );
  14247. this.map = source.map;
  14248. this.lightMap = source.lightMap;
  14249. this.lightMapIntensity = source.lightMapIntensity;
  14250. this.aoMap = source.aoMap;
  14251. this.aoMapIntensity = source.aoMapIntensity;
  14252. this.emissive.copy( source.emissive );
  14253. this.emissiveMap = source.emissiveMap;
  14254. this.emissiveIntensity = source.emissiveIntensity;
  14255. this.bumpMap = source.bumpMap;
  14256. this.bumpScale = source.bumpScale;
  14257. this.normalMap = source.normalMap;
  14258. this.normalMapType = source.normalMapType;
  14259. this.normalScale.copy( source.normalScale );
  14260. this.displacementMap = source.displacementMap;
  14261. this.displacementScale = source.displacementScale;
  14262. this.displacementBias = source.displacementBias;
  14263. this.specularMap = source.specularMap;
  14264. this.alphaMap = source.alphaMap;
  14265. this.envMap = source.envMap;
  14266. this.envMapRotation.copy( source.envMapRotation );
  14267. this.combine = source.combine;
  14268. this.reflectivity = source.reflectivity;
  14269. this.refractionRatio = source.refractionRatio;
  14270. this.wireframe = source.wireframe;
  14271. this.wireframeLinewidth = source.wireframeLinewidth;
  14272. this.wireframeLinecap = source.wireframeLinecap;
  14273. this.wireframeLinejoin = source.wireframeLinejoin;
  14274. this.flatShading = source.flatShading;
  14275. this.fog = source.fog;
  14276. return this;
  14277. }
  14278. }
  14279. class MeshDepthMaterial extends Material {
  14280. constructor( parameters ) {
  14281. super();
  14282. this.isMeshDepthMaterial = true;
  14283. this.type = 'MeshDepthMaterial';
  14284. this.depthPacking = BasicDepthPacking;
  14285. this.map = null;
  14286. this.alphaMap = null;
  14287. this.displacementMap = null;
  14288. this.displacementScale = 1;
  14289. this.displacementBias = 0;
  14290. this.wireframe = false;
  14291. this.wireframeLinewidth = 1;
  14292. this.setValues( parameters );
  14293. }
  14294. copy( source ) {
  14295. super.copy( source );
  14296. this.depthPacking = source.depthPacking;
  14297. this.map = source.map;
  14298. this.alphaMap = source.alphaMap;
  14299. this.displacementMap = source.displacementMap;
  14300. this.displacementScale = source.displacementScale;
  14301. this.displacementBias = source.displacementBias;
  14302. this.wireframe = source.wireframe;
  14303. this.wireframeLinewidth = source.wireframeLinewidth;
  14304. return this;
  14305. }
  14306. }
  14307. class MeshDistanceMaterial extends Material {
  14308. constructor( parameters ) {
  14309. super();
  14310. this.isMeshDistanceMaterial = true;
  14311. this.type = 'MeshDistanceMaterial';
  14312. this.map = null;
  14313. this.alphaMap = null;
  14314. this.displacementMap = null;
  14315. this.displacementScale = 1;
  14316. this.displacementBias = 0;
  14317. this.setValues( parameters );
  14318. }
  14319. copy( source ) {
  14320. super.copy( source );
  14321. this.map = source.map;
  14322. this.alphaMap = source.alphaMap;
  14323. this.displacementMap = source.displacementMap;
  14324. this.displacementScale = source.displacementScale;
  14325. this.displacementBias = source.displacementBias;
  14326. return this;
  14327. }
  14328. }
  14329. class MeshMatcapMaterial extends Material {
  14330. constructor( parameters ) {
  14331. super();
  14332. this.isMeshMatcapMaterial = true;
  14333. this.defines = { 'MATCAP': '' };
  14334. this.type = 'MeshMatcapMaterial';
  14335. this.color = new Color( 0xffffff ); // diffuse
  14336. this.matcap = null;
  14337. this.map = null;
  14338. this.bumpMap = null;
  14339. this.bumpScale = 1;
  14340. this.normalMap = null;
  14341. this.normalMapType = TangentSpaceNormalMap;
  14342. this.normalScale = new Vector2( 1, 1 );
  14343. this.displacementMap = null;
  14344. this.displacementScale = 1;
  14345. this.displacementBias = 0;
  14346. this.alphaMap = null;
  14347. this.flatShading = false;
  14348. this.fog = true;
  14349. this.setValues( parameters );
  14350. }
  14351. copy( source ) {
  14352. super.copy( source );
  14353. this.defines = { 'MATCAP': '' };
  14354. this.color.copy( source.color );
  14355. this.matcap = source.matcap;
  14356. this.map = source.map;
  14357. this.bumpMap = source.bumpMap;
  14358. this.bumpScale = source.bumpScale;
  14359. this.normalMap = source.normalMap;
  14360. this.normalMapType = source.normalMapType;
  14361. this.normalScale.copy( source.normalScale );
  14362. this.displacementMap = source.displacementMap;
  14363. this.displacementScale = source.displacementScale;
  14364. this.displacementBias = source.displacementBias;
  14365. this.alphaMap = source.alphaMap;
  14366. this.flatShading = source.flatShading;
  14367. this.fog = source.fog;
  14368. return this;
  14369. }
  14370. }
  14371. class LineDashedMaterial extends LineBasicMaterial {
  14372. constructor( parameters ) {
  14373. super();
  14374. this.isLineDashedMaterial = true;
  14375. this.type = 'LineDashedMaterial';
  14376. this.scale = 1;
  14377. this.dashSize = 3;
  14378. this.gapSize = 1;
  14379. this.setValues( parameters );
  14380. }
  14381. copy( source ) {
  14382. super.copy( source );
  14383. this.scale = source.scale;
  14384. this.dashSize = source.dashSize;
  14385. this.gapSize = source.gapSize;
  14386. return this;
  14387. }
  14388. }
  14389. // converts an array to a specific type
  14390. function convertArray( array, type, forceClone ) {
  14391. if ( ! array || // let 'undefined' and 'null' pass
  14392. ! forceClone && array.constructor === type ) return array;
  14393. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14394. return new type( array ); // create typed array
  14395. }
  14396. return Array.prototype.slice.call( array ); // create Array
  14397. }
  14398. function isTypedArray( object ) {
  14399. return ArrayBuffer.isView( object ) &&
  14400. ! ( object instanceof DataView );
  14401. }
  14402. // returns an array by which times and values can be sorted
  14403. function getKeyframeOrder( times ) {
  14404. function compareTime( i, j ) {
  14405. return times[ i ] - times[ j ];
  14406. }
  14407. const n = times.length;
  14408. const result = new Array( n );
  14409. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14410. result.sort( compareTime );
  14411. return result;
  14412. }
  14413. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14414. function sortedArray( values, stride, order ) {
  14415. const nValues = values.length;
  14416. const result = new values.constructor( nValues );
  14417. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14418. const srcOffset = order[ i ] * stride;
  14419. for ( let j = 0; j !== stride; ++ j ) {
  14420. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14421. }
  14422. }
  14423. return result;
  14424. }
  14425. // function for parsing AOS keyframe formats
  14426. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14427. let i = 1, key = jsonKeys[ 0 ];
  14428. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14429. key = jsonKeys[ i ++ ];
  14430. }
  14431. if ( key === undefined ) return; // no data
  14432. let value = key[ valuePropertyName ];
  14433. if ( value === undefined ) return; // no data
  14434. if ( Array.isArray( value ) ) {
  14435. do {
  14436. value = key[ valuePropertyName ];
  14437. if ( value !== undefined ) {
  14438. times.push( key.time );
  14439. values.push.apply( values, value ); // push all elements
  14440. }
  14441. key = jsonKeys[ i ++ ];
  14442. } while ( key !== undefined );
  14443. } else if ( value.toArray !== undefined ) {
  14444. // ...assume THREE.Math-ish
  14445. do {
  14446. value = key[ valuePropertyName ];
  14447. if ( value !== undefined ) {
  14448. times.push( key.time );
  14449. value.toArray( values, values.length );
  14450. }
  14451. key = jsonKeys[ i ++ ];
  14452. } while ( key !== undefined );
  14453. } else {
  14454. // otherwise push as-is
  14455. do {
  14456. value = key[ valuePropertyName ];
  14457. if ( value !== undefined ) {
  14458. times.push( key.time );
  14459. values.push( value );
  14460. }
  14461. key = jsonKeys[ i ++ ];
  14462. } while ( key !== undefined );
  14463. }
  14464. }
  14465. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14466. const clip = sourceClip.clone();
  14467. clip.name = name;
  14468. const tracks = [];
  14469. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14470. const track = clip.tracks[ i ];
  14471. const valueSize = track.getValueSize();
  14472. const times = [];
  14473. const values = [];
  14474. for ( let j = 0; j < track.times.length; ++ j ) {
  14475. const frame = track.times[ j ] * fps;
  14476. if ( frame < startFrame || frame >= endFrame ) continue;
  14477. times.push( track.times[ j ] );
  14478. for ( let k = 0; k < valueSize; ++ k ) {
  14479. values.push( track.values[ j * valueSize + k ] );
  14480. }
  14481. }
  14482. if ( times.length === 0 ) continue;
  14483. track.times = convertArray( times, track.times.constructor );
  14484. track.values = convertArray( values, track.values.constructor );
  14485. tracks.push( track );
  14486. }
  14487. clip.tracks = tracks;
  14488. // find minimum .times value across all tracks in the trimmed clip
  14489. let minStartTime = Infinity;
  14490. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14491. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14492. minStartTime = clip.tracks[ i ].times[ 0 ];
  14493. }
  14494. }
  14495. // shift all tracks such that clip begins at t=0
  14496. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14497. clip.tracks[ i ].shift( - 1 * minStartTime );
  14498. }
  14499. clip.resetDuration();
  14500. return clip;
  14501. }
  14502. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14503. if ( fps <= 0 ) fps = 30;
  14504. const numTracks = referenceClip.tracks.length;
  14505. const referenceTime = referenceFrame / fps;
  14506. // Make each track's values relative to the values at the reference frame
  14507. for ( let i = 0; i < numTracks; ++ i ) {
  14508. const referenceTrack = referenceClip.tracks[ i ];
  14509. const referenceTrackType = referenceTrack.ValueTypeName;
  14510. // Skip this track if it's non-numeric
  14511. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14512. // Find the track in the target clip whose name and type matches the reference track
  14513. const targetTrack = targetClip.tracks.find( function ( track ) {
  14514. return track.name === referenceTrack.name
  14515. && track.ValueTypeName === referenceTrackType;
  14516. } );
  14517. if ( targetTrack === undefined ) continue;
  14518. let referenceOffset = 0;
  14519. const referenceValueSize = referenceTrack.getValueSize();
  14520. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14521. referenceOffset = referenceValueSize / 3;
  14522. }
  14523. let targetOffset = 0;
  14524. const targetValueSize = targetTrack.getValueSize();
  14525. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14526. targetOffset = targetValueSize / 3;
  14527. }
  14528. const lastIndex = referenceTrack.times.length - 1;
  14529. let referenceValue;
  14530. // Find the value to subtract out of the track
  14531. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14532. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14533. const startIndex = referenceOffset;
  14534. const endIndex = referenceValueSize - referenceOffset;
  14535. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14536. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14537. // Reference frame is after the last keyframe, so just use the last keyframe
  14538. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14539. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14540. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14541. } else {
  14542. // Interpolate to the reference value
  14543. const interpolant = referenceTrack.createInterpolant();
  14544. const startIndex = referenceOffset;
  14545. const endIndex = referenceValueSize - referenceOffset;
  14546. interpolant.evaluate( referenceTime );
  14547. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14548. }
  14549. // Conjugate the quaternion
  14550. if ( referenceTrackType === 'quaternion' ) {
  14551. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14552. referenceQuat.toArray( referenceValue );
  14553. }
  14554. // Subtract the reference value from all of the track values
  14555. const numTimes = targetTrack.times.length;
  14556. for ( let j = 0; j < numTimes; ++ j ) {
  14557. const valueStart = j * targetValueSize + targetOffset;
  14558. if ( referenceTrackType === 'quaternion' ) {
  14559. // Multiply the conjugate for quaternion track types
  14560. Quaternion.multiplyQuaternionsFlat(
  14561. targetTrack.values,
  14562. valueStart,
  14563. referenceValue,
  14564. 0,
  14565. targetTrack.values,
  14566. valueStart
  14567. );
  14568. } else {
  14569. const valueEnd = targetValueSize - targetOffset * 2;
  14570. // Subtract each value for all other numeric track types
  14571. for ( let k = 0; k < valueEnd; ++ k ) {
  14572. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14573. }
  14574. }
  14575. }
  14576. }
  14577. targetClip.blendMode = AdditiveAnimationBlendMode;
  14578. return targetClip;
  14579. }
  14580. const AnimationUtils = {
  14581. convertArray: convertArray,
  14582. isTypedArray: isTypedArray,
  14583. getKeyframeOrder: getKeyframeOrder,
  14584. sortedArray: sortedArray,
  14585. flattenJSON: flattenJSON,
  14586. subclip: subclip,
  14587. makeClipAdditive: makeClipAdditive
  14588. };
  14589. /**
  14590. * Abstract base class of interpolants over parametric samples.
  14591. *
  14592. * The parameter domain is one dimensional, typically the time or a path
  14593. * along a curve defined by the data.
  14594. *
  14595. * The sample values can have any dimensionality and derived classes may
  14596. * apply special interpretations to the data.
  14597. *
  14598. * This class provides the interval seek in a Template Method, deferring
  14599. * the actual interpolation to derived classes.
  14600. *
  14601. * Time complexity is O(1) for linear access crossing at most two points
  14602. * and O(log N) for random access, where N is the number of positions.
  14603. *
  14604. * References:
  14605. *
  14606. * http://www.oodesign.com/template-method-pattern.html
  14607. *
  14608. */
  14609. class Interpolant {
  14610. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14611. this.parameterPositions = parameterPositions;
  14612. this._cachedIndex = 0;
  14613. this.resultBuffer = resultBuffer !== undefined ?
  14614. resultBuffer : new sampleValues.constructor( sampleSize );
  14615. this.sampleValues = sampleValues;
  14616. this.valueSize = sampleSize;
  14617. this.settings = null;
  14618. this.DefaultSettings_ = {};
  14619. }
  14620. evaluate( t ) {
  14621. const pp = this.parameterPositions;
  14622. let i1 = this._cachedIndex,
  14623. t1 = pp[ i1 ],
  14624. t0 = pp[ i1 - 1 ];
  14625. validate_interval: {
  14626. seek: {
  14627. let right;
  14628. linear_scan: {
  14629. //- See http://jsperf.com/comparison-to-undefined/3
  14630. //- slower code:
  14631. //-
  14632. //- if ( t >= t1 || t1 === undefined ) {
  14633. forward_scan: if ( ! ( t < t1 ) ) {
  14634. for ( let giveUpAt = i1 + 2; ; ) {
  14635. if ( t1 === undefined ) {
  14636. if ( t < t0 ) break forward_scan;
  14637. // after end
  14638. i1 = pp.length;
  14639. this._cachedIndex = i1;
  14640. return this.copySampleValue_( i1 - 1 );
  14641. }
  14642. if ( i1 === giveUpAt ) break; // this loop
  14643. t0 = t1;
  14644. t1 = pp[ ++ i1 ];
  14645. if ( t < t1 ) {
  14646. // we have arrived at the sought interval
  14647. break seek;
  14648. }
  14649. }
  14650. // prepare binary search on the right side of the index
  14651. right = pp.length;
  14652. break linear_scan;
  14653. }
  14654. //- slower code:
  14655. //- if ( t < t0 || t0 === undefined ) {
  14656. if ( ! ( t >= t0 ) ) {
  14657. // looping?
  14658. const t1global = pp[ 1 ];
  14659. if ( t < t1global ) {
  14660. i1 = 2; // + 1, using the scan for the details
  14661. t0 = t1global;
  14662. }
  14663. // linear reverse scan
  14664. for ( let giveUpAt = i1 - 2; ; ) {
  14665. if ( t0 === undefined ) {
  14666. // before start
  14667. this._cachedIndex = 0;
  14668. return this.copySampleValue_( 0 );
  14669. }
  14670. if ( i1 === giveUpAt ) break; // this loop
  14671. t1 = t0;
  14672. t0 = pp[ -- i1 - 1 ];
  14673. if ( t >= t0 ) {
  14674. // we have arrived at the sought interval
  14675. break seek;
  14676. }
  14677. }
  14678. // prepare binary search on the left side of the index
  14679. right = i1;
  14680. i1 = 0;
  14681. break linear_scan;
  14682. }
  14683. // the interval is valid
  14684. break validate_interval;
  14685. } // linear scan
  14686. // binary search
  14687. while ( i1 < right ) {
  14688. const mid = ( i1 + right ) >>> 1;
  14689. if ( t < pp[ mid ] ) {
  14690. right = mid;
  14691. } else {
  14692. i1 = mid + 1;
  14693. }
  14694. }
  14695. t1 = pp[ i1 ];
  14696. t0 = pp[ i1 - 1 ];
  14697. // check boundary cases, again
  14698. if ( t0 === undefined ) {
  14699. this._cachedIndex = 0;
  14700. return this.copySampleValue_( 0 );
  14701. }
  14702. if ( t1 === undefined ) {
  14703. i1 = pp.length;
  14704. this._cachedIndex = i1;
  14705. return this.copySampleValue_( i1 - 1 );
  14706. }
  14707. } // seek
  14708. this._cachedIndex = i1;
  14709. this.intervalChanged_( i1, t0, t1 );
  14710. } // validate_interval
  14711. return this.interpolate_( i1, t0, t, t1 );
  14712. }
  14713. getSettings_() {
  14714. return this.settings || this.DefaultSettings_;
  14715. }
  14716. copySampleValue_( index ) {
  14717. // copies a sample value to the result buffer
  14718. const result = this.resultBuffer,
  14719. values = this.sampleValues,
  14720. stride = this.valueSize,
  14721. offset = index * stride;
  14722. for ( let i = 0; i !== stride; ++ i ) {
  14723. result[ i ] = values[ offset + i ];
  14724. }
  14725. return result;
  14726. }
  14727. // Template methods for derived classes:
  14728. interpolate_( /* i1, t0, t, t1 */ ) {
  14729. throw new Error( 'call to abstract method' );
  14730. // implementations shall return this.resultBuffer
  14731. }
  14732. intervalChanged_( /* i1, t0, t1 */ ) {
  14733. // empty
  14734. }
  14735. }
  14736. /**
  14737. * Fast and simple cubic spline interpolant.
  14738. *
  14739. * It was derived from a Hermitian construction setting the first derivative
  14740. * at each sample position to the linear slope between neighboring positions
  14741. * over their parameter interval.
  14742. */
  14743. class CubicInterpolant extends Interpolant {
  14744. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14745. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14746. this._weightPrev = - 0;
  14747. this._offsetPrev = - 0;
  14748. this._weightNext = - 0;
  14749. this._offsetNext = - 0;
  14750. this.DefaultSettings_ = {
  14751. endingStart: ZeroCurvatureEnding,
  14752. endingEnd: ZeroCurvatureEnding
  14753. };
  14754. }
  14755. intervalChanged_( i1, t0, t1 ) {
  14756. const pp = this.parameterPositions;
  14757. let iPrev = i1 - 2,
  14758. iNext = i1 + 1,
  14759. tPrev = pp[ iPrev ],
  14760. tNext = pp[ iNext ];
  14761. if ( tPrev === undefined ) {
  14762. switch ( this.getSettings_().endingStart ) {
  14763. case ZeroSlopeEnding:
  14764. // f'(t0) = 0
  14765. iPrev = i1;
  14766. tPrev = 2 * t0 - t1;
  14767. break;
  14768. case WrapAroundEnding:
  14769. // use the other end of the curve
  14770. iPrev = pp.length - 2;
  14771. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14772. break;
  14773. default: // ZeroCurvatureEnding
  14774. // f''(t0) = 0 a.k.a. Natural Spline
  14775. iPrev = i1;
  14776. tPrev = t1;
  14777. }
  14778. }
  14779. if ( tNext === undefined ) {
  14780. switch ( this.getSettings_().endingEnd ) {
  14781. case ZeroSlopeEnding:
  14782. // f'(tN) = 0
  14783. iNext = i1;
  14784. tNext = 2 * t1 - t0;
  14785. break;
  14786. case WrapAroundEnding:
  14787. // use the other end of the curve
  14788. iNext = 1;
  14789. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14790. break;
  14791. default: // ZeroCurvatureEnding
  14792. // f''(tN) = 0, a.k.a. Natural Spline
  14793. iNext = i1 - 1;
  14794. tNext = t0;
  14795. }
  14796. }
  14797. const halfDt = ( t1 - t0 ) * 0.5,
  14798. stride = this.valueSize;
  14799. this._weightPrev = halfDt / ( t0 - tPrev );
  14800. this._weightNext = halfDt / ( tNext - t1 );
  14801. this._offsetPrev = iPrev * stride;
  14802. this._offsetNext = iNext * stride;
  14803. }
  14804. interpolate_( i1, t0, t, t1 ) {
  14805. const result = this.resultBuffer,
  14806. values = this.sampleValues,
  14807. stride = this.valueSize,
  14808. o1 = i1 * stride, o0 = o1 - stride,
  14809. oP = this._offsetPrev, oN = this._offsetNext,
  14810. wP = this._weightPrev, wN = this._weightNext,
  14811. p = ( t - t0 ) / ( t1 - t0 ),
  14812. pp = p * p,
  14813. ppp = pp * p;
  14814. // evaluate polynomials
  14815. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14816. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14817. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14818. const sN = wN * ppp - wN * pp;
  14819. // combine data linearly
  14820. for ( let i = 0; i !== stride; ++ i ) {
  14821. result[ i ] =
  14822. sP * values[ oP + i ] +
  14823. s0 * values[ o0 + i ] +
  14824. s1 * values[ o1 + i ] +
  14825. sN * values[ oN + i ];
  14826. }
  14827. return result;
  14828. }
  14829. }
  14830. class LinearInterpolant extends Interpolant {
  14831. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14832. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14833. }
  14834. interpolate_( i1, t0, t, t1 ) {
  14835. const result = this.resultBuffer,
  14836. values = this.sampleValues,
  14837. stride = this.valueSize,
  14838. offset1 = i1 * stride,
  14839. offset0 = offset1 - stride,
  14840. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14841. weight0 = 1 - weight1;
  14842. for ( let i = 0; i !== stride; ++ i ) {
  14843. result[ i ] =
  14844. values[ offset0 + i ] * weight0 +
  14845. values[ offset1 + i ] * weight1;
  14846. }
  14847. return result;
  14848. }
  14849. }
  14850. /**
  14851. *
  14852. * Interpolant that evaluates to the sample value at the position preceding
  14853. * the parameter.
  14854. */
  14855. class DiscreteInterpolant extends Interpolant {
  14856. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14857. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14858. }
  14859. interpolate_( i1 /*, t0, t, t1 */ ) {
  14860. return this.copySampleValue_( i1 - 1 );
  14861. }
  14862. }
  14863. class KeyframeTrack {
  14864. constructor( name, times, values, interpolation ) {
  14865. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14866. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14867. this.name = name;
  14868. this.times = convertArray( times, this.TimeBufferType );
  14869. this.values = convertArray( values, this.ValueBufferType );
  14870. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14871. }
  14872. // Serialization (in static context, because of constructor invocation
  14873. // and automatic invocation of .toJSON):
  14874. static toJSON( track ) {
  14875. const trackType = track.constructor;
  14876. let json;
  14877. // derived classes can define a static toJSON method
  14878. if ( trackType.toJSON !== this.toJSON ) {
  14879. json = trackType.toJSON( track );
  14880. } else {
  14881. // by default, we assume the data can be serialized as-is
  14882. json = {
  14883. 'name': track.name,
  14884. 'times': convertArray( track.times, Array ),
  14885. 'values': convertArray( track.values, Array )
  14886. };
  14887. const interpolation = track.getInterpolation();
  14888. if ( interpolation !== track.DefaultInterpolation ) {
  14889. json.interpolation = interpolation;
  14890. }
  14891. }
  14892. json.type = track.ValueTypeName; // mandatory
  14893. return json;
  14894. }
  14895. InterpolantFactoryMethodDiscrete( result ) {
  14896. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14897. }
  14898. InterpolantFactoryMethodLinear( result ) {
  14899. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14900. }
  14901. InterpolantFactoryMethodSmooth( result ) {
  14902. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14903. }
  14904. setInterpolation( interpolation ) {
  14905. let factoryMethod;
  14906. switch ( interpolation ) {
  14907. case InterpolateDiscrete:
  14908. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14909. break;
  14910. case InterpolateLinear:
  14911. factoryMethod = this.InterpolantFactoryMethodLinear;
  14912. break;
  14913. case InterpolateSmooth:
  14914. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14915. break;
  14916. }
  14917. if ( factoryMethod === undefined ) {
  14918. const message = 'unsupported interpolation for ' +
  14919. this.ValueTypeName + ' keyframe track named ' + this.name;
  14920. if ( this.createInterpolant === undefined ) {
  14921. // fall back to default, unless the default itself is messed up
  14922. if ( interpolation !== this.DefaultInterpolation ) {
  14923. this.setInterpolation( this.DefaultInterpolation );
  14924. } else {
  14925. throw new Error( message ); // fatal, in this case
  14926. }
  14927. }
  14928. console.warn( 'THREE.KeyframeTrack:', message );
  14929. return this;
  14930. }
  14931. this.createInterpolant = factoryMethod;
  14932. return this;
  14933. }
  14934. getInterpolation() {
  14935. switch ( this.createInterpolant ) {
  14936. case this.InterpolantFactoryMethodDiscrete:
  14937. return InterpolateDiscrete;
  14938. case this.InterpolantFactoryMethodLinear:
  14939. return InterpolateLinear;
  14940. case this.InterpolantFactoryMethodSmooth:
  14941. return InterpolateSmooth;
  14942. }
  14943. }
  14944. getValueSize() {
  14945. return this.values.length / this.times.length;
  14946. }
  14947. // move all keyframes either forwards or backwards in time
  14948. shift( timeOffset ) {
  14949. if ( timeOffset !== 0.0 ) {
  14950. const times = this.times;
  14951. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14952. times[ i ] += timeOffset;
  14953. }
  14954. }
  14955. return this;
  14956. }
  14957. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  14958. scale( timeScale ) {
  14959. if ( timeScale !== 1.0 ) {
  14960. const times = this.times;
  14961. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14962. times[ i ] *= timeScale;
  14963. }
  14964. }
  14965. return this;
  14966. }
  14967. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  14968. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  14969. trim( startTime, endTime ) {
  14970. const times = this.times,
  14971. nKeys = times.length;
  14972. let from = 0,
  14973. to = nKeys - 1;
  14974. while ( from !== nKeys && times[ from ] < startTime ) {
  14975. ++ from;
  14976. }
  14977. while ( to !== - 1 && times[ to ] > endTime ) {
  14978. -- to;
  14979. }
  14980. ++ to; // inclusive -> exclusive bound
  14981. if ( from !== 0 || to !== nKeys ) {
  14982. // empty tracks are forbidden, so keep at least one keyframe
  14983. if ( from >= to ) {
  14984. to = Math.max( to, 1 );
  14985. from = to - 1;
  14986. }
  14987. const stride = this.getValueSize();
  14988. this.times = times.slice( from, to );
  14989. this.values = this.values.slice( from * stride, to * stride );
  14990. }
  14991. return this;
  14992. }
  14993. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  14994. validate() {
  14995. let valid = true;
  14996. const valueSize = this.getValueSize();
  14997. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  14998. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  14999. valid = false;
  15000. }
  15001. const times = this.times,
  15002. values = this.values,
  15003. nKeys = times.length;
  15004. if ( nKeys === 0 ) {
  15005. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15006. valid = false;
  15007. }
  15008. let prevTime = null;
  15009. for ( let i = 0; i !== nKeys; i ++ ) {
  15010. const currTime = times[ i ];
  15011. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15012. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15013. valid = false;
  15014. break;
  15015. }
  15016. if ( prevTime !== null && prevTime > currTime ) {
  15017. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15018. valid = false;
  15019. break;
  15020. }
  15021. prevTime = currTime;
  15022. }
  15023. if ( values !== undefined ) {
  15024. if ( isTypedArray( values ) ) {
  15025. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15026. const value = values[ i ];
  15027. if ( isNaN( value ) ) {
  15028. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15029. valid = false;
  15030. break;
  15031. }
  15032. }
  15033. }
  15034. }
  15035. return valid;
  15036. }
  15037. // removes equivalent sequential keys as common in morph target sequences
  15038. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15039. optimize() {
  15040. // times or values may be shared with other tracks, so overwriting is unsafe
  15041. const times = this.times.slice(),
  15042. values = this.values.slice(),
  15043. stride = this.getValueSize(),
  15044. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15045. lastIndex = times.length - 1;
  15046. let writeIndex = 1;
  15047. for ( let i = 1; i < lastIndex; ++ i ) {
  15048. let keep = false;
  15049. const time = times[ i ];
  15050. const timeNext = times[ i + 1 ];
  15051. // remove adjacent keyframes scheduled at the same time
  15052. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15053. if ( ! smoothInterpolation ) {
  15054. // remove unnecessary keyframes same as their neighbors
  15055. const offset = i * stride,
  15056. offsetP = offset - stride,
  15057. offsetN = offset + stride;
  15058. for ( let j = 0; j !== stride; ++ j ) {
  15059. const value = values[ offset + j ];
  15060. if ( value !== values[ offsetP + j ] ||
  15061. value !== values[ offsetN + j ] ) {
  15062. keep = true;
  15063. break;
  15064. }
  15065. }
  15066. } else {
  15067. keep = true;
  15068. }
  15069. }
  15070. // in-place compaction
  15071. if ( keep ) {
  15072. if ( i !== writeIndex ) {
  15073. times[ writeIndex ] = times[ i ];
  15074. const readOffset = i * stride,
  15075. writeOffset = writeIndex * stride;
  15076. for ( let j = 0; j !== stride; ++ j ) {
  15077. values[ writeOffset + j ] = values[ readOffset + j ];
  15078. }
  15079. }
  15080. ++ writeIndex;
  15081. }
  15082. }
  15083. // flush last keyframe (compaction looks ahead)
  15084. if ( lastIndex > 0 ) {
  15085. times[ writeIndex ] = times[ lastIndex ];
  15086. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15087. values[ writeOffset + j ] = values[ readOffset + j ];
  15088. }
  15089. ++ writeIndex;
  15090. }
  15091. if ( writeIndex !== times.length ) {
  15092. this.times = times.slice( 0, writeIndex );
  15093. this.values = values.slice( 0, writeIndex * stride );
  15094. } else {
  15095. this.times = times;
  15096. this.values = values;
  15097. }
  15098. return this;
  15099. }
  15100. clone() {
  15101. const times = this.times.slice();
  15102. const values = this.values.slice();
  15103. const TypedKeyframeTrack = this.constructor;
  15104. const track = new TypedKeyframeTrack( this.name, times, values );
  15105. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15106. track.createInterpolant = this.createInterpolant;
  15107. return track;
  15108. }
  15109. }
  15110. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15111. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15112. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15113. /**
  15114. * A Track of Boolean keyframe values.
  15115. */
  15116. class BooleanKeyframeTrack extends KeyframeTrack {
  15117. // No interpolation parameter because only InterpolateDiscrete is valid.
  15118. constructor( name, times, values ) {
  15119. super( name, times, values );
  15120. }
  15121. }
  15122. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15123. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15124. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15125. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15126. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15127. /**
  15128. * A Track of keyframe values that represent color.
  15129. */
  15130. class ColorKeyframeTrack extends KeyframeTrack {}
  15131. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15132. /**
  15133. * A Track of numeric keyframe values.
  15134. */
  15135. class NumberKeyframeTrack extends KeyframeTrack {}
  15136. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15137. /**
  15138. * Spherical linear unit quaternion interpolant.
  15139. */
  15140. class QuaternionLinearInterpolant extends Interpolant {
  15141. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15142. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15143. }
  15144. interpolate_( i1, t0, t, t1 ) {
  15145. const result = this.resultBuffer,
  15146. values = this.sampleValues,
  15147. stride = this.valueSize,
  15148. alpha = ( t - t0 ) / ( t1 - t0 );
  15149. let offset = i1 * stride;
  15150. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15151. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15152. }
  15153. return result;
  15154. }
  15155. }
  15156. /**
  15157. * A Track of quaternion keyframe values.
  15158. */
  15159. class QuaternionKeyframeTrack extends KeyframeTrack {
  15160. InterpolantFactoryMethodLinear( result ) {
  15161. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15162. }
  15163. }
  15164. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15165. // ValueBufferType is inherited
  15166. // DefaultInterpolation is inherited;
  15167. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15168. /**
  15169. * A Track that interpolates Strings
  15170. */
  15171. class StringKeyframeTrack extends KeyframeTrack {
  15172. // No interpolation parameter because only InterpolateDiscrete is valid.
  15173. constructor( name, times, values ) {
  15174. super( name, times, values );
  15175. }
  15176. }
  15177. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15178. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15179. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15180. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15181. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15182. /**
  15183. * A Track of vectored keyframe values.
  15184. */
  15185. class VectorKeyframeTrack extends KeyframeTrack {}
  15186. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15187. class AnimationClip {
  15188. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15189. this.name = name;
  15190. this.tracks = tracks;
  15191. this.duration = duration;
  15192. this.blendMode = blendMode;
  15193. this.uuid = generateUUID();
  15194. // this means it should figure out its duration by scanning the tracks
  15195. if ( this.duration < 0 ) {
  15196. this.resetDuration();
  15197. }
  15198. }
  15199. static parse( json ) {
  15200. const tracks = [],
  15201. jsonTracks = json.tracks,
  15202. frameTime = 1.0 / ( json.fps || 1.0 );
  15203. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15204. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15205. }
  15206. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15207. clip.uuid = json.uuid;
  15208. return clip;
  15209. }
  15210. static toJSON( clip ) {
  15211. const tracks = [],
  15212. clipTracks = clip.tracks;
  15213. const json = {
  15214. 'name': clip.name,
  15215. 'duration': clip.duration,
  15216. 'tracks': tracks,
  15217. 'uuid': clip.uuid,
  15218. 'blendMode': clip.blendMode
  15219. };
  15220. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15221. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15222. }
  15223. return json;
  15224. }
  15225. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15226. const numMorphTargets = morphTargetSequence.length;
  15227. const tracks = [];
  15228. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15229. let times = [];
  15230. let values = [];
  15231. times.push(
  15232. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15233. i,
  15234. ( i + 1 ) % numMorphTargets );
  15235. values.push( 0, 1, 0 );
  15236. const order = getKeyframeOrder( times );
  15237. times = sortedArray( times, 1, order );
  15238. values = sortedArray( values, 1, order );
  15239. // if there is a key at the first frame, duplicate it as the
  15240. // last frame as well for perfect loop.
  15241. if ( ! noLoop && times[ 0 ] === 0 ) {
  15242. times.push( numMorphTargets );
  15243. values.push( values[ 0 ] );
  15244. }
  15245. tracks.push(
  15246. new NumberKeyframeTrack(
  15247. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15248. times, values
  15249. ).scale( 1.0 / fps ) );
  15250. }
  15251. return new this( name, - 1, tracks );
  15252. }
  15253. static findByName( objectOrClipArray, name ) {
  15254. let clipArray = objectOrClipArray;
  15255. if ( ! Array.isArray( objectOrClipArray ) ) {
  15256. const o = objectOrClipArray;
  15257. clipArray = o.geometry && o.geometry.animations || o.animations;
  15258. }
  15259. for ( let i = 0; i < clipArray.length; i ++ ) {
  15260. if ( clipArray[ i ].name === name ) {
  15261. return clipArray[ i ];
  15262. }
  15263. }
  15264. return null;
  15265. }
  15266. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15267. const animationToMorphTargets = {};
  15268. // tested with https://regex101.com/ on trick sequences
  15269. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15270. const pattern = /^([\w-]*?)([\d]+)$/;
  15271. // sort morph target names into animation groups based
  15272. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15273. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15274. const morphTarget = morphTargets[ i ];
  15275. const parts = morphTarget.name.match( pattern );
  15276. if ( parts && parts.length > 1 ) {
  15277. const name = parts[ 1 ];
  15278. let animationMorphTargets = animationToMorphTargets[ name ];
  15279. if ( ! animationMorphTargets ) {
  15280. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15281. }
  15282. animationMorphTargets.push( morphTarget );
  15283. }
  15284. }
  15285. const clips = [];
  15286. for ( const name in animationToMorphTargets ) {
  15287. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15288. }
  15289. return clips;
  15290. }
  15291. // parse the animation.hierarchy format
  15292. static parseAnimation( animation, bones ) {
  15293. if ( ! animation ) {
  15294. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15295. return null;
  15296. }
  15297. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15298. // only return track if there are actually keys.
  15299. if ( animationKeys.length !== 0 ) {
  15300. const times = [];
  15301. const values = [];
  15302. flattenJSON( animationKeys, times, values, propertyName );
  15303. // empty keys are filtered out, so check again
  15304. if ( times.length !== 0 ) {
  15305. destTracks.push( new trackType( trackName, times, values ) );
  15306. }
  15307. }
  15308. };
  15309. const tracks = [];
  15310. const clipName = animation.name || 'default';
  15311. const fps = animation.fps || 30;
  15312. const blendMode = animation.blendMode;
  15313. // automatic length determination in AnimationClip.
  15314. let duration = animation.length || - 1;
  15315. const hierarchyTracks = animation.hierarchy || [];
  15316. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15317. const animationKeys = hierarchyTracks[ h ].keys;
  15318. // skip empty tracks
  15319. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15320. // process morph targets
  15321. if ( animationKeys[ 0 ].morphTargets ) {
  15322. // figure out all morph targets used in this track
  15323. const morphTargetNames = {};
  15324. let k;
  15325. for ( k = 0; k < animationKeys.length; k ++ ) {
  15326. if ( animationKeys[ k ].morphTargets ) {
  15327. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15328. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15329. }
  15330. }
  15331. }
  15332. // create a track for each morph target with all zero
  15333. // morphTargetInfluences except for the keys in which
  15334. // the morphTarget is named.
  15335. for ( const morphTargetName in morphTargetNames ) {
  15336. const times = [];
  15337. const values = [];
  15338. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15339. const animationKey = animationKeys[ k ];
  15340. times.push( animationKey.time );
  15341. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15342. }
  15343. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15344. }
  15345. duration = morphTargetNames.length * fps;
  15346. } else {
  15347. // ...assume skeletal animation
  15348. const boneName = '.bones[' + bones[ h ].name + ']';
  15349. addNonemptyTrack(
  15350. VectorKeyframeTrack, boneName + '.position',
  15351. animationKeys, 'pos', tracks );
  15352. addNonemptyTrack(
  15353. QuaternionKeyframeTrack, boneName + '.quaternion',
  15354. animationKeys, 'rot', tracks );
  15355. addNonemptyTrack(
  15356. VectorKeyframeTrack, boneName + '.scale',
  15357. animationKeys, 'scl', tracks );
  15358. }
  15359. }
  15360. if ( tracks.length === 0 ) {
  15361. return null;
  15362. }
  15363. const clip = new this( clipName, duration, tracks, blendMode );
  15364. return clip;
  15365. }
  15366. resetDuration() {
  15367. const tracks = this.tracks;
  15368. let duration = 0;
  15369. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15370. const track = this.tracks[ i ];
  15371. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15372. }
  15373. this.duration = duration;
  15374. return this;
  15375. }
  15376. trim() {
  15377. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15378. this.tracks[ i ].trim( 0, this.duration );
  15379. }
  15380. return this;
  15381. }
  15382. validate() {
  15383. let valid = true;
  15384. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15385. valid = valid && this.tracks[ i ].validate();
  15386. }
  15387. return valid;
  15388. }
  15389. optimize() {
  15390. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15391. this.tracks[ i ].optimize();
  15392. }
  15393. return this;
  15394. }
  15395. clone() {
  15396. const tracks = [];
  15397. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15398. tracks.push( this.tracks[ i ].clone() );
  15399. }
  15400. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15401. }
  15402. toJSON() {
  15403. return this.constructor.toJSON( this );
  15404. }
  15405. }
  15406. function getTrackTypeForValueTypeName( typeName ) {
  15407. switch ( typeName.toLowerCase() ) {
  15408. case 'scalar':
  15409. case 'double':
  15410. case 'float':
  15411. case 'number':
  15412. case 'integer':
  15413. return NumberKeyframeTrack;
  15414. case 'vector':
  15415. case 'vector2':
  15416. case 'vector3':
  15417. case 'vector4':
  15418. return VectorKeyframeTrack;
  15419. case 'color':
  15420. return ColorKeyframeTrack;
  15421. case 'quaternion':
  15422. return QuaternionKeyframeTrack;
  15423. case 'bool':
  15424. case 'boolean':
  15425. return BooleanKeyframeTrack;
  15426. case 'string':
  15427. return StringKeyframeTrack;
  15428. }
  15429. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15430. }
  15431. function parseKeyframeTrack( json ) {
  15432. if ( json.type === undefined ) {
  15433. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15434. }
  15435. const trackType = getTrackTypeForValueTypeName( json.type );
  15436. if ( json.times === undefined ) {
  15437. const times = [], values = [];
  15438. flattenJSON( json.keys, times, values, 'value' );
  15439. json.times = times;
  15440. json.values = values;
  15441. }
  15442. // derived classes can define a static parse method
  15443. if ( trackType.parse !== undefined ) {
  15444. return trackType.parse( json );
  15445. } else {
  15446. // by default, we assume a constructor compatible with the base
  15447. return new trackType( json.name, json.times, json.values, json.interpolation );
  15448. }
  15449. }
  15450. const Cache = {
  15451. enabled: false,
  15452. files: {},
  15453. add: function ( key, file ) {
  15454. if ( this.enabled === false ) return;
  15455. // console.log( 'THREE.Cache', 'Adding key:', key );
  15456. this.files[ key ] = file;
  15457. },
  15458. get: function ( key ) {
  15459. if ( this.enabled === false ) return;
  15460. // console.log( 'THREE.Cache', 'Checking key:', key );
  15461. return this.files[ key ];
  15462. },
  15463. remove: function ( key ) {
  15464. delete this.files[ key ];
  15465. },
  15466. clear: function () {
  15467. this.files = {};
  15468. }
  15469. };
  15470. class LoadingManager {
  15471. constructor( onLoad, onProgress, onError ) {
  15472. const scope = this;
  15473. let isLoading = false;
  15474. let itemsLoaded = 0;
  15475. let itemsTotal = 0;
  15476. let urlModifier = undefined;
  15477. const handlers = [];
  15478. // Refer to #5689 for the reason why we don't set .onStart
  15479. // in the constructor
  15480. this.onStart = undefined;
  15481. this.onLoad = onLoad;
  15482. this.onProgress = onProgress;
  15483. this.onError = onError;
  15484. this.itemStart = function ( url ) {
  15485. itemsTotal ++;
  15486. if ( isLoading === false ) {
  15487. if ( scope.onStart !== undefined ) {
  15488. scope.onStart( url, itemsLoaded, itemsTotal );
  15489. }
  15490. }
  15491. isLoading = true;
  15492. };
  15493. this.itemEnd = function ( url ) {
  15494. itemsLoaded ++;
  15495. if ( scope.onProgress !== undefined ) {
  15496. scope.onProgress( url, itemsLoaded, itemsTotal );
  15497. }
  15498. if ( itemsLoaded === itemsTotal ) {
  15499. isLoading = false;
  15500. if ( scope.onLoad !== undefined ) {
  15501. scope.onLoad();
  15502. }
  15503. }
  15504. };
  15505. this.itemError = function ( url ) {
  15506. if ( scope.onError !== undefined ) {
  15507. scope.onError( url );
  15508. }
  15509. };
  15510. this.resolveURL = function ( url ) {
  15511. if ( urlModifier ) {
  15512. return urlModifier( url );
  15513. }
  15514. return url;
  15515. };
  15516. this.setURLModifier = function ( transform ) {
  15517. urlModifier = transform;
  15518. return this;
  15519. };
  15520. this.addHandler = function ( regex, loader ) {
  15521. handlers.push( regex, loader );
  15522. return this;
  15523. };
  15524. this.removeHandler = function ( regex ) {
  15525. const index = handlers.indexOf( regex );
  15526. if ( index !== - 1 ) {
  15527. handlers.splice( index, 2 );
  15528. }
  15529. return this;
  15530. };
  15531. this.getHandler = function ( file ) {
  15532. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15533. const regex = handlers[ i ];
  15534. const loader = handlers[ i + 1 ];
  15535. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15536. if ( regex.test( file ) ) {
  15537. return loader;
  15538. }
  15539. }
  15540. return null;
  15541. };
  15542. }
  15543. }
  15544. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15545. class Loader {
  15546. constructor( manager ) {
  15547. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15548. this.crossOrigin = 'anonymous';
  15549. this.withCredentials = false;
  15550. this.path = '';
  15551. this.resourcePath = '';
  15552. this.requestHeader = {};
  15553. }
  15554. load( /* url, onLoad, onProgress, onError */ ) {}
  15555. loadAsync( url, onProgress ) {
  15556. const scope = this;
  15557. return new Promise( function ( resolve, reject ) {
  15558. scope.load( url, resolve, onProgress, reject );
  15559. } );
  15560. }
  15561. parse( /* data */ ) {}
  15562. setCrossOrigin( crossOrigin ) {
  15563. this.crossOrigin = crossOrigin;
  15564. return this;
  15565. }
  15566. setWithCredentials( value ) {
  15567. this.withCredentials = value;
  15568. return this;
  15569. }
  15570. setPath( path ) {
  15571. this.path = path;
  15572. return this;
  15573. }
  15574. setResourcePath( resourcePath ) {
  15575. this.resourcePath = resourcePath;
  15576. return this;
  15577. }
  15578. setRequestHeader( requestHeader ) {
  15579. this.requestHeader = requestHeader;
  15580. return this;
  15581. }
  15582. }
  15583. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15584. const loading = {};
  15585. class HttpError extends Error {
  15586. constructor( message, response ) {
  15587. super( message );
  15588. this.response = response;
  15589. }
  15590. }
  15591. class FileLoader extends Loader {
  15592. constructor( manager ) {
  15593. super( manager );
  15594. }
  15595. load( url, onLoad, onProgress, onError ) {
  15596. if ( url === undefined ) url = '';
  15597. if ( this.path !== undefined ) url = this.path + url;
  15598. url = this.manager.resolveURL( url );
  15599. const cached = Cache.get( url );
  15600. if ( cached !== undefined ) {
  15601. this.manager.itemStart( url );
  15602. setTimeout( () => {
  15603. if ( onLoad ) onLoad( cached );
  15604. this.manager.itemEnd( url );
  15605. }, 0 );
  15606. return cached;
  15607. }
  15608. // Check if request is duplicate
  15609. if ( loading[ url ] !== undefined ) {
  15610. loading[ url ].push( {
  15611. onLoad: onLoad,
  15612. onProgress: onProgress,
  15613. onError: onError
  15614. } );
  15615. return;
  15616. }
  15617. // Initialise array for duplicate requests
  15618. loading[ url ] = [];
  15619. loading[ url ].push( {
  15620. onLoad: onLoad,
  15621. onProgress: onProgress,
  15622. onError: onError,
  15623. } );
  15624. // create request
  15625. const req = new Request( url, {
  15626. headers: new Headers( this.requestHeader ),
  15627. credentials: this.withCredentials ? 'include' : 'same-origin',
  15628. // An abort controller could be added within a future PR
  15629. } );
  15630. // record states ( avoid data race )
  15631. const mimeType = this.mimeType;
  15632. const responseType = this.responseType;
  15633. // start the fetch
  15634. fetch( req )
  15635. .then( response => {
  15636. if ( response.status === 200 || response.status === 0 ) {
  15637. // Some browsers return HTTP Status 0 when using non-http protocol
  15638. // e.g. 'file://' or 'data://'. Handle as success.
  15639. if ( response.status === 0 ) {
  15640. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15641. }
  15642. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15643. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15644. return response;
  15645. }
  15646. const callbacks = loading[ url ];
  15647. const reader = response.body.getReader();
  15648. // Nginx needs X-File-Size check
  15649. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15650. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15651. const total = contentLength ? parseInt( contentLength ) : 0;
  15652. const lengthComputable = total !== 0;
  15653. let loaded = 0;
  15654. // periodically read data into the new stream tracking while download progress
  15655. const stream = new ReadableStream( {
  15656. start( controller ) {
  15657. readData();
  15658. function readData() {
  15659. reader.read().then( ( { done, value } ) => {
  15660. if ( done ) {
  15661. controller.close();
  15662. } else {
  15663. loaded += value.byteLength;
  15664. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15665. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15666. const callback = callbacks[ i ];
  15667. if ( callback.onProgress ) callback.onProgress( event );
  15668. }
  15669. controller.enqueue( value );
  15670. readData();
  15671. }
  15672. }, ( e ) => {
  15673. controller.error( e );
  15674. } );
  15675. }
  15676. }
  15677. } );
  15678. return new Response( stream );
  15679. } else {
  15680. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15681. }
  15682. } )
  15683. .then( response => {
  15684. switch ( responseType ) {
  15685. case 'arraybuffer':
  15686. return response.arrayBuffer();
  15687. case 'blob':
  15688. return response.blob();
  15689. case 'document':
  15690. return response.text()
  15691. .then( text => {
  15692. const parser = new DOMParser();
  15693. return parser.parseFromString( text, mimeType );
  15694. } );
  15695. case 'json':
  15696. return response.json();
  15697. default:
  15698. if ( mimeType === undefined ) {
  15699. return response.text();
  15700. } else {
  15701. // sniff encoding
  15702. const re = /charset="?([^;"\s]*)"?/i;
  15703. const exec = re.exec( mimeType );
  15704. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15705. const decoder = new TextDecoder( label );
  15706. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15707. }
  15708. }
  15709. } )
  15710. .then( data => {
  15711. // Add to cache only on HTTP success, so that we do not cache
  15712. // error response bodies as proper responses to requests.
  15713. Cache.add( url, data );
  15714. const callbacks = loading[ url ];
  15715. delete loading[ url ];
  15716. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15717. const callback = callbacks[ i ];
  15718. if ( callback.onLoad ) callback.onLoad( data );
  15719. }
  15720. } )
  15721. .catch( err => {
  15722. // Abort errors and other errors are handled the same
  15723. const callbacks = loading[ url ];
  15724. if ( callbacks === undefined ) {
  15725. // When onLoad was called and url was deleted in `loading`
  15726. this.manager.itemError( url );
  15727. throw err;
  15728. }
  15729. delete loading[ url ];
  15730. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15731. const callback = callbacks[ i ];
  15732. if ( callback.onError ) callback.onError( err );
  15733. }
  15734. this.manager.itemError( url );
  15735. } )
  15736. .finally( () => {
  15737. this.manager.itemEnd( url );
  15738. } );
  15739. this.manager.itemStart( url );
  15740. }
  15741. setResponseType( value ) {
  15742. this.responseType = value;
  15743. return this;
  15744. }
  15745. setMimeType( value ) {
  15746. this.mimeType = value;
  15747. return this;
  15748. }
  15749. }
  15750. class AnimationLoader extends Loader {
  15751. constructor( manager ) {
  15752. super( manager );
  15753. }
  15754. load( url, onLoad, onProgress, onError ) {
  15755. const scope = this;
  15756. const loader = new FileLoader( this.manager );
  15757. loader.setPath( this.path );
  15758. loader.setRequestHeader( this.requestHeader );
  15759. loader.setWithCredentials( this.withCredentials );
  15760. loader.load( url, function ( text ) {
  15761. try {
  15762. onLoad( scope.parse( JSON.parse( text ) ) );
  15763. } catch ( e ) {
  15764. if ( onError ) {
  15765. onError( e );
  15766. } else {
  15767. console.error( e );
  15768. }
  15769. scope.manager.itemError( url );
  15770. }
  15771. }, onProgress, onError );
  15772. }
  15773. parse( json ) {
  15774. const animations = [];
  15775. for ( let i = 0; i < json.length; i ++ ) {
  15776. const clip = AnimationClip.parse( json[ i ] );
  15777. animations.push( clip );
  15778. }
  15779. return animations;
  15780. }
  15781. }
  15782. /**
  15783. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15784. *
  15785. * Sub classes have to implement the parse() method which will be used in load().
  15786. */
  15787. class CompressedTextureLoader extends Loader {
  15788. constructor( manager ) {
  15789. super( manager );
  15790. }
  15791. load( url, onLoad, onProgress, onError ) {
  15792. const scope = this;
  15793. const images = [];
  15794. const texture = new CompressedTexture();
  15795. const loader = new FileLoader( this.manager );
  15796. loader.setPath( this.path );
  15797. loader.setResponseType( 'arraybuffer' );
  15798. loader.setRequestHeader( this.requestHeader );
  15799. loader.setWithCredentials( scope.withCredentials );
  15800. let loaded = 0;
  15801. function loadTexture( i ) {
  15802. loader.load( url[ i ], function ( buffer ) {
  15803. const texDatas = scope.parse( buffer, true );
  15804. images[ i ] = {
  15805. width: texDatas.width,
  15806. height: texDatas.height,
  15807. format: texDatas.format,
  15808. mipmaps: texDatas.mipmaps
  15809. };
  15810. loaded += 1;
  15811. if ( loaded === 6 ) {
  15812. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15813. texture.image = images;
  15814. texture.format = texDatas.format;
  15815. texture.needsUpdate = true;
  15816. if ( onLoad ) onLoad( texture );
  15817. }
  15818. }, onProgress, onError );
  15819. }
  15820. if ( Array.isArray( url ) ) {
  15821. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15822. loadTexture( i );
  15823. }
  15824. } else {
  15825. // compressed cubemap texture stored in a single DDS file
  15826. loader.load( url, function ( buffer ) {
  15827. const texDatas = scope.parse( buffer, true );
  15828. if ( texDatas.isCubemap ) {
  15829. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15830. for ( let f = 0; f < faces; f ++ ) {
  15831. images[ f ] = { mipmaps: [] };
  15832. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15833. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15834. images[ f ].format = texDatas.format;
  15835. images[ f ].width = texDatas.width;
  15836. images[ f ].height = texDatas.height;
  15837. }
  15838. }
  15839. texture.image = images;
  15840. } else {
  15841. texture.image.width = texDatas.width;
  15842. texture.image.height = texDatas.height;
  15843. texture.mipmaps = texDatas.mipmaps;
  15844. }
  15845. if ( texDatas.mipmapCount === 1 ) {
  15846. texture.minFilter = LinearFilter;
  15847. }
  15848. texture.format = texDatas.format;
  15849. texture.needsUpdate = true;
  15850. if ( onLoad ) onLoad( texture );
  15851. }, onProgress, onError );
  15852. }
  15853. return texture;
  15854. }
  15855. }
  15856. class ImageLoader extends Loader {
  15857. constructor( manager ) {
  15858. super( manager );
  15859. }
  15860. load( url, onLoad, onProgress, onError ) {
  15861. if ( this.path !== undefined ) url = this.path + url;
  15862. url = this.manager.resolveURL( url );
  15863. const scope = this;
  15864. const cached = Cache.get( url );
  15865. if ( cached !== undefined ) {
  15866. scope.manager.itemStart( url );
  15867. setTimeout( function () {
  15868. if ( onLoad ) onLoad( cached );
  15869. scope.manager.itemEnd( url );
  15870. }, 0 );
  15871. return cached;
  15872. }
  15873. const image = createElementNS( 'img' );
  15874. function onImageLoad() {
  15875. removeEventListeners();
  15876. Cache.add( url, this );
  15877. if ( onLoad ) onLoad( this );
  15878. scope.manager.itemEnd( url );
  15879. }
  15880. function onImageError( event ) {
  15881. removeEventListeners();
  15882. if ( onError ) onError( event );
  15883. scope.manager.itemError( url );
  15884. scope.manager.itemEnd( url );
  15885. }
  15886. function removeEventListeners() {
  15887. image.removeEventListener( 'load', onImageLoad, false );
  15888. image.removeEventListener( 'error', onImageError, false );
  15889. }
  15890. image.addEventListener( 'load', onImageLoad, false );
  15891. image.addEventListener( 'error', onImageError, false );
  15892. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15893. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15894. }
  15895. scope.manager.itemStart( url );
  15896. image.src = url;
  15897. return image;
  15898. }
  15899. }
  15900. class CubeTextureLoader extends Loader {
  15901. constructor( manager ) {
  15902. super( manager );
  15903. }
  15904. load( urls, onLoad, onProgress, onError ) {
  15905. const texture = new CubeTexture();
  15906. texture.colorSpace = SRGBColorSpace;
  15907. const loader = new ImageLoader( this.manager );
  15908. loader.setCrossOrigin( this.crossOrigin );
  15909. loader.setPath( this.path );
  15910. let loaded = 0;
  15911. function loadTexture( i ) {
  15912. loader.load( urls[ i ], function ( image ) {
  15913. texture.images[ i ] = image;
  15914. loaded ++;
  15915. if ( loaded === 6 ) {
  15916. texture.needsUpdate = true;
  15917. if ( onLoad ) onLoad( texture );
  15918. }
  15919. }, undefined, onError );
  15920. }
  15921. for ( let i = 0; i < urls.length; ++ i ) {
  15922. loadTexture( i );
  15923. }
  15924. return texture;
  15925. }
  15926. }
  15927. /**
  15928. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15929. *
  15930. * Sub classes have to implement the parse() method which will be used in load().
  15931. */
  15932. class DataTextureLoader extends Loader {
  15933. constructor( manager ) {
  15934. super( manager );
  15935. }
  15936. load( url, onLoad, onProgress, onError ) {
  15937. const scope = this;
  15938. const texture = new DataTexture();
  15939. const loader = new FileLoader( this.manager );
  15940. loader.setResponseType( 'arraybuffer' );
  15941. loader.setRequestHeader( this.requestHeader );
  15942. loader.setPath( this.path );
  15943. loader.setWithCredentials( scope.withCredentials );
  15944. loader.load( url, function ( buffer ) {
  15945. let texData;
  15946. try {
  15947. texData = scope.parse( buffer );
  15948. } catch ( error ) {
  15949. if ( onError !== undefined ) {
  15950. onError( error );
  15951. } else {
  15952. console.error( error );
  15953. return;
  15954. }
  15955. }
  15956. if ( texData.image !== undefined ) {
  15957. texture.image = texData.image;
  15958. } else if ( texData.data !== undefined ) {
  15959. texture.image.width = texData.width;
  15960. texture.image.height = texData.height;
  15961. texture.image.data = texData.data;
  15962. }
  15963. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  15964. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  15965. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  15966. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  15967. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  15968. if ( texData.colorSpace !== undefined ) {
  15969. texture.colorSpace = texData.colorSpace;
  15970. }
  15971. if ( texData.flipY !== undefined ) {
  15972. texture.flipY = texData.flipY;
  15973. }
  15974. if ( texData.format !== undefined ) {
  15975. texture.format = texData.format;
  15976. }
  15977. if ( texData.type !== undefined ) {
  15978. texture.type = texData.type;
  15979. }
  15980. if ( texData.mipmaps !== undefined ) {
  15981. texture.mipmaps = texData.mipmaps;
  15982. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  15983. }
  15984. if ( texData.mipmapCount === 1 ) {
  15985. texture.minFilter = LinearFilter;
  15986. }
  15987. if ( texData.generateMipmaps !== undefined ) {
  15988. texture.generateMipmaps = texData.generateMipmaps;
  15989. }
  15990. texture.needsUpdate = true;
  15991. if ( onLoad ) onLoad( texture, texData );
  15992. }, onProgress, onError );
  15993. return texture;
  15994. }
  15995. }
  15996. class TextureLoader extends Loader {
  15997. constructor( manager ) {
  15998. super( manager );
  15999. }
  16000. load( url, onLoad, onProgress, onError ) {
  16001. const texture = new Texture();
  16002. const loader = new ImageLoader( this.manager );
  16003. loader.setCrossOrigin( this.crossOrigin );
  16004. loader.setPath( this.path );
  16005. loader.load( url, function ( image ) {
  16006. texture.image = image;
  16007. texture.needsUpdate = true;
  16008. if ( onLoad !== undefined ) {
  16009. onLoad( texture );
  16010. }
  16011. }, onProgress, onError );
  16012. return texture;
  16013. }
  16014. }
  16015. class Light extends Object3D {
  16016. constructor( color, intensity = 1 ) {
  16017. super();
  16018. this.isLight = true;
  16019. this.type = 'Light';
  16020. this.color = new Color( color );
  16021. this.intensity = intensity;
  16022. }
  16023. dispose() {
  16024. // Empty here in base class; some subclasses override.
  16025. }
  16026. copy( source, recursive ) {
  16027. super.copy( source, recursive );
  16028. this.color.copy( source.color );
  16029. this.intensity = source.intensity;
  16030. return this;
  16031. }
  16032. toJSON( meta ) {
  16033. const data = super.toJSON( meta );
  16034. data.object.color = this.color.getHex();
  16035. data.object.intensity = this.intensity;
  16036. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16037. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16038. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16039. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16040. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16041. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16042. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16043. return data;
  16044. }
  16045. }
  16046. class HemisphereLight extends Light {
  16047. constructor( skyColor, groundColor, intensity ) {
  16048. super( skyColor, intensity );
  16049. this.isHemisphereLight = true;
  16050. this.type = 'HemisphereLight';
  16051. this.position.copy( Object3D.DEFAULT_UP );
  16052. this.updateMatrix();
  16053. this.groundColor = new Color( groundColor );
  16054. }
  16055. copy( source, recursive ) {
  16056. super.copy( source, recursive );
  16057. this.groundColor.copy( source.groundColor );
  16058. return this;
  16059. }
  16060. }
  16061. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16062. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16063. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16064. class LightShadow {
  16065. constructor( camera ) {
  16066. this.camera = camera;
  16067. this.intensity = 1;
  16068. this.bias = 0;
  16069. this.normalBias = 0;
  16070. this.radius = 1;
  16071. this.blurSamples = 8;
  16072. this.mapSize = new Vector2( 512, 512 );
  16073. this.map = null;
  16074. this.mapPass = null;
  16075. this.matrix = new Matrix4();
  16076. this.autoUpdate = true;
  16077. this.needsUpdate = false;
  16078. this._frustum = new Frustum();
  16079. this._frameExtents = new Vector2( 1, 1 );
  16080. this._viewportCount = 1;
  16081. this._viewports = [
  16082. new Vector4( 0, 0, 1, 1 )
  16083. ];
  16084. }
  16085. getViewportCount() {
  16086. return this._viewportCount;
  16087. }
  16088. getFrustum() {
  16089. return this._frustum;
  16090. }
  16091. updateMatrices( light ) {
  16092. const shadowCamera = this.camera;
  16093. const shadowMatrix = this.matrix;
  16094. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16095. shadowCamera.position.copy( _lightPositionWorld$1 );
  16096. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16097. shadowCamera.lookAt( _lookTarget$1 );
  16098. shadowCamera.updateMatrixWorld();
  16099. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16100. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16101. shadowMatrix.set(
  16102. 0.5, 0.0, 0.0, 0.5,
  16103. 0.0, 0.5, 0.0, 0.5,
  16104. 0.0, 0.0, 0.5, 0.5,
  16105. 0.0, 0.0, 0.0, 1.0
  16106. );
  16107. shadowMatrix.multiply( _projScreenMatrix$2 );
  16108. }
  16109. getViewport( viewportIndex ) {
  16110. return this._viewports[ viewportIndex ];
  16111. }
  16112. getFrameExtents() {
  16113. return this._frameExtents;
  16114. }
  16115. dispose() {
  16116. if ( this.map ) {
  16117. this.map.dispose();
  16118. }
  16119. if ( this.mapPass ) {
  16120. this.mapPass.dispose();
  16121. }
  16122. }
  16123. copy( source ) {
  16124. this.camera = source.camera.clone();
  16125. this.intensity = source.intensity;
  16126. this.bias = source.bias;
  16127. this.radius = source.radius;
  16128. this.mapSize.copy( source.mapSize );
  16129. return this;
  16130. }
  16131. clone() {
  16132. return new this.constructor().copy( this );
  16133. }
  16134. toJSON() {
  16135. const object = {};
  16136. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16137. if ( this.bias !== 0 ) object.bias = this.bias;
  16138. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16139. if ( this.radius !== 1 ) object.radius = this.radius;
  16140. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16141. object.camera = this.camera.toJSON( false ).object;
  16142. delete object.camera.matrix;
  16143. return object;
  16144. }
  16145. }
  16146. class SpotLightShadow extends LightShadow {
  16147. constructor() {
  16148. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16149. this.isSpotLightShadow = true;
  16150. this.focus = 1;
  16151. }
  16152. updateMatrices( light ) {
  16153. const camera = this.camera;
  16154. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16155. const aspect = this.mapSize.width / this.mapSize.height;
  16156. const far = light.distance || camera.far;
  16157. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16158. camera.fov = fov;
  16159. camera.aspect = aspect;
  16160. camera.far = far;
  16161. camera.updateProjectionMatrix();
  16162. }
  16163. super.updateMatrices( light );
  16164. }
  16165. copy( source ) {
  16166. super.copy( source );
  16167. this.focus = source.focus;
  16168. return this;
  16169. }
  16170. }
  16171. class SpotLight extends Light {
  16172. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16173. super( color, intensity );
  16174. this.isSpotLight = true;
  16175. this.type = 'SpotLight';
  16176. this.position.copy( Object3D.DEFAULT_UP );
  16177. this.updateMatrix();
  16178. this.target = new Object3D();
  16179. this.distance = distance;
  16180. this.angle = angle;
  16181. this.penumbra = penumbra;
  16182. this.decay = decay;
  16183. this.map = null;
  16184. this.shadow = new SpotLightShadow();
  16185. }
  16186. get power() {
  16187. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16188. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16189. return this.intensity * Math.PI;
  16190. }
  16191. set power( power ) {
  16192. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16193. this.intensity = power / Math.PI;
  16194. }
  16195. dispose() {
  16196. this.shadow.dispose();
  16197. }
  16198. copy( source, recursive ) {
  16199. super.copy( source, recursive );
  16200. this.distance = source.distance;
  16201. this.angle = source.angle;
  16202. this.penumbra = source.penumbra;
  16203. this.decay = source.decay;
  16204. this.target = source.target.clone();
  16205. this.shadow = source.shadow.clone();
  16206. return this;
  16207. }
  16208. }
  16209. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16210. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16211. const _lookTarget = /*@__PURE__*/ new Vector3();
  16212. class PointLightShadow extends LightShadow {
  16213. constructor() {
  16214. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16215. this.isPointLightShadow = true;
  16216. this._frameExtents = new Vector2( 4, 2 );
  16217. this._viewportCount = 6;
  16218. this._viewports = [
  16219. // These viewports map a cube-map onto a 2D texture with the
  16220. // following orientation:
  16221. //
  16222. // xzXZ
  16223. // y Y
  16224. //
  16225. // X - Positive x direction
  16226. // x - Negative x direction
  16227. // Y - Positive y direction
  16228. // y - Negative y direction
  16229. // Z - Positive z direction
  16230. // z - Negative z direction
  16231. // positive X
  16232. new Vector4( 2, 1, 1, 1 ),
  16233. // negative X
  16234. new Vector4( 0, 1, 1, 1 ),
  16235. // positive Z
  16236. new Vector4( 3, 1, 1, 1 ),
  16237. // negative Z
  16238. new Vector4( 1, 1, 1, 1 ),
  16239. // positive Y
  16240. new Vector4( 3, 0, 1, 1 ),
  16241. // negative Y
  16242. new Vector4( 1, 0, 1, 1 )
  16243. ];
  16244. this._cubeDirections = [
  16245. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16246. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16247. ];
  16248. this._cubeUps = [
  16249. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16250. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16251. ];
  16252. }
  16253. updateMatrices( light, viewportIndex = 0 ) {
  16254. const camera = this.camera;
  16255. const shadowMatrix = this.matrix;
  16256. const far = light.distance || camera.far;
  16257. if ( far !== camera.far ) {
  16258. camera.far = far;
  16259. camera.updateProjectionMatrix();
  16260. }
  16261. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16262. camera.position.copy( _lightPositionWorld );
  16263. _lookTarget.copy( camera.position );
  16264. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16265. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16266. camera.lookAt( _lookTarget );
  16267. camera.updateMatrixWorld();
  16268. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16269. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16270. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16271. }
  16272. }
  16273. class PointLight extends Light {
  16274. constructor( color, intensity, distance = 0, decay = 2 ) {
  16275. super( color, intensity );
  16276. this.isPointLight = true;
  16277. this.type = 'PointLight';
  16278. this.distance = distance;
  16279. this.decay = decay;
  16280. this.shadow = new PointLightShadow();
  16281. }
  16282. get power() {
  16283. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16284. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16285. return this.intensity * 4 * Math.PI;
  16286. }
  16287. set power( power ) {
  16288. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16289. this.intensity = power / ( 4 * Math.PI );
  16290. }
  16291. dispose() {
  16292. this.shadow.dispose();
  16293. }
  16294. copy( source, recursive ) {
  16295. super.copy( source, recursive );
  16296. this.distance = source.distance;
  16297. this.decay = source.decay;
  16298. this.shadow = source.shadow.clone();
  16299. return this;
  16300. }
  16301. }
  16302. class OrthographicCamera extends Camera {
  16303. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16304. super();
  16305. this.isOrthographicCamera = true;
  16306. this.type = 'OrthographicCamera';
  16307. this.zoom = 1;
  16308. this.view = null;
  16309. this.left = left;
  16310. this.right = right;
  16311. this.top = top;
  16312. this.bottom = bottom;
  16313. this.near = near;
  16314. this.far = far;
  16315. this.updateProjectionMatrix();
  16316. }
  16317. copy( source, recursive ) {
  16318. super.copy( source, recursive );
  16319. this.left = source.left;
  16320. this.right = source.right;
  16321. this.top = source.top;
  16322. this.bottom = source.bottom;
  16323. this.near = source.near;
  16324. this.far = source.far;
  16325. this.zoom = source.zoom;
  16326. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16327. return this;
  16328. }
  16329. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16330. if ( this.view === null ) {
  16331. this.view = {
  16332. enabled: true,
  16333. fullWidth: 1,
  16334. fullHeight: 1,
  16335. offsetX: 0,
  16336. offsetY: 0,
  16337. width: 1,
  16338. height: 1
  16339. };
  16340. }
  16341. this.view.enabled = true;
  16342. this.view.fullWidth = fullWidth;
  16343. this.view.fullHeight = fullHeight;
  16344. this.view.offsetX = x;
  16345. this.view.offsetY = y;
  16346. this.view.width = width;
  16347. this.view.height = height;
  16348. this.updateProjectionMatrix();
  16349. }
  16350. clearViewOffset() {
  16351. if ( this.view !== null ) {
  16352. this.view.enabled = false;
  16353. }
  16354. this.updateProjectionMatrix();
  16355. }
  16356. updateProjectionMatrix() {
  16357. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16358. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16359. const cx = ( this.right + this.left ) / 2;
  16360. const cy = ( this.top + this.bottom ) / 2;
  16361. let left = cx - dx;
  16362. let right = cx + dx;
  16363. let top = cy + dy;
  16364. let bottom = cy - dy;
  16365. if ( this.view !== null && this.view.enabled ) {
  16366. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16367. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16368. left += scaleW * this.view.offsetX;
  16369. right = left + scaleW * this.view.width;
  16370. top -= scaleH * this.view.offsetY;
  16371. bottom = top - scaleH * this.view.height;
  16372. }
  16373. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16374. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16375. }
  16376. toJSON( meta ) {
  16377. const data = super.toJSON( meta );
  16378. data.object.zoom = this.zoom;
  16379. data.object.left = this.left;
  16380. data.object.right = this.right;
  16381. data.object.top = this.top;
  16382. data.object.bottom = this.bottom;
  16383. data.object.near = this.near;
  16384. data.object.far = this.far;
  16385. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16386. return data;
  16387. }
  16388. }
  16389. class DirectionalLightShadow extends LightShadow {
  16390. constructor() {
  16391. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16392. this.isDirectionalLightShadow = true;
  16393. }
  16394. }
  16395. class DirectionalLight extends Light {
  16396. constructor( color, intensity ) {
  16397. super( color, intensity );
  16398. this.isDirectionalLight = true;
  16399. this.type = 'DirectionalLight';
  16400. this.position.copy( Object3D.DEFAULT_UP );
  16401. this.updateMatrix();
  16402. this.target = new Object3D();
  16403. this.shadow = new DirectionalLightShadow();
  16404. }
  16405. dispose() {
  16406. this.shadow.dispose();
  16407. }
  16408. copy( source ) {
  16409. super.copy( source );
  16410. this.target = source.target.clone();
  16411. this.shadow = source.shadow.clone();
  16412. return this;
  16413. }
  16414. }
  16415. class AmbientLight extends Light {
  16416. constructor( color, intensity ) {
  16417. super( color, intensity );
  16418. this.isAmbientLight = true;
  16419. this.type = 'AmbientLight';
  16420. }
  16421. }
  16422. class RectAreaLight extends Light {
  16423. constructor( color, intensity, width = 10, height = 10 ) {
  16424. super( color, intensity );
  16425. this.isRectAreaLight = true;
  16426. this.type = 'RectAreaLight';
  16427. this.width = width;
  16428. this.height = height;
  16429. }
  16430. get power() {
  16431. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16432. return this.intensity * this.width * this.height * Math.PI;
  16433. }
  16434. set power( power ) {
  16435. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16436. this.intensity = power / ( this.width * this.height * Math.PI );
  16437. }
  16438. copy( source ) {
  16439. super.copy( source );
  16440. this.width = source.width;
  16441. this.height = source.height;
  16442. return this;
  16443. }
  16444. toJSON( meta ) {
  16445. const data = super.toJSON( meta );
  16446. data.object.width = this.width;
  16447. data.object.height = this.height;
  16448. return data;
  16449. }
  16450. }
  16451. /**
  16452. * Primary reference:
  16453. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16454. *
  16455. * Secondary reference:
  16456. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16457. */
  16458. // 3-band SH defined by 9 coefficients
  16459. class SphericalHarmonics3 {
  16460. constructor() {
  16461. this.isSphericalHarmonics3 = true;
  16462. this.coefficients = [];
  16463. for ( let i = 0; i < 9; i ++ ) {
  16464. this.coefficients.push( new Vector3() );
  16465. }
  16466. }
  16467. set( coefficients ) {
  16468. for ( let i = 0; i < 9; i ++ ) {
  16469. this.coefficients[ i ].copy( coefficients[ i ] );
  16470. }
  16471. return this;
  16472. }
  16473. zero() {
  16474. for ( let i = 0; i < 9; i ++ ) {
  16475. this.coefficients[ i ].set( 0, 0, 0 );
  16476. }
  16477. return this;
  16478. }
  16479. // get the radiance in the direction of the normal
  16480. // target is a Vector3
  16481. getAt( normal, target ) {
  16482. // normal is assumed to be unit length
  16483. const x = normal.x, y = normal.y, z = normal.z;
  16484. const coeff = this.coefficients;
  16485. // band 0
  16486. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16487. // band 1
  16488. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16489. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16490. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16491. // band 2
  16492. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16493. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16494. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16495. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16496. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16497. return target;
  16498. }
  16499. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16500. // target is a Vector3
  16501. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16502. getIrradianceAt( normal, target ) {
  16503. // normal is assumed to be unit length
  16504. const x = normal.x, y = normal.y, z = normal.z;
  16505. const coeff = this.coefficients;
  16506. // band 0
  16507. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16508. // band 1
  16509. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16510. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16511. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16512. // band 2
  16513. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16514. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16515. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16516. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16517. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16518. return target;
  16519. }
  16520. add( sh ) {
  16521. for ( let i = 0; i < 9; i ++ ) {
  16522. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16523. }
  16524. return this;
  16525. }
  16526. addScaledSH( sh, s ) {
  16527. for ( let i = 0; i < 9; i ++ ) {
  16528. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16529. }
  16530. return this;
  16531. }
  16532. scale( s ) {
  16533. for ( let i = 0; i < 9; i ++ ) {
  16534. this.coefficients[ i ].multiplyScalar( s );
  16535. }
  16536. return this;
  16537. }
  16538. lerp( sh, alpha ) {
  16539. for ( let i = 0; i < 9; i ++ ) {
  16540. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16541. }
  16542. return this;
  16543. }
  16544. equals( sh ) {
  16545. for ( let i = 0; i < 9; i ++ ) {
  16546. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16547. return false;
  16548. }
  16549. }
  16550. return true;
  16551. }
  16552. copy( sh ) {
  16553. return this.set( sh.coefficients );
  16554. }
  16555. clone() {
  16556. return new this.constructor().copy( this );
  16557. }
  16558. fromArray( array, offset = 0 ) {
  16559. const coefficients = this.coefficients;
  16560. for ( let i = 0; i < 9; i ++ ) {
  16561. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16562. }
  16563. return this;
  16564. }
  16565. toArray( array = [], offset = 0 ) {
  16566. const coefficients = this.coefficients;
  16567. for ( let i = 0; i < 9; i ++ ) {
  16568. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16569. }
  16570. return array;
  16571. }
  16572. // evaluate the basis functions
  16573. // shBasis is an Array[ 9 ]
  16574. static getBasisAt( normal, shBasis ) {
  16575. // normal is assumed to be unit length
  16576. const x = normal.x, y = normal.y, z = normal.z;
  16577. // band 0
  16578. shBasis[ 0 ] = 0.282095;
  16579. // band 1
  16580. shBasis[ 1 ] = 0.488603 * y;
  16581. shBasis[ 2 ] = 0.488603 * z;
  16582. shBasis[ 3 ] = 0.488603 * x;
  16583. // band 2
  16584. shBasis[ 4 ] = 1.092548 * x * y;
  16585. shBasis[ 5 ] = 1.092548 * y * z;
  16586. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16587. shBasis[ 7 ] = 1.092548 * x * z;
  16588. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16589. }
  16590. }
  16591. class LightProbe extends Light {
  16592. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16593. super( undefined, intensity );
  16594. this.isLightProbe = true;
  16595. this.sh = sh;
  16596. }
  16597. copy( source ) {
  16598. super.copy( source );
  16599. this.sh.copy( source.sh );
  16600. return this;
  16601. }
  16602. fromJSON( json ) {
  16603. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16604. this.sh.fromArray( json.sh );
  16605. return this;
  16606. }
  16607. toJSON( meta ) {
  16608. const data = super.toJSON( meta );
  16609. data.object.sh = this.sh.toArray();
  16610. return data;
  16611. }
  16612. }
  16613. class MaterialLoader extends Loader {
  16614. constructor( manager ) {
  16615. super( manager );
  16616. this.textures = {};
  16617. }
  16618. load( url, onLoad, onProgress, onError ) {
  16619. const scope = this;
  16620. const loader = new FileLoader( scope.manager );
  16621. loader.setPath( scope.path );
  16622. loader.setRequestHeader( scope.requestHeader );
  16623. loader.setWithCredentials( scope.withCredentials );
  16624. loader.load( url, function ( text ) {
  16625. try {
  16626. onLoad( scope.parse( JSON.parse( text ) ) );
  16627. } catch ( e ) {
  16628. if ( onError ) {
  16629. onError( e );
  16630. } else {
  16631. console.error( e );
  16632. }
  16633. scope.manager.itemError( url );
  16634. }
  16635. }, onProgress, onError );
  16636. }
  16637. parse( json ) {
  16638. const textures = this.textures;
  16639. function getTexture( name ) {
  16640. if ( textures[ name ] === undefined ) {
  16641. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16642. }
  16643. return textures[ name ];
  16644. }
  16645. const material = MaterialLoader.createMaterialFromType( json.type );
  16646. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16647. if ( json.name !== undefined ) material.name = json.name;
  16648. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16649. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16650. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16651. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16652. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16653. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16654. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16655. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16656. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16657. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16658. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16659. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16660. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16661. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16662. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16663. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16664. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16665. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16666. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16667. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16668. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16669. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16670. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16671. if ( json.fog !== undefined ) material.fog = json.fog;
  16672. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16673. if ( json.blending !== undefined ) material.blending = json.blending;
  16674. if ( json.combine !== undefined ) material.combine = json.combine;
  16675. if ( json.side !== undefined ) material.side = json.side;
  16676. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16677. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16678. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16679. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16680. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16681. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16682. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16683. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16684. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16685. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16686. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16687. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16688. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16689. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16690. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16691. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16692. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16693. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16694. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16695. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16696. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16697. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16698. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16699. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16700. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16701. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16702. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16703. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16704. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16705. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16706. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16707. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16708. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16709. if ( json.scale !== undefined ) material.scale = json.scale;
  16710. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16711. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16712. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16713. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16714. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16715. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16716. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16717. if ( json.visible !== undefined ) material.visible = json.visible;
  16718. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16719. if ( json.userData !== undefined ) material.userData = json.userData;
  16720. if ( json.vertexColors !== undefined ) {
  16721. if ( typeof json.vertexColors === 'number' ) {
  16722. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16723. } else {
  16724. material.vertexColors = json.vertexColors;
  16725. }
  16726. }
  16727. // Shader Material
  16728. if ( json.uniforms !== undefined ) {
  16729. for ( const name in json.uniforms ) {
  16730. const uniform = json.uniforms[ name ];
  16731. material.uniforms[ name ] = {};
  16732. switch ( uniform.type ) {
  16733. case 't':
  16734. material.uniforms[ name ].value = getTexture( uniform.value );
  16735. break;
  16736. case 'c':
  16737. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16738. break;
  16739. case 'v2':
  16740. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16741. break;
  16742. case 'v3':
  16743. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16744. break;
  16745. case 'v4':
  16746. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16747. break;
  16748. case 'm3':
  16749. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16750. break;
  16751. case 'm4':
  16752. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16753. break;
  16754. default:
  16755. material.uniforms[ name ].value = uniform.value;
  16756. }
  16757. }
  16758. }
  16759. if ( json.defines !== undefined ) material.defines = json.defines;
  16760. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16761. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16762. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16763. if ( json.extensions !== undefined ) {
  16764. for ( const key in json.extensions ) {
  16765. material.extensions[ key ] = json.extensions[ key ];
  16766. }
  16767. }
  16768. if ( json.lights !== undefined ) material.lights = json.lights;
  16769. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16770. // for PointsMaterial
  16771. if ( json.size !== undefined ) material.size = json.size;
  16772. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16773. // maps
  16774. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16775. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16776. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16777. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16778. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16779. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16780. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16781. if ( json.normalScale !== undefined ) {
  16782. let normalScale = json.normalScale;
  16783. if ( Array.isArray( normalScale ) === false ) {
  16784. // Blender exporter used to export a scalar. See #7459
  16785. normalScale = [ normalScale, normalScale ];
  16786. }
  16787. material.normalScale = new Vector2().fromArray( normalScale );
  16788. }
  16789. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16790. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16791. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16792. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16793. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16794. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16795. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16796. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16797. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16798. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16799. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16800. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16801. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16802. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16803. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16804. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16805. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16806. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16807. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16808. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16809. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16810. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16811. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16812. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16813. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16814. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16815. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16816. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16817. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16818. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16819. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16820. return material;
  16821. }
  16822. setTextures( value ) {
  16823. this.textures = value;
  16824. return this;
  16825. }
  16826. static createMaterialFromType( type ) {
  16827. const materialLib = {
  16828. ShadowMaterial,
  16829. SpriteMaterial,
  16830. RawShaderMaterial,
  16831. ShaderMaterial,
  16832. PointsMaterial,
  16833. MeshPhysicalMaterial,
  16834. MeshStandardMaterial,
  16835. MeshPhongMaterial,
  16836. MeshToonMaterial,
  16837. MeshNormalMaterial,
  16838. MeshLambertMaterial,
  16839. MeshDepthMaterial,
  16840. MeshDistanceMaterial,
  16841. MeshBasicMaterial,
  16842. MeshMatcapMaterial,
  16843. LineDashedMaterial,
  16844. LineBasicMaterial,
  16845. Material
  16846. };
  16847. return new materialLib[ type ]();
  16848. }
  16849. }
  16850. class LoaderUtils {
  16851. static decodeText( array ) { // @deprecated, r165
  16852. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16853. if ( typeof TextDecoder !== 'undefined' ) {
  16854. return new TextDecoder().decode( array );
  16855. }
  16856. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16857. // throws a "maximum call stack size exceeded" error for large arrays.
  16858. let s = '';
  16859. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16860. // Implicitly assumes little-endian.
  16861. s += String.fromCharCode( array[ i ] );
  16862. }
  16863. try {
  16864. // merges multi-byte utf-8 characters.
  16865. return decodeURIComponent( escape( s ) );
  16866. } catch ( e ) { // see #16358
  16867. return s;
  16868. }
  16869. }
  16870. static extractUrlBase( url ) {
  16871. const index = url.lastIndexOf( '/' );
  16872. if ( index === - 1 ) return './';
  16873. return url.slice( 0, index + 1 );
  16874. }
  16875. static resolveURL( url, path ) {
  16876. // Invalid URL
  16877. if ( typeof url !== 'string' || url === '' ) return '';
  16878. // Host Relative URL
  16879. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16880. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16881. }
  16882. // Absolute URL http://,https://,//
  16883. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16884. // Data URI
  16885. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16886. // Blob URL
  16887. if ( /^blob:.*$/i.test( url ) ) return url;
  16888. // Relative URL
  16889. return path + url;
  16890. }
  16891. }
  16892. class InstancedBufferGeometry extends BufferGeometry {
  16893. constructor() {
  16894. super();
  16895. this.isInstancedBufferGeometry = true;
  16896. this.type = 'InstancedBufferGeometry';
  16897. this.instanceCount = Infinity;
  16898. }
  16899. copy( source ) {
  16900. super.copy( source );
  16901. this.instanceCount = source.instanceCount;
  16902. return this;
  16903. }
  16904. toJSON() {
  16905. const data = super.toJSON();
  16906. data.instanceCount = this.instanceCount;
  16907. data.isInstancedBufferGeometry = true;
  16908. return data;
  16909. }
  16910. }
  16911. class BufferGeometryLoader extends Loader {
  16912. constructor( manager ) {
  16913. super( manager );
  16914. }
  16915. load( url, onLoad, onProgress, onError ) {
  16916. const scope = this;
  16917. const loader = new FileLoader( scope.manager );
  16918. loader.setPath( scope.path );
  16919. loader.setRequestHeader( scope.requestHeader );
  16920. loader.setWithCredentials( scope.withCredentials );
  16921. loader.load( url, function ( text ) {
  16922. try {
  16923. onLoad( scope.parse( JSON.parse( text ) ) );
  16924. } catch ( e ) {
  16925. if ( onError ) {
  16926. onError( e );
  16927. } else {
  16928. console.error( e );
  16929. }
  16930. scope.manager.itemError( url );
  16931. }
  16932. }, onProgress, onError );
  16933. }
  16934. parse( json ) {
  16935. const interleavedBufferMap = {};
  16936. const arrayBufferMap = {};
  16937. function getInterleavedBuffer( json, uuid ) {
  16938. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16939. const interleavedBuffers = json.interleavedBuffers;
  16940. const interleavedBuffer = interleavedBuffers[ uuid ];
  16941. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16942. const array = getTypedArray( interleavedBuffer.type, buffer );
  16943. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16944. ib.uuid = interleavedBuffer.uuid;
  16945. interleavedBufferMap[ uuid ] = ib;
  16946. return ib;
  16947. }
  16948. function getArrayBuffer( json, uuid ) {
  16949. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  16950. const arrayBuffers = json.arrayBuffers;
  16951. const arrayBuffer = arrayBuffers[ uuid ];
  16952. const ab = new Uint32Array( arrayBuffer ).buffer;
  16953. arrayBufferMap[ uuid ] = ab;
  16954. return ab;
  16955. }
  16956. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  16957. const index = json.data.index;
  16958. if ( index !== undefined ) {
  16959. const typedArray = getTypedArray( index.type, index.array );
  16960. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16961. }
  16962. const attributes = json.data.attributes;
  16963. for ( const key in attributes ) {
  16964. const attribute = attributes[ key ];
  16965. let bufferAttribute;
  16966. if ( attribute.isInterleavedBufferAttribute ) {
  16967. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16968. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16969. } else {
  16970. const typedArray = getTypedArray( attribute.type, attribute.array );
  16971. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  16972. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  16973. }
  16974. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16975. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  16976. geometry.setAttribute( key, bufferAttribute );
  16977. }
  16978. const morphAttributes = json.data.morphAttributes;
  16979. if ( morphAttributes ) {
  16980. for ( const key in morphAttributes ) {
  16981. const attributeArray = morphAttributes[ key ];
  16982. const array = [];
  16983. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  16984. const attribute = attributeArray[ i ];
  16985. let bufferAttribute;
  16986. if ( attribute.isInterleavedBufferAttribute ) {
  16987. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16988. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16989. } else {
  16990. const typedArray = getTypedArray( attribute.type, attribute.array );
  16991. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  16992. }
  16993. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16994. array.push( bufferAttribute );
  16995. }
  16996. geometry.morphAttributes[ key ] = array;
  16997. }
  16998. }
  16999. const morphTargetsRelative = json.data.morphTargetsRelative;
  17000. if ( morphTargetsRelative ) {
  17001. geometry.morphTargetsRelative = true;
  17002. }
  17003. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17004. if ( groups !== undefined ) {
  17005. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17006. const group = groups[ i ];
  17007. geometry.addGroup( group.start, group.count, group.materialIndex );
  17008. }
  17009. }
  17010. const boundingSphere = json.data.boundingSphere;
  17011. if ( boundingSphere !== undefined ) {
  17012. const center = new Vector3();
  17013. if ( boundingSphere.center !== undefined ) {
  17014. center.fromArray( boundingSphere.center );
  17015. }
  17016. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17017. }
  17018. if ( json.name ) geometry.name = json.name;
  17019. if ( json.userData ) geometry.userData = json.userData;
  17020. return geometry;
  17021. }
  17022. }
  17023. class ObjectLoader extends Loader {
  17024. constructor( manager ) {
  17025. super( manager );
  17026. }
  17027. load( url, onLoad, onProgress, onError ) {
  17028. const scope = this;
  17029. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17030. this.resourcePath = this.resourcePath || path;
  17031. const loader = new FileLoader( this.manager );
  17032. loader.setPath( this.path );
  17033. loader.setRequestHeader( this.requestHeader );
  17034. loader.setWithCredentials( this.withCredentials );
  17035. loader.load( url, function ( text ) {
  17036. let json = null;
  17037. try {
  17038. json = JSON.parse( text );
  17039. } catch ( error ) {
  17040. if ( onError !== undefined ) onError( error );
  17041. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17042. return;
  17043. }
  17044. const metadata = json.metadata;
  17045. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17046. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17047. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17048. return;
  17049. }
  17050. scope.parse( json, onLoad );
  17051. }, onProgress, onError );
  17052. }
  17053. async loadAsync( url, onProgress ) {
  17054. const scope = this;
  17055. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17056. this.resourcePath = this.resourcePath || path;
  17057. const loader = new FileLoader( this.manager );
  17058. loader.setPath( this.path );
  17059. loader.setRequestHeader( this.requestHeader );
  17060. loader.setWithCredentials( this.withCredentials );
  17061. const text = await loader.loadAsync( url, onProgress );
  17062. const json = JSON.parse( text );
  17063. const metadata = json.metadata;
  17064. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17065. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17066. }
  17067. return await scope.parseAsync( json );
  17068. }
  17069. parse( json, onLoad ) {
  17070. const animations = this.parseAnimations( json.animations );
  17071. const shapes = this.parseShapes( json.shapes );
  17072. const geometries = this.parseGeometries( json.geometries, shapes );
  17073. const images = this.parseImages( json.images, function () {
  17074. if ( onLoad !== undefined ) onLoad( object );
  17075. } );
  17076. const textures = this.parseTextures( json.textures, images );
  17077. const materials = this.parseMaterials( json.materials, textures );
  17078. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17079. const skeletons = this.parseSkeletons( json.skeletons, object );
  17080. this.bindSkeletons( object, skeletons );
  17081. this.bindLightTargets( object );
  17082. //
  17083. if ( onLoad !== undefined ) {
  17084. let hasImages = false;
  17085. for ( const uuid in images ) {
  17086. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17087. hasImages = true;
  17088. break;
  17089. }
  17090. }
  17091. if ( hasImages === false ) onLoad( object );
  17092. }
  17093. return object;
  17094. }
  17095. async parseAsync( json ) {
  17096. const animations = this.parseAnimations( json.animations );
  17097. const shapes = this.parseShapes( json.shapes );
  17098. const geometries = this.parseGeometries( json.geometries, shapes );
  17099. const images = await this.parseImagesAsync( json.images );
  17100. const textures = this.parseTextures( json.textures, images );
  17101. const materials = this.parseMaterials( json.materials, textures );
  17102. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17103. const skeletons = this.parseSkeletons( json.skeletons, object );
  17104. this.bindSkeletons( object, skeletons );
  17105. this.bindLightTargets( object );
  17106. return object;
  17107. }
  17108. parseShapes( json ) {
  17109. const shapes = {};
  17110. if ( json !== undefined ) {
  17111. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17112. const shape = new Shape().fromJSON( json[ i ] );
  17113. shapes[ shape.uuid ] = shape;
  17114. }
  17115. }
  17116. return shapes;
  17117. }
  17118. parseSkeletons( json, object ) {
  17119. const skeletons = {};
  17120. const bones = {};
  17121. // generate bone lookup table
  17122. object.traverse( function ( child ) {
  17123. if ( child.isBone ) bones[ child.uuid ] = child;
  17124. } );
  17125. // create skeletons
  17126. if ( json !== undefined ) {
  17127. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17128. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17129. skeletons[ skeleton.uuid ] = skeleton;
  17130. }
  17131. }
  17132. return skeletons;
  17133. }
  17134. parseGeometries( json, shapes ) {
  17135. const geometries = {};
  17136. if ( json !== undefined ) {
  17137. const bufferGeometryLoader = new BufferGeometryLoader();
  17138. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17139. let geometry;
  17140. const data = json[ i ];
  17141. switch ( data.type ) {
  17142. case 'BufferGeometry':
  17143. case 'InstancedBufferGeometry':
  17144. geometry = bufferGeometryLoader.parse( data );
  17145. break;
  17146. default:
  17147. if ( data.type in Geometries$1 ) {
  17148. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17149. } else {
  17150. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17151. }
  17152. }
  17153. geometry.uuid = data.uuid;
  17154. if ( data.name !== undefined ) geometry.name = data.name;
  17155. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17156. geometries[ data.uuid ] = geometry;
  17157. }
  17158. }
  17159. return geometries;
  17160. }
  17161. parseMaterials( json, textures ) {
  17162. const cache = {}; // MultiMaterial
  17163. const materials = {};
  17164. if ( json !== undefined ) {
  17165. const loader = new MaterialLoader();
  17166. loader.setTextures( textures );
  17167. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17168. const data = json[ i ];
  17169. if ( cache[ data.uuid ] === undefined ) {
  17170. cache[ data.uuid ] = loader.parse( data );
  17171. }
  17172. materials[ data.uuid ] = cache[ data.uuid ];
  17173. }
  17174. }
  17175. return materials;
  17176. }
  17177. parseAnimations( json ) {
  17178. const animations = {};
  17179. if ( json !== undefined ) {
  17180. for ( let i = 0; i < json.length; i ++ ) {
  17181. const data = json[ i ];
  17182. const clip = AnimationClip.parse( data );
  17183. animations[ clip.uuid ] = clip;
  17184. }
  17185. }
  17186. return animations;
  17187. }
  17188. parseImages( json, onLoad ) {
  17189. const scope = this;
  17190. const images = {};
  17191. let loader;
  17192. function loadImage( url ) {
  17193. scope.manager.itemStart( url );
  17194. return loader.load( url, function () {
  17195. scope.manager.itemEnd( url );
  17196. }, undefined, function () {
  17197. scope.manager.itemError( url );
  17198. scope.manager.itemEnd( url );
  17199. } );
  17200. }
  17201. function deserializeImage( image ) {
  17202. if ( typeof image === 'string' ) {
  17203. const url = image;
  17204. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17205. return loadImage( path );
  17206. } else {
  17207. if ( image.data ) {
  17208. return {
  17209. data: getTypedArray( image.type, image.data ),
  17210. width: image.width,
  17211. height: image.height
  17212. };
  17213. } else {
  17214. return null;
  17215. }
  17216. }
  17217. }
  17218. if ( json !== undefined && json.length > 0 ) {
  17219. const manager = new LoadingManager( onLoad );
  17220. loader = new ImageLoader( manager );
  17221. loader.setCrossOrigin( this.crossOrigin );
  17222. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17223. const image = json[ i ];
  17224. const url = image.url;
  17225. if ( Array.isArray( url ) ) {
  17226. // load array of images e.g CubeTexture
  17227. const imageArray = [];
  17228. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17229. const currentUrl = url[ j ];
  17230. const deserializedImage = deserializeImage( currentUrl );
  17231. if ( deserializedImage !== null ) {
  17232. if ( deserializedImage instanceof HTMLImageElement ) {
  17233. imageArray.push( deserializedImage );
  17234. } else {
  17235. // special case: handle array of data textures for cube textures
  17236. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17237. }
  17238. }
  17239. }
  17240. images[ image.uuid ] = new Source( imageArray );
  17241. } else {
  17242. // load single image
  17243. const deserializedImage = deserializeImage( image.url );
  17244. images[ image.uuid ] = new Source( deserializedImage );
  17245. }
  17246. }
  17247. }
  17248. return images;
  17249. }
  17250. async parseImagesAsync( json ) {
  17251. const scope = this;
  17252. const images = {};
  17253. let loader;
  17254. async function deserializeImage( image ) {
  17255. if ( typeof image === 'string' ) {
  17256. const url = image;
  17257. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17258. return await loader.loadAsync( path );
  17259. } else {
  17260. if ( image.data ) {
  17261. return {
  17262. data: getTypedArray( image.type, image.data ),
  17263. width: image.width,
  17264. height: image.height
  17265. };
  17266. } else {
  17267. return null;
  17268. }
  17269. }
  17270. }
  17271. if ( json !== undefined && json.length > 0 ) {
  17272. loader = new ImageLoader( this.manager );
  17273. loader.setCrossOrigin( this.crossOrigin );
  17274. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17275. const image = json[ i ];
  17276. const url = image.url;
  17277. if ( Array.isArray( url ) ) {
  17278. // load array of images e.g CubeTexture
  17279. const imageArray = [];
  17280. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17281. const currentUrl = url[ j ];
  17282. const deserializedImage = await deserializeImage( currentUrl );
  17283. if ( deserializedImage !== null ) {
  17284. if ( deserializedImage instanceof HTMLImageElement ) {
  17285. imageArray.push( deserializedImage );
  17286. } else {
  17287. // special case: handle array of data textures for cube textures
  17288. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17289. }
  17290. }
  17291. }
  17292. images[ image.uuid ] = new Source( imageArray );
  17293. } else {
  17294. // load single image
  17295. const deserializedImage = await deserializeImage( image.url );
  17296. images[ image.uuid ] = new Source( deserializedImage );
  17297. }
  17298. }
  17299. }
  17300. return images;
  17301. }
  17302. parseTextures( json, images ) {
  17303. function parseConstant( value, type ) {
  17304. if ( typeof value === 'number' ) return value;
  17305. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17306. return type[ value ];
  17307. }
  17308. const textures = {};
  17309. if ( json !== undefined ) {
  17310. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17311. const data = json[ i ];
  17312. if ( data.image === undefined ) {
  17313. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17314. }
  17315. if ( images[ data.image ] === undefined ) {
  17316. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17317. }
  17318. const source = images[ data.image ];
  17319. const image = source.data;
  17320. let texture;
  17321. if ( Array.isArray( image ) ) {
  17322. texture = new CubeTexture();
  17323. if ( image.length === 6 ) texture.needsUpdate = true;
  17324. } else {
  17325. if ( image && image.data ) {
  17326. texture = new DataTexture();
  17327. } else {
  17328. texture = new Texture();
  17329. }
  17330. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17331. }
  17332. texture.source = source;
  17333. texture.uuid = data.uuid;
  17334. if ( data.name !== undefined ) texture.name = data.name;
  17335. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17336. if ( data.channel !== undefined ) texture.channel = data.channel;
  17337. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17338. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17339. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17340. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17341. if ( data.wrap !== undefined ) {
  17342. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17343. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17344. }
  17345. if ( data.format !== undefined ) texture.format = data.format;
  17346. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17347. if ( data.type !== undefined ) texture.type = data.type;
  17348. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17349. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17350. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17351. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17352. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17353. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17354. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17355. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17356. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17357. if ( data.userData !== undefined ) texture.userData = data.userData;
  17358. textures[ data.uuid ] = texture;
  17359. }
  17360. }
  17361. return textures;
  17362. }
  17363. parseObject( data, geometries, materials, textures, animations ) {
  17364. let object;
  17365. function getGeometry( name ) {
  17366. if ( geometries[ name ] === undefined ) {
  17367. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17368. }
  17369. return geometries[ name ];
  17370. }
  17371. function getMaterial( name ) {
  17372. if ( name === undefined ) return undefined;
  17373. if ( Array.isArray( name ) ) {
  17374. const array = [];
  17375. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17376. const uuid = name[ i ];
  17377. if ( materials[ uuid ] === undefined ) {
  17378. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17379. }
  17380. array.push( materials[ uuid ] );
  17381. }
  17382. return array;
  17383. }
  17384. if ( materials[ name ] === undefined ) {
  17385. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17386. }
  17387. return materials[ name ];
  17388. }
  17389. function getTexture( uuid ) {
  17390. if ( textures[ uuid ] === undefined ) {
  17391. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17392. }
  17393. return textures[ uuid ];
  17394. }
  17395. let geometry, material;
  17396. switch ( data.type ) {
  17397. case 'Scene':
  17398. object = new Scene();
  17399. if ( data.background !== undefined ) {
  17400. if ( Number.isInteger( data.background ) ) {
  17401. object.background = new Color( data.background );
  17402. } else {
  17403. object.background = getTexture( data.background );
  17404. }
  17405. }
  17406. if ( data.environment !== undefined ) {
  17407. object.environment = getTexture( data.environment );
  17408. }
  17409. if ( data.fog !== undefined ) {
  17410. if ( data.fog.type === 'Fog' ) {
  17411. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17412. } else if ( data.fog.type === 'FogExp2' ) {
  17413. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17414. }
  17415. if ( data.fog.name !== '' ) {
  17416. object.fog.name = data.fog.name;
  17417. }
  17418. }
  17419. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17420. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17421. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17422. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17423. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17424. break;
  17425. case 'PerspectiveCamera':
  17426. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17427. if ( data.focus !== undefined ) object.focus = data.focus;
  17428. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17429. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17430. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17431. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17432. break;
  17433. case 'OrthographicCamera':
  17434. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17435. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17436. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17437. break;
  17438. case 'AmbientLight':
  17439. object = new AmbientLight( data.color, data.intensity );
  17440. break;
  17441. case 'DirectionalLight':
  17442. object = new DirectionalLight( data.color, data.intensity );
  17443. object.target = data.target || '';
  17444. break;
  17445. case 'PointLight':
  17446. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17447. break;
  17448. case 'RectAreaLight':
  17449. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17450. break;
  17451. case 'SpotLight':
  17452. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17453. object.target = data.target || '';
  17454. break;
  17455. case 'HemisphereLight':
  17456. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17457. break;
  17458. case 'LightProbe':
  17459. object = new LightProbe().fromJSON( data );
  17460. break;
  17461. case 'SkinnedMesh':
  17462. geometry = getGeometry( data.geometry );
  17463. material = getMaterial( data.material );
  17464. object = new SkinnedMesh( geometry, material );
  17465. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17466. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17467. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17468. break;
  17469. case 'Mesh':
  17470. geometry = getGeometry( data.geometry );
  17471. material = getMaterial( data.material );
  17472. object = new Mesh( geometry, material );
  17473. break;
  17474. case 'InstancedMesh':
  17475. geometry = getGeometry( data.geometry );
  17476. material = getMaterial( data.material );
  17477. const count = data.count;
  17478. const instanceMatrix = data.instanceMatrix;
  17479. const instanceColor = data.instanceColor;
  17480. object = new InstancedMesh( geometry, material, count );
  17481. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17482. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17483. break;
  17484. case 'BatchedMesh':
  17485. geometry = getGeometry( data.geometry );
  17486. material = getMaterial( data.material );
  17487. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17488. object.geometry = geometry;
  17489. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17490. object.sortObjects = data.sortObjects;
  17491. object._drawRanges = data.drawRanges;
  17492. object._reservedRanges = data.reservedRanges;
  17493. object._visibility = data.visibility;
  17494. object._active = data.active;
  17495. object._bounds = data.bounds.map( bound => {
  17496. const box = new Box3();
  17497. box.min.fromArray( bound.boxMin );
  17498. box.max.fromArray( bound.boxMax );
  17499. const sphere = new Sphere();
  17500. sphere.radius = bound.sphereRadius;
  17501. sphere.center.fromArray( bound.sphereCenter );
  17502. return {
  17503. boxInitialized: bound.boxInitialized,
  17504. box: box,
  17505. sphereInitialized: bound.sphereInitialized,
  17506. sphere: sphere
  17507. };
  17508. } );
  17509. object._maxInstanceCount = data.maxInstanceCount;
  17510. object._maxVertexCount = data.maxVertexCount;
  17511. object._maxIndexCount = data.maxIndexCount;
  17512. object._geometryInitialized = data.geometryInitialized;
  17513. object._geometryCount = data.geometryCount;
  17514. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17515. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17516. break;
  17517. case 'LOD':
  17518. object = new LOD();
  17519. break;
  17520. case 'Line':
  17521. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17522. break;
  17523. case 'LineLoop':
  17524. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17525. break;
  17526. case 'LineSegments':
  17527. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17528. break;
  17529. case 'PointCloud':
  17530. case 'Points':
  17531. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17532. break;
  17533. case 'Sprite':
  17534. object = new Sprite( getMaterial( data.material ) );
  17535. break;
  17536. case 'Group':
  17537. object = new Group();
  17538. break;
  17539. case 'Bone':
  17540. object = new Bone();
  17541. break;
  17542. default:
  17543. object = new Object3D();
  17544. }
  17545. object.uuid = data.uuid;
  17546. if ( data.name !== undefined ) object.name = data.name;
  17547. if ( data.matrix !== undefined ) {
  17548. object.matrix.fromArray( data.matrix );
  17549. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17550. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17551. } else {
  17552. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17553. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17554. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17555. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17556. }
  17557. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17558. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17559. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17560. if ( data.shadow ) {
  17561. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17562. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17563. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17564. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17565. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17566. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17567. }
  17568. if ( data.visible !== undefined ) object.visible = data.visible;
  17569. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17570. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17571. if ( data.userData !== undefined ) object.userData = data.userData;
  17572. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17573. if ( data.children !== undefined ) {
  17574. const children = data.children;
  17575. for ( let i = 0; i < children.length; i ++ ) {
  17576. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17577. }
  17578. }
  17579. if ( data.animations !== undefined ) {
  17580. const objectAnimations = data.animations;
  17581. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17582. const uuid = objectAnimations[ i ];
  17583. object.animations.push( animations[ uuid ] );
  17584. }
  17585. }
  17586. if ( data.type === 'LOD' ) {
  17587. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17588. const levels = data.levels;
  17589. for ( let l = 0; l < levels.length; l ++ ) {
  17590. const level = levels[ l ];
  17591. const child = object.getObjectByProperty( 'uuid', level.object );
  17592. if ( child !== undefined ) {
  17593. object.addLevel( child, level.distance, level.hysteresis );
  17594. }
  17595. }
  17596. }
  17597. return object;
  17598. }
  17599. bindSkeletons( object, skeletons ) {
  17600. if ( Object.keys( skeletons ).length === 0 ) return;
  17601. object.traverse( function ( child ) {
  17602. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17603. const skeleton = skeletons[ child.skeleton ];
  17604. if ( skeleton === undefined ) {
  17605. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17606. } else {
  17607. child.bind( skeleton, child.bindMatrix );
  17608. }
  17609. }
  17610. } );
  17611. }
  17612. bindLightTargets( object ) {
  17613. object.traverse( function ( child ) {
  17614. if ( child.isDirectionalLight || child.isSpotLight ) {
  17615. const uuid = child.target;
  17616. const target = object.getObjectByProperty( 'uuid', uuid );
  17617. if ( target !== undefined ) {
  17618. child.target = target;
  17619. } else {
  17620. child.target = new Object3D();
  17621. }
  17622. }
  17623. } );
  17624. }
  17625. }
  17626. const TEXTURE_MAPPING = {
  17627. UVMapping: UVMapping,
  17628. CubeReflectionMapping: CubeReflectionMapping,
  17629. CubeRefractionMapping: CubeRefractionMapping,
  17630. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17631. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17632. CubeUVReflectionMapping: CubeUVReflectionMapping
  17633. };
  17634. const TEXTURE_WRAPPING = {
  17635. RepeatWrapping: RepeatWrapping,
  17636. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17637. MirroredRepeatWrapping: MirroredRepeatWrapping
  17638. };
  17639. const TEXTURE_FILTER = {
  17640. NearestFilter: NearestFilter,
  17641. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17642. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17643. LinearFilter: LinearFilter,
  17644. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17645. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17646. };
  17647. class ImageBitmapLoader extends Loader {
  17648. constructor( manager ) {
  17649. super( manager );
  17650. this.isImageBitmapLoader = true;
  17651. if ( typeof createImageBitmap === 'undefined' ) {
  17652. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17653. }
  17654. if ( typeof fetch === 'undefined' ) {
  17655. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17656. }
  17657. this.options = { premultiplyAlpha: 'none' };
  17658. }
  17659. setOptions( options ) {
  17660. this.options = options;
  17661. return this;
  17662. }
  17663. load( url, onLoad, onProgress, onError ) {
  17664. if ( url === undefined ) url = '';
  17665. if ( this.path !== undefined ) url = this.path + url;
  17666. url = this.manager.resolveURL( url );
  17667. const scope = this;
  17668. const cached = Cache.get( url );
  17669. if ( cached !== undefined ) {
  17670. scope.manager.itemStart( url );
  17671. // If cached is a promise, wait for it to resolve
  17672. if ( cached.then ) {
  17673. cached.then( imageBitmap => {
  17674. if ( onLoad ) onLoad( imageBitmap );
  17675. scope.manager.itemEnd( url );
  17676. } ).catch( e => {
  17677. if ( onError ) onError( e );
  17678. } );
  17679. return;
  17680. }
  17681. // If cached is not a promise (i.e., it's already an imageBitmap)
  17682. setTimeout( function () {
  17683. if ( onLoad ) onLoad( cached );
  17684. scope.manager.itemEnd( url );
  17685. }, 0 );
  17686. return cached;
  17687. }
  17688. const fetchOptions = {};
  17689. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17690. fetchOptions.headers = this.requestHeader;
  17691. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17692. return res.blob();
  17693. } ).then( function ( blob ) {
  17694. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17695. } ).then( function ( imageBitmap ) {
  17696. Cache.add( url, imageBitmap );
  17697. if ( onLoad ) onLoad( imageBitmap );
  17698. scope.manager.itemEnd( url );
  17699. return imageBitmap;
  17700. } ).catch( function ( e ) {
  17701. if ( onError ) onError( e );
  17702. Cache.remove( url );
  17703. scope.manager.itemError( url );
  17704. scope.manager.itemEnd( url );
  17705. } );
  17706. Cache.add( url, promise );
  17707. scope.manager.itemStart( url );
  17708. }
  17709. }
  17710. let _context;
  17711. class AudioContext {
  17712. static getContext() {
  17713. if ( _context === undefined ) {
  17714. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17715. }
  17716. return _context;
  17717. }
  17718. static setContext( value ) {
  17719. _context = value;
  17720. }
  17721. }
  17722. class AudioLoader extends Loader {
  17723. constructor( manager ) {
  17724. super( manager );
  17725. }
  17726. load( url, onLoad, onProgress, onError ) {
  17727. const scope = this;
  17728. const loader = new FileLoader( this.manager );
  17729. loader.setResponseType( 'arraybuffer' );
  17730. loader.setPath( this.path );
  17731. loader.setRequestHeader( this.requestHeader );
  17732. loader.setWithCredentials( this.withCredentials );
  17733. loader.load( url, function ( buffer ) {
  17734. try {
  17735. // Create a copy of the buffer. The `decodeAudioData` method
  17736. // detaches the buffer when complete, preventing reuse.
  17737. const bufferCopy = buffer.slice( 0 );
  17738. const context = AudioContext.getContext();
  17739. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17740. onLoad( audioBuffer );
  17741. } ).catch( handleError );
  17742. } catch ( e ) {
  17743. handleError( e );
  17744. }
  17745. }, onProgress, onError );
  17746. function handleError( e ) {
  17747. if ( onError ) {
  17748. onError( e );
  17749. } else {
  17750. console.error( e );
  17751. }
  17752. scope.manager.itemError( url );
  17753. }
  17754. }
  17755. }
  17756. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17757. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17758. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17759. class StereoCamera {
  17760. constructor() {
  17761. this.type = 'StereoCamera';
  17762. this.aspect = 1;
  17763. this.eyeSep = 0.064;
  17764. this.cameraL = new PerspectiveCamera();
  17765. this.cameraL.layers.enable( 1 );
  17766. this.cameraL.matrixAutoUpdate = false;
  17767. this.cameraR = new PerspectiveCamera();
  17768. this.cameraR.layers.enable( 2 );
  17769. this.cameraR.matrixAutoUpdate = false;
  17770. this._cache = {
  17771. focus: null,
  17772. fov: null,
  17773. aspect: null,
  17774. near: null,
  17775. far: null,
  17776. zoom: null,
  17777. eyeSep: null
  17778. };
  17779. }
  17780. update( camera ) {
  17781. const cache = this._cache;
  17782. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17783. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17784. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17785. if ( needsUpdate ) {
  17786. cache.focus = camera.focus;
  17787. cache.fov = camera.fov;
  17788. cache.aspect = camera.aspect * this.aspect;
  17789. cache.near = camera.near;
  17790. cache.far = camera.far;
  17791. cache.zoom = camera.zoom;
  17792. cache.eyeSep = this.eyeSep;
  17793. // Off-axis stereoscopic effect based on
  17794. // http://paulbourke.net/stereographics/stereorender/
  17795. _projectionMatrix.copy( camera.projectionMatrix );
  17796. const eyeSepHalf = cache.eyeSep / 2;
  17797. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17798. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17799. let xmin, xmax;
  17800. // translate xOffset
  17801. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17802. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17803. // for left eye
  17804. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17805. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17806. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17807. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17808. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17809. // for right eye
  17810. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17811. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17812. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17813. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17814. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17815. }
  17816. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17817. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17818. }
  17819. }
  17820. class ArrayCamera extends PerspectiveCamera {
  17821. constructor( array = [] ) {
  17822. super();
  17823. this.isArrayCamera = true;
  17824. this.cameras = array;
  17825. }
  17826. }
  17827. class Clock {
  17828. constructor( autoStart = true ) {
  17829. this.autoStart = autoStart;
  17830. this.startTime = 0;
  17831. this.oldTime = 0;
  17832. this.elapsedTime = 0;
  17833. this.running = false;
  17834. }
  17835. start() {
  17836. this.startTime = now();
  17837. this.oldTime = this.startTime;
  17838. this.elapsedTime = 0;
  17839. this.running = true;
  17840. }
  17841. stop() {
  17842. this.getElapsedTime();
  17843. this.running = false;
  17844. this.autoStart = false;
  17845. }
  17846. getElapsedTime() {
  17847. this.getDelta();
  17848. return this.elapsedTime;
  17849. }
  17850. getDelta() {
  17851. let diff = 0;
  17852. if ( this.autoStart && ! this.running ) {
  17853. this.start();
  17854. return 0;
  17855. }
  17856. if ( this.running ) {
  17857. const newTime = now();
  17858. diff = ( newTime - this.oldTime ) / 1000;
  17859. this.oldTime = newTime;
  17860. this.elapsedTime += diff;
  17861. }
  17862. return diff;
  17863. }
  17864. }
  17865. function now() {
  17866. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  17867. }
  17868. const _position$1 = /*@__PURE__*/ new Vector3();
  17869. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17870. const _scale$1 = /*@__PURE__*/ new Vector3();
  17871. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17872. class AudioListener extends Object3D {
  17873. constructor() {
  17874. super();
  17875. this.type = 'AudioListener';
  17876. this.context = AudioContext.getContext();
  17877. this.gain = this.context.createGain();
  17878. this.gain.connect( this.context.destination );
  17879. this.filter = null;
  17880. this.timeDelta = 0;
  17881. // private
  17882. this._clock = new Clock();
  17883. }
  17884. getInput() {
  17885. return this.gain;
  17886. }
  17887. removeFilter() {
  17888. if ( this.filter !== null ) {
  17889. this.gain.disconnect( this.filter );
  17890. this.filter.disconnect( this.context.destination );
  17891. this.gain.connect( this.context.destination );
  17892. this.filter = null;
  17893. }
  17894. return this;
  17895. }
  17896. getFilter() {
  17897. return this.filter;
  17898. }
  17899. setFilter( value ) {
  17900. if ( this.filter !== null ) {
  17901. this.gain.disconnect( this.filter );
  17902. this.filter.disconnect( this.context.destination );
  17903. } else {
  17904. this.gain.disconnect( this.context.destination );
  17905. }
  17906. this.filter = value;
  17907. this.gain.connect( this.filter );
  17908. this.filter.connect( this.context.destination );
  17909. return this;
  17910. }
  17911. getMasterVolume() {
  17912. return this.gain.gain.value;
  17913. }
  17914. setMasterVolume( value ) {
  17915. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17916. return this;
  17917. }
  17918. updateMatrixWorld( force ) {
  17919. super.updateMatrixWorld( force );
  17920. const listener = this.context.listener;
  17921. const up = this.up;
  17922. this.timeDelta = this._clock.getDelta();
  17923. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17924. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17925. if ( listener.positionX ) {
  17926. // code path for Chrome (see #14393)
  17927. const endTime = this.context.currentTime + this.timeDelta;
  17928. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17929. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17930. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17931. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17932. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17933. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17934. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17935. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17936. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17937. } else {
  17938. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17939. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17940. }
  17941. }
  17942. }
  17943. class Audio extends Object3D {
  17944. constructor( listener ) {
  17945. super();
  17946. this.type = 'Audio';
  17947. this.listener = listener;
  17948. this.context = listener.context;
  17949. this.gain = this.context.createGain();
  17950. this.gain.connect( listener.getInput() );
  17951. this.autoplay = false;
  17952. this.buffer = null;
  17953. this.detune = 0;
  17954. this.loop = false;
  17955. this.loopStart = 0;
  17956. this.loopEnd = 0;
  17957. this.offset = 0;
  17958. this.duration = undefined;
  17959. this.playbackRate = 1;
  17960. this.isPlaying = false;
  17961. this.hasPlaybackControl = true;
  17962. this.source = null;
  17963. this.sourceType = 'empty';
  17964. this._startedAt = 0;
  17965. this._progress = 0;
  17966. this._connected = false;
  17967. this.filters = [];
  17968. }
  17969. getOutput() {
  17970. return this.gain;
  17971. }
  17972. setNodeSource( audioNode ) {
  17973. this.hasPlaybackControl = false;
  17974. this.sourceType = 'audioNode';
  17975. this.source = audioNode;
  17976. this.connect();
  17977. return this;
  17978. }
  17979. setMediaElementSource( mediaElement ) {
  17980. this.hasPlaybackControl = false;
  17981. this.sourceType = 'mediaNode';
  17982. this.source = this.context.createMediaElementSource( mediaElement );
  17983. this.connect();
  17984. return this;
  17985. }
  17986. setMediaStreamSource( mediaStream ) {
  17987. this.hasPlaybackControl = false;
  17988. this.sourceType = 'mediaStreamNode';
  17989. this.source = this.context.createMediaStreamSource( mediaStream );
  17990. this.connect();
  17991. return this;
  17992. }
  17993. setBuffer( audioBuffer ) {
  17994. this.buffer = audioBuffer;
  17995. this.sourceType = 'buffer';
  17996. if ( this.autoplay ) this.play();
  17997. return this;
  17998. }
  17999. play( delay = 0 ) {
  18000. if ( this.isPlaying === true ) {
  18001. console.warn( 'THREE.Audio: Audio is already playing.' );
  18002. return;
  18003. }
  18004. if ( this.hasPlaybackControl === false ) {
  18005. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18006. return;
  18007. }
  18008. this._startedAt = this.context.currentTime + delay;
  18009. const source = this.context.createBufferSource();
  18010. source.buffer = this.buffer;
  18011. source.loop = this.loop;
  18012. source.loopStart = this.loopStart;
  18013. source.loopEnd = this.loopEnd;
  18014. source.onended = this.onEnded.bind( this );
  18015. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18016. this.isPlaying = true;
  18017. this.source = source;
  18018. this.setDetune( this.detune );
  18019. this.setPlaybackRate( this.playbackRate );
  18020. return this.connect();
  18021. }
  18022. pause() {
  18023. if ( this.hasPlaybackControl === false ) {
  18024. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18025. return;
  18026. }
  18027. if ( this.isPlaying === true ) {
  18028. // update current progress
  18029. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18030. if ( this.loop === true ) {
  18031. // ensure _progress does not exceed duration with looped audios
  18032. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18033. }
  18034. this.source.stop();
  18035. this.source.onended = null;
  18036. this.isPlaying = false;
  18037. }
  18038. return this;
  18039. }
  18040. stop() {
  18041. if ( this.hasPlaybackControl === false ) {
  18042. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18043. return;
  18044. }
  18045. this._progress = 0;
  18046. if ( this.source !== null ) {
  18047. this.source.stop();
  18048. this.source.onended = null;
  18049. }
  18050. this.isPlaying = false;
  18051. return this;
  18052. }
  18053. connect() {
  18054. if ( this.filters.length > 0 ) {
  18055. this.source.connect( this.filters[ 0 ] );
  18056. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18057. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18058. }
  18059. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18060. } else {
  18061. this.source.connect( this.getOutput() );
  18062. }
  18063. this._connected = true;
  18064. return this;
  18065. }
  18066. disconnect() {
  18067. if ( this._connected === false ) {
  18068. return;
  18069. }
  18070. if ( this.filters.length > 0 ) {
  18071. this.source.disconnect( this.filters[ 0 ] );
  18072. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18073. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18074. }
  18075. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18076. } else {
  18077. this.source.disconnect( this.getOutput() );
  18078. }
  18079. this._connected = false;
  18080. return this;
  18081. }
  18082. getFilters() {
  18083. return this.filters;
  18084. }
  18085. setFilters( value ) {
  18086. if ( ! value ) value = [];
  18087. if ( this._connected === true ) {
  18088. this.disconnect();
  18089. this.filters = value.slice();
  18090. this.connect();
  18091. } else {
  18092. this.filters = value.slice();
  18093. }
  18094. return this;
  18095. }
  18096. setDetune( value ) {
  18097. this.detune = value;
  18098. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18099. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18100. }
  18101. return this;
  18102. }
  18103. getDetune() {
  18104. return this.detune;
  18105. }
  18106. getFilter() {
  18107. return this.getFilters()[ 0 ];
  18108. }
  18109. setFilter( filter ) {
  18110. return this.setFilters( filter ? [ filter ] : [] );
  18111. }
  18112. setPlaybackRate( value ) {
  18113. if ( this.hasPlaybackControl === false ) {
  18114. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18115. return;
  18116. }
  18117. this.playbackRate = value;
  18118. if ( this.isPlaying === true ) {
  18119. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18120. }
  18121. return this;
  18122. }
  18123. getPlaybackRate() {
  18124. return this.playbackRate;
  18125. }
  18126. onEnded() {
  18127. this.isPlaying = false;
  18128. }
  18129. getLoop() {
  18130. if ( this.hasPlaybackControl === false ) {
  18131. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18132. return false;
  18133. }
  18134. return this.loop;
  18135. }
  18136. setLoop( value ) {
  18137. if ( this.hasPlaybackControl === false ) {
  18138. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18139. return;
  18140. }
  18141. this.loop = value;
  18142. if ( this.isPlaying === true ) {
  18143. this.source.loop = this.loop;
  18144. }
  18145. return this;
  18146. }
  18147. setLoopStart( value ) {
  18148. this.loopStart = value;
  18149. return this;
  18150. }
  18151. setLoopEnd( value ) {
  18152. this.loopEnd = value;
  18153. return this;
  18154. }
  18155. getVolume() {
  18156. return this.gain.gain.value;
  18157. }
  18158. setVolume( value ) {
  18159. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18160. return this;
  18161. }
  18162. }
  18163. const _position = /*@__PURE__*/ new Vector3();
  18164. const _quaternion = /*@__PURE__*/ new Quaternion();
  18165. const _scale = /*@__PURE__*/ new Vector3();
  18166. const _orientation = /*@__PURE__*/ new Vector3();
  18167. class PositionalAudio extends Audio {
  18168. constructor( listener ) {
  18169. super( listener );
  18170. this.panner = this.context.createPanner();
  18171. this.panner.panningModel = 'HRTF';
  18172. this.panner.connect( this.gain );
  18173. }
  18174. connect() {
  18175. super.connect();
  18176. this.panner.connect( this.gain );
  18177. }
  18178. disconnect() {
  18179. super.disconnect();
  18180. this.panner.disconnect( this.gain );
  18181. }
  18182. getOutput() {
  18183. return this.panner;
  18184. }
  18185. getRefDistance() {
  18186. return this.panner.refDistance;
  18187. }
  18188. setRefDistance( value ) {
  18189. this.panner.refDistance = value;
  18190. return this;
  18191. }
  18192. getRolloffFactor() {
  18193. return this.panner.rolloffFactor;
  18194. }
  18195. setRolloffFactor( value ) {
  18196. this.panner.rolloffFactor = value;
  18197. return this;
  18198. }
  18199. getDistanceModel() {
  18200. return this.panner.distanceModel;
  18201. }
  18202. setDistanceModel( value ) {
  18203. this.panner.distanceModel = value;
  18204. return this;
  18205. }
  18206. getMaxDistance() {
  18207. return this.panner.maxDistance;
  18208. }
  18209. setMaxDistance( value ) {
  18210. this.panner.maxDistance = value;
  18211. return this;
  18212. }
  18213. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18214. this.panner.coneInnerAngle = coneInnerAngle;
  18215. this.panner.coneOuterAngle = coneOuterAngle;
  18216. this.panner.coneOuterGain = coneOuterGain;
  18217. return this;
  18218. }
  18219. updateMatrixWorld( force ) {
  18220. super.updateMatrixWorld( force );
  18221. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18222. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18223. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18224. const panner = this.panner;
  18225. if ( panner.positionX ) {
  18226. // code path for Chrome and Firefox (see #14393)
  18227. const endTime = this.context.currentTime + this.listener.timeDelta;
  18228. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18229. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18230. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18231. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18232. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18233. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18234. } else {
  18235. panner.setPosition( _position.x, _position.y, _position.z );
  18236. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18237. }
  18238. }
  18239. }
  18240. class AudioAnalyser {
  18241. constructor( audio, fftSize = 2048 ) {
  18242. this.analyser = audio.context.createAnalyser();
  18243. this.analyser.fftSize = fftSize;
  18244. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18245. audio.getOutput().connect( this.analyser );
  18246. }
  18247. getFrequencyData() {
  18248. this.analyser.getByteFrequencyData( this.data );
  18249. return this.data;
  18250. }
  18251. getAverageFrequency() {
  18252. let value = 0;
  18253. const data = this.getFrequencyData();
  18254. for ( let i = 0; i < data.length; i ++ ) {
  18255. value += data[ i ];
  18256. }
  18257. return value / data.length;
  18258. }
  18259. }
  18260. class PropertyMixer {
  18261. constructor( binding, typeName, valueSize ) {
  18262. this.binding = binding;
  18263. this.valueSize = valueSize;
  18264. let mixFunction,
  18265. mixFunctionAdditive,
  18266. setIdentity;
  18267. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18268. //
  18269. // interpolators can use .buffer as their .result
  18270. // the data then goes to 'incoming'
  18271. //
  18272. // 'accu0' and 'accu1' are used frame-interleaved for
  18273. // the cumulative result and are compared to detect
  18274. // changes
  18275. //
  18276. // 'orig' stores the original state of the property
  18277. //
  18278. // 'add' is used for additive cumulative results
  18279. //
  18280. // 'work' is optional and is only present for quaternion types. It is used
  18281. // to store intermediate quaternion multiplication results
  18282. switch ( typeName ) {
  18283. case 'quaternion':
  18284. mixFunction = this._slerp;
  18285. mixFunctionAdditive = this._slerpAdditive;
  18286. setIdentity = this._setAdditiveIdentityQuaternion;
  18287. this.buffer = new Float64Array( valueSize * 6 );
  18288. this._workIndex = 5;
  18289. break;
  18290. case 'string':
  18291. case 'bool':
  18292. mixFunction = this._select;
  18293. // Use the regular mix function and for additive on these types,
  18294. // additive is not relevant for non-numeric types
  18295. mixFunctionAdditive = this._select;
  18296. setIdentity = this._setAdditiveIdentityOther;
  18297. this.buffer = new Array( valueSize * 5 );
  18298. break;
  18299. default:
  18300. mixFunction = this._lerp;
  18301. mixFunctionAdditive = this._lerpAdditive;
  18302. setIdentity = this._setAdditiveIdentityNumeric;
  18303. this.buffer = new Float64Array( valueSize * 5 );
  18304. }
  18305. this._mixBufferRegion = mixFunction;
  18306. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18307. this._setIdentity = setIdentity;
  18308. this._origIndex = 3;
  18309. this._addIndex = 4;
  18310. this.cumulativeWeight = 0;
  18311. this.cumulativeWeightAdditive = 0;
  18312. this.useCount = 0;
  18313. this.referenceCount = 0;
  18314. }
  18315. // accumulate data in the 'incoming' region into 'accu<i>'
  18316. accumulate( accuIndex, weight ) {
  18317. // note: happily accumulating nothing when weight = 0, the caller knows
  18318. // the weight and shouldn't have made the call in the first place
  18319. const buffer = this.buffer,
  18320. stride = this.valueSize,
  18321. offset = accuIndex * stride + stride;
  18322. let currentWeight = this.cumulativeWeight;
  18323. if ( currentWeight === 0 ) {
  18324. // accuN := incoming * weight
  18325. for ( let i = 0; i !== stride; ++ i ) {
  18326. buffer[ offset + i ] = buffer[ i ];
  18327. }
  18328. currentWeight = weight;
  18329. } else {
  18330. // accuN := accuN + incoming * weight
  18331. currentWeight += weight;
  18332. const mix = weight / currentWeight;
  18333. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18334. }
  18335. this.cumulativeWeight = currentWeight;
  18336. }
  18337. // accumulate data in the 'incoming' region into 'add'
  18338. accumulateAdditive( weight ) {
  18339. const buffer = this.buffer,
  18340. stride = this.valueSize,
  18341. offset = stride * this._addIndex;
  18342. if ( this.cumulativeWeightAdditive === 0 ) {
  18343. // add = identity
  18344. this._setIdentity();
  18345. }
  18346. // add := add + incoming * weight
  18347. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18348. this.cumulativeWeightAdditive += weight;
  18349. }
  18350. // apply the state of 'accu<i>' to the binding when accus differ
  18351. apply( accuIndex ) {
  18352. const stride = this.valueSize,
  18353. buffer = this.buffer,
  18354. offset = accuIndex * stride + stride,
  18355. weight = this.cumulativeWeight,
  18356. weightAdditive = this.cumulativeWeightAdditive,
  18357. binding = this.binding;
  18358. this.cumulativeWeight = 0;
  18359. this.cumulativeWeightAdditive = 0;
  18360. if ( weight < 1 ) {
  18361. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18362. const originalValueOffset = stride * this._origIndex;
  18363. this._mixBufferRegion(
  18364. buffer, offset, originalValueOffset, 1 - weight, stride );
  18365. }
  18366. if ( weightAdditive > 0 ) {
  18367. // accuN := accuN + additive accuN
  18368. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18369. }
  18370. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18371. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18372. // value has changed -> update scene graph
  18373. binding.setValue( buffer, offset );
  18374. break;
  18375. }
  18376. }
  18377. }
  18378. // remember the state of the bound property and copy it to both accus
  18379. saveOriginalState() {
  18380. const binding = this.binding;
  18381. const buffer = this.buffer,
  18382. stride = this.valueSize,
  18383. originalValueOffset = stride * this._origIndex;
  18384. binding.getValue( buffer, originalValueOffset );
  18385. // accu[0..1] := orig -- initially detect changes against the original
  18386. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18387. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18388. }
  18389. // Add to identity for additive
  18390. this._setIdentity();
  18391. this.cumulativeWeight = 0;
  18392. this.cumulativeWeightAdditive = 0;
  18393. }
  18394. // apply the state previously taken via 'saveOriginalState' to the binding
  18395. restoreOriginalState() {
  18396. const originalValueOffset = this.valueSize * 3;
  18397. this.binding.setValue( this.buffer, originalValueOffset );
  18398. }
  18399. _setAdditiveIdentityNumeric() {
  18400. const startIndex = this._addIndex * this.valueSize;
  18401. const endIndex = startIndex + this.valueSize;
  18402. for ( let i = startIndex; i < endIndex; i ++ ) {
  18403. this.buffer[ i ] = 0;
  18404. }
  18405. }
  18406. _setAdditiveIdentityQuaternion() {
  18407. this._setAdditiveIdentityNumeric();
  18408. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18409. }
  18410. _setAdditiveIdentityOther() {
  18411. const startIndex = this._origIndex * this.valueSize;
  18412. const targetIndex = this._addIndex * this.valueSize;
  18413. for ( let i = 0; i < this.valueSize; i ++ ) {
  18414. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18415. }
  18416. }
  18417. // mix functions
  18418. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18419. if ( t >= 0.5 ) {
  18420. for ( let i = 0; i !== stride; ++ i ) {
  18421. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18422. }
  18423. }
  18424. }
  18425. _slerp( buffer, dstOffset, srcOffset, t ) {
  18426. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18427. }
  18428. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18429. const workOffset = this._workIndex * stride;
  18430. // Store result in intermediate buffer offset
  18431. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18432. // Slerp to the intermediate result
  18433. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18434. }
  18435. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18436. const s = 1 - t;
  18437. for ( let i = 0; i !== stride; ++ i ) {
  18438. const j = dstOffset + i;
  18439. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18440. }
  18441. }
  18442. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18443. for ( let i = 0; i !== stride; ++ i ) {
  18444. const j = dstOffset + i;
  18445. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18446. }
  18447. }
  18448. }
  18449. // Characters [].:/ are reserved for track binding syntax.
  18450. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18451. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18452. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18453. // only latin characters, and the unicode \p{L} is not yet supported. So
  18454. // instead, we exclude reserved characters and match everything else.
  18455. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18456. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18457. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18458. // be matched to parse the rest of the track name.
  18459. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18460. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18461. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18462. // Object on target node, and accessor. May not contain reserved
  18463. // characters. Accessor may contain any character except closing bracket.
  18464. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18465. // Property and accessor. May not contain reserved characters. Accessor may
  18466. // contain any non-bracket characters.
  18467. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18468. const _trackRe = new RegExp( ''
  18469. + '^'
  18470. + _directoryRe
  18471. + _nodeRe
  18472. + _objectRe
  18473. + _propertyRe
  18474. + '$'
  18475. );
  18476. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18477. class Composite {
  18478. constructor( targetGroup, path, optionalParsedPath ) {
  18479. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18480. this._targetGroup = targetGroup;
  18481. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18482. }
  18483. getValue( array, offset ) {
  18484. this.bind(); // bind all binding
  18485. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18486. binding = this._bindings[ firstValidIndex ];
  18487. // and only call .getValue on the first
  18488. if ( binding !== undefined ) binding.getValue( array, offset );
  18489. }
  18490. setValue( array, offset ) {
  18491. const bindings = this._bindings;
  18492. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18493. bindings[ i ].setValue( array, offset );
  18494. }
  18495. }
  18496. bind() {
  18497. const bindings = this._bindings;
  18498. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18499. bindings[ i ].bind();
  18500. }
  18501. }
  18502. unbind() {
  18503. const bindings = this._bindings;
  18504. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18505. bindings[ i ].unbind();
  18506. }
  18507. }
  18508. }
  18509. // Note: This class uses a State pattern on a per-method basis:
  18510. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18511. // prototype version of these methods with one that represents
  18512. // the bound state. When the property is not found, the methods
  18513. // become no-ops.
  18514. class PropertyBinding {
  18515. constructor( rootNode, path, parsedPath ) {
  18516. this.path = path;
  18517. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18518. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18519. this.rootNode = rootNode;
  18520. // initial state of these methods that calls 'bind'
  18521. this.getValue = this._getValue_unbound;
  18522. this.setValue = this._setValue_unbound;
  18523. }
  18524. static create( root, path, parsedPath ) {
  18525. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18526. return new PropertyBinding( root, path, parsedPath );
  18527. } else {
  18528. return new PropertyBinding.Composite( root, path, parsedPath );
  18529. }
  18530. }
  18531. /**
  18532. * Replaces spaces with underscores and removes unsupported characters from
  18533. * node names, to ensure compatibility with parseTrackName().
  18534. *
  18535. * @param {string} name Node name to be sanitized.
  18536. * @return {string}
  18537. */
  18538. static sanitizeNodeName( name ) {
  18539. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18540. }
  18541. static parseTrackName( trackName ) {
  18542. const matches = _trackRe.exec( trackName );
  18543. if ( matches === null ) {
  18544. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18545. }
  18546. const results = {
  18547. // directoryName: matches[ 1 ], // (tschw) currently unused
  18548. nodeName: matches[ 2 ],
  18549. objectName: matches[ 3 ],
  18550. objectIndex: matches[ 4 ],
  18551. propertyName: matches[ 5 ], // required
  18552. propertyIndex: matches[ 6 ]
  18553. };
  18554. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18555. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18556. const objectName = results.nodeName.substring( lastDot + 1 );
  18557. // Object names must be checked against an allowlist. Otherwise, there
  18558. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18559. // 'bar' could be the objectName, or part of a nodeName (which can
  18560. // include '.' characters).
  18561. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18562. results.nodeName = results.nodeName.substring( 0, lastDot );
  18563. results.objectName = objectName;
  18564. }
  18565. }
  18566. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18567. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18568. }
  18569. return results;
  18570. }
  18571. static findNode( root, nodeName ) {
  18572. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18573. return root;
  18574. }
  18575. // search into skeleton bones.
  18576. if ( root.skeleton ) {
  18577. const bone = root.skeleton.getBoneByName( nodeName );
  18578. if ( bone !== undefined ) {
  18579. return bone;
  18580. }
  18581. }
  18582. // search into node subtree.
  18583. if ( root.children ) {
  18584. const searchNodeSubtree = function ( children ) {
  18585. for ( let i = 0; i < children.length; i ++ ) {
  18586. const childNode = children[ i ];
  18587. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18588. return childNode;
  18589. }
  18590. const result = searchNodeSubtree( childNode.children );
  18591. if ( result ) return result;
  18592. }
  18593. return null;
  18594. };
  18595. const subTreeNode = searchNodeSubtree( root.children );
  18596. if ( subTreeNode ) {
  18597. return subTreeNode;
  18598. }
  18599. }
  18600. return null;
  18601. }
  18602. // these are used to "bind" a nonexistent property
  18603. _getValue_unavailable() {}
  18604. _setValue_unavailable() {}
  18605. // Getters
  18606. _getValue_direct( buffer, offset ) {
  18607. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18608. }
  18609. _getValue_array( buffer, offset ) {
  18610. const source = this.resolvedProperty;
  18611. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18612. buffer[ offset ++ ] = source[ i ];
  18613. }
  18614. }
  18615. _getValue_arrayElement( buffer, offset ) {
  18616. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18617. }
  18618. _getValue_toArray( buffer, offset ) {
  18619. this.resolvedProperty.toArray( buffer, offset );
  18620. }
  18621. // Direct
  18622. _setValue_direct( buffer, offset ) {
  18623. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18624. }
  18625. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18626. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18627. this.targetObject.needsUpdate = true;
  18628. }
  18629. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18630. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18631. this.targetObject.matrixWorldNeedsUpdate = true;
  18632. }
  18633. // EntireArray
  18634. _setValue_array( buffer, offset ) {
  18635. const dest = this.resolvedProperty;
  18636. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18637. dest[ i ] = buffer[ offset ++ ];
  18638. }
  18639. }
  18640. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18641. const dest = this.resolvedProperty;
  18642. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18643. dest[ i ] = buffer[ offset ++ ];
  18644. }
  18645. this.targetObject.needsUpdate = true;
  18646. }
  18647. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18648. const dest = this.resolvedProperty;
  18649. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18650. dest[ i ] = buffer[ offset ++ ];
  18651. }
  18652. this.targetObject.matrixWorldNeedsUpdate = true;
  18653. }
  18654. // ArrayElement
  18655. _setValue_arrayElement( buffer, offset ) {
  18656. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18657. }
  18658. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18659. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18660. this.targetObject.needsUpdate = true;
  18661. }
  18662. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18663. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18664. this.targetObject.matrixWorldNeedsUpdate = true;
  18665. }
  18666. // HasToFromArray
  18667. _setValue_fromArray( buffer, offset ) {
  18668. this.resolvedProperty.fromArray( buffer, offset );
  18669. }
  18670. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18671. this.resolvedProperty.fromArray( buffer, offset );
  18672. this.targetObject.needsUpdate = true;
  18673. }
  18674. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18675. this.resolvedProperty.fromArray( buffer, offset );
  18676. this.targetObject.matrixWorldNeedsUpdate = true;
  18677. }
  18678. _getValue_unbound( targetArray, offset ) {
  18679. this.bind();
  18680. this.getValue( targetArray, offset );
  18681. }
  18682. _setValue_unbound( sourceArray, offset ) {
  18683. this.bind();
  18684. this.setValue( sourceArray, offset );
  18685. }
  18686. // create getter / setter pair for a property in the scene graph
  18687. bind() {
  18688. let targetObject = this.node;
  18689. const parsedPath = this.parsedPath;
  18690. const objectName = parsedPath.objectName;
  18691. const propertyName = parsedPath.propertyName;
  18692. let propertyIndex = parsedPath.propertyIndex;
  18693. if ( ! targetObject ) {
  18694. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18695. this.node = targetObject;
  18696. }
  18697. // set fail state so we can just 'return' on error
  18698. this.getValue = this._getValue_unavailable;
  18699. this.setValue = this._setValue_unavailable;
  18700. // ensure there is a value node
  18701. if ( ! targetObject ) {
  18702. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18703. return;
  18704. }
  18705. if ( objectName ) {
  18706. let objectIndex = parsedPath.objectIndex;
  18707. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18708. switch ( objectName ) {
  18709. case 'materials':
  18710. if ( ! targetObject.material ) {
  18711. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18712. return;
  18713. }
  18714. if ( ! targetObject.material.materials ) {
  18715. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18716. return;
  18717. }
  18718. targetObject = targetObject.material.materials;
  18719. break;
  18720. case 'bones':
  18721. if ( ! targetObject.skeleton ) {
  18722. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18723. return;
  18724. }
  18725. // potential future optimization: skip this if propertyIndex is already an integer
  18726. // and convert the integer string to a true integer.
  18727. targetObject = targetObject.skeleton.bones;
  18728. // support resolving morphTarget names into indices.
  18729. for ( let i = 0; i < targetObject.length; i ++ ) {
  18730. if ( targetObject[ i ].name === objectIndex ) {
  18731. objectIndex = i;
  18732. break;
  18733. }
  18734. }
  18735. break;
  18736. case 'map':
  18737. if ( 'map' in targetObject ) {
  18738. targetObject = targetObject.map;
  18739. break;
  18740. }
  18741. if ( ! targetObject.material ) {
  18742. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18743. return;
  18744. }
  18745. if ( ! targetObject.material.map ) {
  18746. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18747. return;
  18748. }
  18749. targetObject = targetObject.material.map;
  18750. break;
  18751. default:
  18752. if ( targetObject[ objectName ] === undefined ) {
  18753. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18754. return;
  18755. }
  18756. targetObject = targetObject[ objectName ];
  18757. }
  18758. if ( objectIndex !== undefined ) {
  18759. if ( targetObject[ objectIndex ] === undefined ) {
  18760. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18761. return;
  18762. }
  18763. targetObject = targetObject[ objectIndex ];
  18764. }
  18765. }
  18766. // resolve property
  18767. const nodeProperty = targetObject[ propertyName ];
  18768. if ( nodeProperty === undefined ) {
  18769. const nodeName = parsedPath.nodeName;
  18770. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18771. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18772. return;
  18773. }
  18774. // determine versioning scheme
  18775. let versioning = this.Versioning.None;
  18776. this.targetObject = targetObject;
  18777. if ( targetObject.needsUpdate !== undefined ) { // material
  18778. versioning = this.Versioning.NeedsUpdate;
  18779. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18780. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18781. }
  18782. // determine how the property gets bound
  18783. let bindingType = this.BindingType.Direct;
  18784. if ( propertyIndex !== undefined ) {
  18785. // access a sub element of the property array (only primitives are supported right now)
  18786. if ( propertyName === 'morphTargetInfluences' ) {
  18787. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18788. // support resolving morphTarget names into indices.
  18789. if ( ! targetObject.geometry ) {
  18790. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18791. return;
  18792. }
  18793. if ( ! targetObject.geometry.morphAttributes ) {
  18794. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18795. return;
  18796. }
  18797. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18798. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18799. }
  18800. }
  18801. bindingType = this.BindingType.ArrayElement;
  18802. this.resolvedProperty = nodeProperty;
  18803. this.propertyIndex = propertyIndex;
  18804. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18805. // must use copy for Object3D.Euler/Quaternion
  18806. bindingType = this.BindingType.HasFromToArray;
  18807. this.resolvedProperty = nodeProperty;
  18808. } else if ( Array.isArray( nodeProperty ) ) {
  18809. bindingType = this.BindingType.EntireArray;
  18810. this.resolvedProperty = nodeProperty;
  18811. } else {
  18812. this.propertyName = propertyName;
  18813. }
  18814. // select getter / setter
  18815. this.getValue = this.GetterByBindingType[ bindingType ];
  18816. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18817. }
  18818. unbind() {
  18819. this.node = null;
  18820. // back to the prototype version of getValue / setValue
  18821. // note: avoiding to mutate the shape of 'this' via 'delete'
  18822. this.getValue = this._getValue_unbound;
  18823. this.setValue = this._setValue_unbound;
  18824. }
  18825. }
  18826. PropertyBinding.Composite = Composite;
  18827. PropertyBinding.prototype.BindingType = {
  18828. Direct: 0,
  18829. EntireArray: 1,
  18830. ArrayElement: 2,
  18831. HasFromToArray: 3
  18832. };
  18833. PropertyBinding.prototype.Versioning = {
  18834. None: 0,
  18835. NeedsUpdate: 1,
  18836. MatrixWorldNeedsUpdate: 2
  18837. };
  18838. PropertyBinding.prototype.GetterByBindingType = [
  18839. PropertyBinding.prototype._getValue_direct,
  18840. PropertyBinding.prototype._getValue_array,
  18841. PropertyBinding.prototype._getValue_arrayElement,
  18842. PropertyBinding.prototype._getValue_toArray,
  18843. ];
  18844. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18845. [
  18846. // Direct
  18847. PropertyBinding.prototype._setValue_direct,
  18848. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18849. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18850. ], [
  18851. // EntireArray
  18852. PropertyBinding.prototype._setValue_array,
  18853. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18854. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18855. ], [
  18856. // ArrayElement
  18857. PropertyBinding.prototype._setValue_arrayElement,
  18858. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18859. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18860. ], [
  18861. // HasToFromArray
  18862. PropertyBinding.prototype._setValue_fromArray,
  18863. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18864. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18865. ]
  18866. ];
  18867. /**
  18868. *
  18869. * A group of objects that receives a shared animation state.
  18870. *
  18871. * Usage:
  18872. *
  18873. * - Add objects you would otherwise pass as 'root' to the
  18874. * constructor or the .clipAction method of AnimationMixer.
  18875. *
  18876. * - Instead pass this object as 'root'.
  18877. *
  18878. * - You can also add and remove objects later when the mixer
  18879. * is running.
  18880. *
  18881. * Note:
  18882. *
  18883. * Objects of this class appear as one object to the mixer,
  18884. * so cache control of the individual objects must be done
  18885. * on the group.
  18886. *
  18887. * Limitation:
  18888. *
  18889. * - The animated properties must be compatible among the
  18890. * all objects in the group.
  18891. *
  18892. * - A single property can either be controlled through a
  18893. * target group or directly, but not both.
  18894. */
  18895. class AnimationObjectGroup {
  18896. constructor() {
  18897. this.isAnimationObjectGroup = true;
  18898. this.uuid = generateUUID();
  18899. // cached objects followed by the active ones
  18900. this._objects = Array.prototype.slice.call( arguments );
  18901. this.nCachedObjects_ = 0; // threshold
  18902. // note: read by PropertyBinding.Composite
  18903. const indices = {};
  18904. this._indicesByUUID = indices; // for bookkeeping
  18905. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18906. indices[ arguments[ i ].uuid ] = i;
  18907. }
  18908. this._paths = []; // inside: string
  18909. this._parsedPaths = []; // inside: { we don't care, here }
  18910. this._bindings = []; // inside: Array< PropertyBinding >
  18911. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18912. const scope = this;
  18913. this.stats = {
  18914. objects: {
  18915. get total() {
  18916. return scope._objects.length;
  18917. },
  18918. get inUse() {
  18919. return this.total - scope.nCachedObjects_;
  18920. }
  18921. },
  18922. get bindingsPerObject() {
  18923. return scope._bindings.length;
  18924. }
  18925. };
  18926. }
  18927. add() {
  18928. const objects = this._objects,
  18929. indicesByUUID = this._indicesByUUID,
  18930. paths = this._paths,
  18931. parsedPaths = this._parsedPaths,
  18932. bindings = this._bindings,
  18933. nBindings = bindings.length;
  18934. let knownObject = undefined,
  18935. nObjects = objects.length,
  18936. nCachedObjects = this.nCachedObjects_;
  18937. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18938. const object = arguments[ i ],
  18939. uuid = object.uuid;
  18940. let index = indicesByUUID[ uuid ];
  18941. if ( index === undefined ) {
  18942. // unknown object -> add it to the ACTIVE region
  18943. index = nObjects ++;
  18944. indicesByUUID[ uuid ] = index;
  18945. objects.push( object );
  18946. // accounting is done, now do the same for all bindings
  18947. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18948. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18949. }
  18950. } else if ( index < nCachedObjects ) {
  18951. knownObject = objects[ index ];
  18952. // move existing object to the ACTIVE region
  18953. const firstActiveIndex = -- nCachedObjects,
  18954. lastCachedObject = objects[ firstActiveIndex ];
  18955. indicesByUUID[ lastCachedObject.uuid ] = index;
  18956. objects[ index ] = lastCachedObject;
  18957. indicesByUUID[ uuid ] = firstActiveIndex;
  18958. objects[ firstActiveIndex ] = object;
  18959. // accounting is done, now do the same for all bindings
  18960. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18961. const bindingsForPath = bindings[ j ],
  18962. lastCached = bindingsForPath[ firstActiveIndex ];
  18963. let binding = bindingsForPath[ index ];
  18964. bindingsForPath[ index ] = lastCached;
  18965. if ( binding === undefined ) {
  18966. // since we do not bother to create new bindings
  18967. // for objects that are cached, the binding may
  18968. // or may not exist
  18969. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  18970. }
  18971. bindingsForPath[ firstActiveIndex ] = binding;
  18972. }
  18973. } else if ( objects[ index ] !== knownObject ) {
  18974. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  18975. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  18976. } // else the object is already where we want it to be
  18977. } // for arguments
  18978. this.nCachedObjects_ = nCachedObjects;
  18979. }
  18980. remove() {
  18981. const objects = this._objects,
  18982. indicesByUUID = this._indicesByUUID,
  18983. bindings = this._bindings,
  18984. nBindings = bindings.length;
  18985. let nCachedObjects = this.nCachedObjects_;
  18986. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18987. const object = arguments[ i ],
  18988. uuid = object.uuid,
  18989. index = indicesByUUID[ uuid ];
  18990. if ( index !== undefined && index >= nCachedObjects ) {
  18991. // move existing object into the CACHED region
  18992. const lastCachedIndex = nCachedObjects ++,
  18993. firstActiveObject = objects[ lastCachedIndex ];
  18994. indicesByUUID[ firstActiveObject.uuid ] = index;
  18995. objects[ index ] = firstActiveObject;
  18996. indicesByUUID[ uuid ] = lastCachedIndex;
  18997. objects[ lastCachedIndex ] = object;
  18998. // accounting is done, now do the same for all bindings
  18999. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19000. const bindingsForPath = bindings[ j ],
  19001. firstActive = bindingsForPath[ lastCachedIndex ],
  19002. binding = bindingsForPath[ index ];
  19003. bindingsForPath[ index ] = firstActive;
  19004. bindingsForPath[ lastCachedIndex ] = binding;
  19005. }
  19006. }
  19007. } // for arguments
  19008. this.nCachedObjects_ = nCachedObjects;
  19009. }
  19010. // remove & forget
  19011. uncache() {
  19012. const objects = this._objects,
  19013. indicesByUUID = this._indicesByUUID,
  19014. bindings = this._bindings,
  19015. nBindings = bindings.length;
  19016. let nCachedObjects = this.nCachedObjects_,
  19017. nObjects = objects.length;
  19018. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19019. const object = arguments[ i ],
  19020. uuid = object.uuid,
  19021. index = indicesByUUID[ uuid ];
  19022. if ( index !== undefined ) {
  19023. delete indicesByUUID[ uuid ];
  19024. if ( index < nCachedObjects ) {
  19025. // object is cached, shrink the CACHED region
  19026. const firstActiveIndex = -- nCachedObjects,
  19027. lastCachedObject = objects[ firstActiveIndex ],
  19028. lastIndex = -- nObjects,
  19029. lastObject = objects[ lastIndex ];
  19030. // last cached object takes this object's place
  19031. indicesByUUID[ lastCachedObject.uuid ] = index;
  19032. objects[ index ] = lastCachedObject;
  19033. // last object goes to the activated slot and pop
  19034. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19035. objects[ firstActiveIndex ] = lastObject;
  19036. objects.pop();
  19037. // accounting is done, now do the same for all bindings
  19038. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19039. const bindingsForPath = bindings[ j ],
  19040. lastCached = bindingsForPath[ firstActiveIndex ],
  19041. last = bindingsForPath[ lastIndex ];
  19042. bindingsForPath[ index ] = lastCached;
  19043. bindingsForPath[ firstActiveIndex ] = last;
  19044. bindingsForPath.pop();
  19045. }
  19046. } else {
  19047. // object is active, just swap with the last and pop
  19048. const lastIndex = -- nObjects,
  19049. lastObject = objects[ lastIndex ];
  19050. if ( lastIndex > 0 ) {
  19051. indicesByUUID[ lastObject.uuid ] = index;
  19052. }
  19053. objects[ index ] = lastObject;
  19054. objects.pop();
  19055. // accounting is done, now do the same for all bindings
  19056. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19057. const bindingsForPath = bindings[ j ];
  19058. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19059. bindingsForPath.pop();
  19060. }
  19061. } // cached or active
  19062. } // if object is known
  19063. } // for arguments
  19064. this.nCachedObjects_ = nCachedObjects;
  19065. }
  19066. // Internal interface used by befriended PropertyBinding.Composite:
  19067. subscribe_( path, parsedPath ) {
  19068. // returns an array of bindings for the given path that is changed
  19069. // according to the contained objects in the group
  19070. const indicesByPath = this._bindingsIndicesByPath;
  19071. let index = indicesByPath[ path ];
  19072. const bindings = this._bindings;
  19073. if ( index !== undefined ) return bindings[ index ];
  19074. const paths = this._paths,
  19075. parsedPaths = this._parsedPaths,
  19076. objects = this._objects,
  19077. nObjects = objects.length,
  19078. nCachedObjects = this.nCachedObjects_,
  19079. bindingsForPath = new Array( nObjects );
  19080. index = bindings.length;
  19081. indicesByPath[ path ] = index;
  19082. paths.push( path );
  19083. parsedPaths.push( parsedPath );
  19084. bindings.push( bindingsForPath );
  19085. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19086. const object = objects[ i ];
  19087. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19088. }
  19089. return bindingsForPath;
  19090. }
  19091. unsubscribe_( path ) {
  19092. // tells the group to forget about a property path and no longer
  19093. // update the array previously obtained with 'subscribe_'
  19094. const indicesByPath = this._bindingsIndicesByPath,
  19095. index = indicesByPath[ path ];
  19096. if ( index !== undefined ) {
  19097. const paths = this._paths,
  19098. parsedPaths = this._parsedPaths,
  19099. bindings = this._bindings,
  19100. lastBindingsIndex = bindings.length - 1,
  19101. lastBindings = bindings[ lastBindingsIndex ],
  19102. lastBindingsPath = path[ lastBindingsIndex ];
  19103. indicesByPath[ lastBindingsPath ] = index;
  19104. bindings[ index ] = lastBindings;
  19105. bindings.pop();
  19106. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19107. parsedPaths.pop();
  19108. paths[ index ] = paths[ lastBindingsIndex ];
  19109. paths.pop();
  19110. }
  19111. }
  19112. }
  19113. class AnimationAction {
  19114. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19115. this._mixer = mixer;
  19116. this._clip = clip;
  19117. this._localRoot = localRoot;
  19118. this.blendMode = blendMode;
  19119. const tracks = clip.tracks,
  19120. nTracks = tracks.length,
  19121. interpolants = new Array( nTracks );
  19122. const interpolantSettings = {
  19123. endingStart: ZeroCurvatureEnding,
  19124. endingEnd: ZeroCurvatureEnding
  19125. };
  19126. for ( let i = 0; i !== nTracks; ++ i ) {
  19127. const interpolant = tracks[ i ].createInterpolant( null );
  19128. interpolants[ i ] = interpolant;
  19129. interpolant.settings = interpolantSettings;
  19130. }
  19131. this._interpolantSettings = interpolantSettings;
  19132. this._interpolants = interpolants; // bound by the mixer
  19133. // inside: PropertyMixer (managed by the mixer)
  19134. this._propertyBindings = new Array( nTracks );
  19135. this._cacheIndex = null; // for the memory manager
  19136. this._byClipCacheIndex = null; // for the memory manager
  19137. this._timeScaleInterpolant = null;
  19138. this._weightInterpolant = null;
  19139. this.loop = LoopRepeat;
  19140. this._loopCount = - 1;
  19141. // global mixer time when the action is to be started
  19142. // it's set back to 'null' upon start of the action
  19143. this._startTime = null;
  19144. // scaled local time of the action
  19145. // gets clamped or wrapped to 0..clip.duration according to loop
  19146. this.time = 0;
  19147. this.timeScale = 1;
  19148. this._effectiveTimeScale = 1;
  19149. this.weight = 1;
  19150. this._effectiveWeight = 1;
  19151. this.repetitions = Infinity; // no. of repetitions when looping
  19152. this.paused = false; // true -> zero effective time scale
  19153. this.enabled = true; // false -> zero effective weight
  19154. this.clampWhenFinished = false;// keep feeding the last frame?
  19155. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19156. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19157. }
  19158. // State & Scheduling
  19159. play() {
  19160. this._mixer._activateAction( this );
  19161. return this;
  19162. }
  19163. stop() {
  19164. this._mixer._deactivateAction( this );
  19165. return this.reset();
  19166. }
  19167. reset() {
  19168. this.paused = false;
  19169. this.enabled = true;
  19170. this.time = 0; // restart clip
  19171. this._loopCount = - 1;// forget previous loops
  19172. this._startTime = null;// forget scheduling
  19173. return this.stopFading().stopWarping();
  19174. }
  19175. isRunning() {
  19176. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19177. this._startTime === null && this._mixer._isActiveAction( this );
  19178. }
  19179. // return true when play has been called
  19180. isScheduled() {
  19181. return this._mixer._isActiveAction( this );
  19182. }
  19183. startAt( time ) {
  19184. this._startTime = time;
  19185. return this;
  19186. }
  19187. setLoop( mode, repetitions ) {
  19188. this.loop = mode;
  19189. this.repetitions = repetitions;
  19190. return this;
  19191. }
  19192. // Weight
  19193. // set the weight stopping any scheduled fading
  19194. // although .enabled = false yields an effective weight of zero, this
  19195. // method does *not* change .enabled, because it would be confusing
  19196. setEffectiveWeight( weight ) {
  19197. this.weight = weight;
  19198. // note: same logic as when updated at runtime
  19199. this._effectiveWeight = this.enabled ? weight : 0;
  19200. return this.stopFading();
  19201. }
  19202. // return the weight considering fading and .enabled
  19203. getEffectiveWeight() {
  19204. return this._effectiveWeight;
  19205. }
  19206. fadeIn( duration ) {
  19207. return this._scheduleFading( duration, 0, 1 );
  19208. }
  19209. fadeOut( duration ) {
  19210. return this._scheduleFading( duration, 1, 0 );
  19211. }
  19212. crossFadeFrom( fadeOutAction, duration, warp ) {
  19213. fadeOutAction.fadeOut( duration );
  19214. this.fadeIn( duration );
  19215. if ( warp ) {
  19216. const fadeInDuration = this._clip.duration,
  19217. fadeOutDuration = fadeOutAction._clip.duration,
  19218. startEndRatio = fadeOutDuration / fadeInDuration,
  19219. endStartRatio = fadeInDuration / fadeOutDuration;
  19220. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19221. this.warp( endStartRatio, 1.0, duration );
  19222. }
  19223. return this;
  19224. }
  19225. crossFadeTo( fadeInAction, duration, warp ) {
  19226. return fadeInAction.crossFadeFrom( this, duration, warp );
  19227. }
  19228. stopFading() {
  19229. const weightInterpolant = this._weightInterpolant;
  19230. if ( weightInterpolant !== null ) {
  19231. this._weightInterpolant = null;
  19232. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19233. }
  19234. return this;
  19235. }
  19236. // Time Scale Control
  19237. // set the time scale stopping any scheduled warping
  19238. // although .paused = true yields an effective time scale of zero, this
  19239. // method does *not* change .paused, because it would be confusing
  19240. setEffectiveTimeScale( timeScale ) {
  19241. this.timeScale = timeScale;
  19242. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19243. return this.stopWarping();
  19244. }
  19245. // return the time scale considering warping and .paused
  19246. getEffectiveTimeScale() {
  19247. return this._effectiveTimeScale;
  19248. }
  19249. setDuration( duration ) {
  19250. this.timeScale = this._clip.duration / duration;
  19251. return this.stopWarping();
  19252. }
  19253. syncWith( action ) {
  19254. this.time = action.time;
  19255. this.timeScale = action.timeScale;
  19256. return this.stopWarping();
  19257. }
  19258. halt( duration ) {
  19259. return this.warp( this._effectiveTimeScale, 0, duration );
  19260. }
  19261. warp( startTimeScale, endTimeScale, duration ) {
  19262. const mixer = this._mixer,
  19263. now = mixer.time,
  19264. timeScale = this.timeScale;
  19265. let interpolant = this._timeScaleInterpolant;
  19266. if ( interpolant === null ) {
  19267. interpolant = mixer._lendControlInterpolant();
  19268. this._timeScaleInterpolant = interpolant;
  19269. }
  19270. const times = interpolant.parameterPositions,
  19271. values = interpolant.sampleValues;
  19272. times[ 0 ] = now;
  19273. times[ 1 ] = now + duration;
  19274. values[ 0 ] = startTimeScale / timeScale;
  19275. values[ 1 ] = endTimeScale / timeScale;
  19276. return this;
  19277. }
  19278. stopWarping() {
  19279. const timeScaleInterpolant = this._timeScaleInterpolant;
  19280. if ( timeScaleInterpolant !== null ) {
  19281. this._timeScaleInterpolant = null;
  19282. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19283. }
  19284. return this;
  19285. }
  19286. // Object Accessors
  19287. getMixer() {
  19288. return this._mixer;
  19289. }
  19290. getClip() {
  19291. return this._clip;
  19292. }
  19293. getRoot() {
  19294. return this._localRoot || this._mixer._root;
  19295. }
  19296. // Interna
  19297. _update( time, deltaTime, timeDirection, accuIndex ) {
  19298. // called by the mixer
  19299. if ( ! this.enabled ) {
  19300. // call ._updateWeight() to update ._effectiveWeight
  19301. this._updateWeight( time );
  19302. return;
  19303. }
  19304. const startTime = this._startTime;
  19305. if ( startTime !== null ) {
  19306. // check for scheduled start of action
  19307. const timeRunning = ( time - startTime ) * timeDirection;
  19308. if ( timeRunning < 0 || timeDirection === 0 ) {
  19309. deltaTime = 0;
  19310. } else {
  19311. this._startTime = null; // unschedule
  19312. deltaTime = timeDirection * timeRunning;
  19313. }
  19314. }
  19315. // apply time scale and advance time
  19316. deltaTime *= this._updateTimeScale( time );
  19317. const clipTime = this._updateTime( deltaTime );
  19318. // note: _updateTime may disable the action resulting in
  19319. // an effective weight of 0
  19320. const weight = this._updateWeight( time );
  19321. if ( weight > 0 ) {
  19322. const interpolants = this._interpolants;
  19323. const propertyMixers = this._propertyBindings;
  19324. switch ( this.blendMode ) {
  19325. case AdditiveAnimationBlendMode:
  19326. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19327. interpolants[ j ].evaluate( clipTime );
  19328. propertyMixers[ j ].accumulateAdditive( weight );
  19329. }
  19330. break;
  19331. case NormalAnimationBlendMode:
  19332. default:
  19333. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19334. interpolants[ j ].evaluate( clipTime );
  19335. propertyMixers[ j ].accumulate( accuIndex, weight );
  19336. }
  19337. }
  19338. }
  19339. }
  19340. _updateWeight( time ) {
  19341. let weight = 0;
  19342. if ( this.enabled ) {
  19343. weight = this.weight;
  19344. const interpolant = this._weightInterpolant;
  19345. if ( interpolant !== null ) {
  19346. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19347. weight *= interpolantValue;
  19348. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19349. this.stopFading();
  19350. if ( interpolantValue === 0 ) {
  19351. // faded out, disable
  19352. this.enabled = false;
  19353. }
  19354. }
  19355. }
  19356. }
  19357. this._effectiveWeight = weight;
  19358. return weight;
  19359. }
  19360. _updateTimeScale( time ) {
  19361. let timeScale = 0;
  19362. if ( ! this.paused ) {
  19363. timeScale = this.timeScale;
  19364. const interpolant = this._timeScaleInterpolant;
  19365. if ( interpolant !== null ) {
  19366. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19367. timeScale *= interpolantValue;
  19368. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19369. this.stopWarping();
  19370. if ( timeScale === 0 ) {
  19371. // motion has halted, pause
  19372. this.paused = true;
  19373. } else {
  19374. // warp done - apply final time scale
  19375. this.timeScale = timeScale;
  19376. }
  19377. }
  19378. }
  19379. }
  19380. this._effectiveTimeScale = timeScale;
  19381. return timeScale;
  19382. }
  19383. _updateTime( deltaTime ) {
  19384. const duration = this._clip.duration;
  19385. const loop = this.loop;
  19386. let time = this.time + deltaTime;
  19387. let loopCount = this._loopCount;
  19388. const pingPong = ( loop === LoopPingPong );
  19389. if ( deltaTime === 0 ) {
  19390. if ( loopCount === - 1 ) return time;
  19391. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19392. }
  19393. if ( loop === LoopOnce ) {
  19394. if ( loopCount === - 1 ) {
  19395. // just started
  19396. this._loopCount = 0;
  19397. this._setEndings( true, true, false );
  19398. }
  19399. handle_stop: {
  19400. if ( time >= duration ) {
  19401. time = duration;
  19402. } else if ( time < 0 ) {
  19403. time = 0;
  19404. } else {
  19405. this.time = time;
  19406. break handle_stop;
  19407. }
  19408. if ( this.clampWhenFinished ) this.paused = true;
  19409. else this.enabled = false;
  19410. this.time = time;
  19411. this._mixer.dispatchEvent( {
  19412. type: 'finished', action: this,
  19413. direction: deltaTime < 0 ? - 1 : 1
  19414. } );
  19415. }
  19416. } else { // repetitive Repeat or PingPong
  19417. if ( loopCount === - 1 ) {
  19418. // just started
  19419. if ( deltaTime >= 0 ) {
  19420. loopCount = 0;
  19421. this._setEndings( true, this.repetitions === 0, pingPong );
  19422. } else {
  19423. // when looping in reverse direction, the initial
  19424. // transition through zero counts as a repetition,
  19425. // so leave loopCount at -1
  19426. this._setEndings( this.repetitions === 0, true, pingPong );
  19427. }
  19428. }
  19429. if ( time >= duration || time < 0 ) {
  19430. // wrap around
  19431. const loopDelta = Math.floor( time / duration ); // signed
  19432. time -= duration * loopDelta;
  19433. loopCount += Math.abs( loopDelta );
  19434. const pending = this.repetitions - loopCount;
  19435. if ( pending <= 0 ) {
  19436. // have to stop (switch state, clamp time, fire event)
  19437. if ( this.clampWhenFinished ) this.paused = true;
  19438. else this.enabled = false;
  19439. time = deltaTime > 0 ? duration : 0;
  19440. this.time = time;
  19441. this._mixer.dispatchEvent( {
  19442. type: 'finished', action: this,
  19443. direction: deltaTime > 0 ? 1 : - 1
  19444. } );
  19445. } else {
  19446. // keep running
  19447. if ( pending === 1 ) {
  19448. // entering the last round
  19449. const atStart = deltaTime < 0;
  19450. this._setEndings( atStart, ! atStart, pingPong );
  19451. } else {
  19452. this._setEndings( false, false, pingPong );
  19453. }
  19454. this._loopCount = loopCount;
  19455. this.time = time;
  19456. this._mixer.dispatchEvent( {
  19457. type: 'loop', action: this, loopDelta: loopDelta
  19458. } );
  19459. }
  19460. } else {
  19461. this.time = time;
  19462. }
  19463. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19464. // invert time for the "pong round"
  19465. return duration - time;
  19466. }
  19467. }
  19468. return time;
  19469. }
  19470. _setEndings( atStart, atEnd, pingPong ) {
  19471. const settings = this._interpolantSettings;
  19472. if ( pingPong ) {
  19473. settings.endingStart = ZeroSlopeEnding;
  19474. settings.endingEnd = ZeroSlopeEnding;
  19475. } else {
  19476. // assuming for LoopOnce atStart == atEnd == true
  19477. if ( atStart ) {
  19478. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19479. } else {
  19480. settings.endingStart = WrapAroundEnding;
  19481. }
  19482. if ( atEnd ) {
  19483. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19484. } else {
  19485. settings.endingEnd = WrapAroundEnding;
  19486. }
  19487. }
  19488. }
  19489. _scheduleFading( duration, weightNow, weightThen ) {
  19490. const mixer = this._mixer, now = mixer.time;
  19491. let interpolant = this._weightInterpolant;
  19492. if ( interpolant === null ) {
  19493. interpolant = mixer._lendControlInterpolant();
  19494. this._weightInterpolant = interpolant;
  19495. }
  19496. const times = interpolant.parameterPositions,
  19497. values = interpolant.sampleValues;
  19498. times[ 0 ] = now;
  19499. values[ 0 ] = weightNow;
  19500. times[ 1 ] = now + duration;
  19501. values[ 1 ] = weightThen;
  19502. return this;
  19503. }
  19504. }
  19505. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19506. class AnimationMixer extends EventDispatcher {
  19507. constructor( root ) {
  19508. super();
  19509. this._root = root;
  19510. this._initMemoryManager();
  19511. this._accuIndex = 0;
  19512. this.time = 0;
  19513. this.timeScale = 1.0;
  19514. }
  19515. _bindAction( action, prototypeAction ) {
  19516. const root = action._localRoot || this._root,
  19517. tracks = action._clip.tracks,
  19518. nTracks = tracks.length,
  19519. bindings = action._propertyBindings,
  19520. interpolants = action._interpolants,
  19521. rootUuid = root.uuid,
  19522. bindingsByRoot = this._bindingsByRootAndName;
  19523. let bindingsByName = bindingsByRoot[ rootUuid ];
  19524. if ( bindingsByName === undefined ) {
  19525. bindingsByName = {};
  19526. bindingsByRoot[ rootUuid ] = bindingsByName;
  19527. }
  19528. for ( let i = 0; i !== nTracks; ++ i ) {
  19529. const track = tracks[ i ],
  19530. trackName = track.name;
  19531. let binding = bindingsByName[ trackName ];
  19532. if ( binding !== undefined ) {
  19533. ++ binding.referenceCount;
  19534. bindings[ i ] = binding;
  19535. } else {
  19536. binding = bindings[ i ];
  19537. if ( binding !== undefined ) {
  19538. // existing binding, make sure the cache knows
  19539. if ( binding._cacheIndex === null ) {
  19540. ++ binding.referenceCount;
  19541. this._addInactiveBinding( binding, rootUuid, trackName );
  19542. }
  19543. continue;
  19544. }
  19545. const path = prototypeAction && prototypeAction.
  19546. _propertyBindings[ i ].binding.parsedPath;
  19547. binding = new PropertyMixer(
  19548. PropertyBinding.create( root, trackName, path ),
  19549. track.ValueTypeName, track.getValueSize() );
  19550. ++ binding.referenceCount;
  19551. this._addInactiveBinding( binding, rootUuid, trackName );
  19552. bindings[ i ] = binding;
  19553. }
  19554. interpolants[ i ].resultBuffer = binding.buffer;
  19555. }
  19556. }
  19557. _activateAction( action ) {
  19558. if ( ! this._isActiveAction( action ) ) {
  19559. if ( action._cacheIndex === null ) {
  19560. // this action has been forgotten by the cache, but the user
  19561. // appears to be still using it -> rebind
  19562. const rootUuid = ( action._localRoot || this._root ).uuid,
  19563. clipUuid = action._clip.uuid,
  19564. actionsForClip = this._actionsByClip[ clipUuid ];
  19565. this._bindAction( action,
  19566. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19567. this._addInactiveAction( action, clipUuid, rootUuid );
  19568. }
  19569. const bindings = action._propertyBindings;
  19570. // increment reference counts / sort out state
  19571. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19572. const binding = bindings[ i ];
  19573. if ( binding.useCount ++ === 0 ) {
  19574. this._lendBinding( binding );
  19575. binding.saveOriginalState();
  19576. }
  19577. }
  19578. this._lendAction( action );
  19579. }
  19580. }
  19581. _deactivateAction( action ) {
  19582. if ( this._isActiveAction( action ) ) {
  19583. const bindings = action._propertyBindings;
  19584. // decrement reference counts / sort out state
  19585. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19586. const binding = bindings[ i ];
  19587. if ( -- binding.useCount === 0 ) {
  19588. binding.restoreOriginalState();
  19589. this._takeBackBinding( binding );
  19590. }
  19591. }
  19592. this._takeBackAction( action );
  19593. }
  19594. }
  19595. // Memory manager
  19596. _initMemoryManager() {
  19597. this._actions = []; // 'nActiveActions' followed by inactive ones
  19598. this._nActiveActions = 0;
  19599. this._actionsByClip = {};
  19600. // inside:
  19601. // {
  19602. // knownActions: Array< AnimationAction > - used as prototypes
  19603. // actionByRoot: AnimationAction - lookup
  19604. // }
  19605. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19606. this._nActiveBindings = 0;
  19607. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19608. this._controlInterpolants = []; // same game as above
  19609. this._nActiveControlInterpolants = 0;
  19610. const scope = this;
  19611. this.stats = {
  19612. actions: {
  19613. get total() {
  19614. return scope._actions.length;
  19615. },
  19616. get inUse() {
  19617. return scope._nActiveActions;
  19618. }
  19619. },
  19620. bindings: {
  19621. get total() {
  19622. return scope._bindings.length;
  19623. },
  19624. get inUse() {
  19625. return scope._nActiveBindings;
  19626. }
  19627. },
  19628. controlInterpolants: {
  19629. get total() {
  19630. return scope._controlInterpolants.length;
  19631. },
  19632. get inUse() {
  19633. return scope._nActiveControlInterpolants;
  19634. }
  19635. }
  19636. };
  19637. }
  19638. // Memory management for AnimationAction objects
  19639. _isActiveAction( action ) {
  19640. const index = action._cacheIndex;
  19641. return index !== null && index < this._nActiveActions;
  19642. }
  19643. _addInactiveAction( action, clipUuid, rootUuid ) {
  19644. const actions = this._actions,
  19645. actionsByClip = this._actionsByClip;
  19646. let actionsForClip = actionsByClip[ clipUuid ];
  19647. if ( actionsForClip === undefined ) {
  19648. actionsForClip = {
  19649. knownActions: [ action ],
  19650. actionByRoot: {}
  19651. };
  19652. action._byClipCacheIndex = 0;
  19653. actionsByClip[ clipUuid ] = actionsForClip;
  19654. } else {
  19655. const knownActions = actionsForClip.knownActions;
  19656. action._byClipCacheIndex = knownActions.length;
  19657. knownActions.push( action );
  19658. }
  19659. action._cacheIndex = actions.length;
  19660. actions.push( action );
  19661. actionsForClip.actionByRoot[ rootUuid ] = action;
  19662. }
  19663. _removeInactiveAction( action ) {
  19664. const actions = this._actions,
  19665. lastInactiveAction = actions[ actions.length - 1 ],
  19666. cacheIndex = action._cacheIndex;
  19667. lastInactiveAction._cacheIndex = cacheIndex;
  19668. actions[ cacheIndex ] = lastInactiveAction;
  19669. actions.pop();
  19670. action._cacheIndex = null;
  19671. const clipUuid = action._clip.uuid,
  19672. actionsByClip = this._actionsByClip,
  19673. actionsForClip = actionsByClip[ clipUuid ],
  19674. knownActionsForClip = actionsForClip.knownActions,
  19675. lastKnownAction =
  19676. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19677. byClipCacheIndex = action._byClipCacheIndex;
  19678. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19679. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19680. knownActionsForClip.pop();
  19681. action._byClipCacheIndex = null;
  19682. const actionByRoot = actionsForClip.actionByRoot,
  19683. rootUuid = ( action._localRoot || this._root ).uuid;
  19684. delete actionByRoot[ rootUuid ];
  19685. if ( knownActionsForClip.length === 0 ) {
  19686. delete actionsByClip[ clipUuid ];
  19687. }
  19688. this._removeInactiveBindingsForAction( action );
  19689. }
  19690. _removeInactiveBindingsForAction( action ) {
  19691. const bindings = action._propertyBindings;
  19692. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19693. const binding = bindings[ i ];
  19694. if ( -- binding.referenceCount === 0 ) {
  19695. this._removeInactiveBinding( binding );
  19696. }
  19697. }
  19698. }
  19699. _lendAction( action ) {
  19700. // [ active actions | inactive actions ]
  19701. // [ active actions >| inactive actions ]
  19702. // s a
  19703. // <-swap->
  19704. // a s
  19705. const actions = this._actions,
  19706. prevIndex = action._cacheIndex,
  19707. lastActiveIndex = this._nActiveActions ++,
  19708. firstInactiveAction = actions[ lastActiveIndex ];
  19709. action._cacheIndex = lastActiveIndex;
  19710. actions[ lastActiveIndex ] = action;
  19711. firstInactiveAction._cacheIndex = prevIndex;
  19712. actions[ prevIndex ] = firstInactiveAction;
  19713. }
  19714. _takeBackAction( action ) {
  19715. // [ active actions | inactive actions ]
  19716. // [ active actions |< inactive actions ]
  19717. // a s
  19718. // <-swap->
  19719. // s a
  19720. const actions = this._actions,
  19721. prevIndex = action._cacheIndex,
  19722. firstInactiveIndex = -- this._nActiveActions,
  19723. lastActiveAction = actions[ firstInactiveIndex ];
  19724. action._cacheIndex = firstInactiveIndex;
  19725. actions[ firstInactiveIndex ] = action;
  19726. lastActiveAction._cacheIndex = prevIndex;
  19727. actions[ prevIndex ] = lastActiveAction;
  19728. }
  19729. // Memory management for PropertyMixer objects
  19730. _addInactiveBinding( binding, rootUuid, trackName ) {
  19731. const bindingsByRoot = this._bindingsByRootAndName,
  19732. bindings = this._bindings;
  19733. let bindingByName = bindingsByRoot[ rootUuid ];
  19734. if ( bindingByName === undefined ) {
  19735. bindingByName = {};
  19736. bindingsByRoot[ rootUuid ] = bindingByName;
  19737. }
  19738. bindingByName[ trackName ] = binding;
  19739. binding._cacheIndex = bindings.length;
  19740. bindings.push( binding );
  19741. }
  19742. _removeInactiveBinding( binding ) {
  19743. const bindings = this._bindings,
  19744. propBinding = binding.binding,
  19745. rootUuid = propBinding.rootNode.uuid,
  19746. trackName = propBinding.path,
  19747. bindingsByRoot = this._bindingsByRootAndName,
  19748. bindingByName = bindingsByRoot[ rootUuid ],
  19749. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19750. cacheIndex = binding._cacheIndex;
  19751. lastInactiveBinding._cacheIndex = cacheIndex;
  19752. bindings[ cacheIndex ] = lastInactiveBinding;
  19753. bindings.pop();
  19754. delete bindingByName[ trackName ];
  19755. if ( Object.keys( bindingByName ).length === 0 ) {
  19756. delete bindingsByRoot[ rootUuid ];
  19757. }
  19758. }
  19759. _lendBinding( binding ) {
  19760. const bindings = this._bindings,
  19761. prevIndex = binding._cacheIndex,
  19762. lastActiveIndex = this._nActiveBindings ++,
  19763. firstInactiveBinding = bindings[ lastActiveIndex ];
  19764. binding._cacheIndex = lastActiveIndex;
  19765. bindings[ lastActiveIndex ] = binding;
  19766. firstInactiveBinding._cacheIndex = prevIndex;
  19767. bindings[ prevIndex ] = firstInactiveBinding;
  19768. }
  19769. _takeBackBinding( binding ) {
  19770. const bindings = this._bindings,
  19771. prevIndex = binding._cacheIndex,
  19772. firstInactiveIndex = -- this._nActiveBindings,
  19773. lastActiveBinding = bindings[ firstInactiveIndex ];
  19774. binding._cacheIndex = firstInactiveIndex;
  19775. bindings[ firstInactiveIndex ] = binding;
  19776. lastActiveBinding._cacheIndex = prevIndex;
  19777. bindings[ prevIndex ] = lastActiveBinding;
  19778. }
  19779. // Memory management of Interpolants for weight and time scale
  19780. _lendControlInterpolant() {
  19781. const interpolants = this._controlInterpolants,
  19782. lastActiveIndex = this._nActiveControlInterpolants ++;
  19783. let interpolant = interpolants[ lastActiveIndex ];
  19784. if ( interpolant === undefined ) {
  19785. interpolant = new LinearInterpolant(
  19786. new Float32Array( 2 ), new Float32Array( 2 ),
  19787. 1, _controlInterpolantsResultBuffer );
  19788. interpolant.__cacheIndex = lastActiveIndex;
  19789. interpolants[ lastActiveIndex ] = interpolant;
  19790. }
  19791. return interpolant;
  19792. }
  19793. _takeBackControlInterpolant( interpolant ) {
  19794. const interpolants = this._controlInterpolants,
  19795. prevIndex = interpolant.__cacheIndex,
  19796. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19797. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19798. interpolant.__cacheIndex = firstInactiveIndex;
  19799. interpolants[ firstInactiveIndex ] = interpolant;
  19800. lastActiveInterpolant.__cacheIndex = prevIndex;
  19801. interpolants[ prevIndex ] = lastActiveInterpolant;
  19802. }
  19803. // return an action for a clip optionally using a custom root target
  19804. // object (this method allocates a lot of dynamic memory in case a
  19805. // previously unknown clip/root combination is specified)
  19806. clipAction( clip, optionalRoot, blendMode ) {
  19807. const root = optionalRoot || this._root,
  19808. rootUuid = root.uuid;
  19809. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19810. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19811. const actionsForClip = this._actionsByClip[ clipUuid ];
  19812. let prototypeAction = null;
  19813. if ( blendMode === undefined ) {
  19814. if ( clipObject !== null ) {
  19815. blendMode = clipObject.blendMode;
  19816. } else {
  19817. blendMode = NormalAnimationBlendMode;
  19818. }
  19819. }
  19820. if ( actionsForClip !== undefined ) {
  19821. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19822. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19823. return existingAction;
  19824. }
  19825. // we know the clip, so we don't have to parse all
  19826. // the bindings again but can just copy
  19827. prototypeAction = actionsForClip.knownActions[ 0 ];
  19828. // also, take the clip from the prototype action
  19829. if ( clipObject === null )
  19830. clipObject = prototypeAction._clip;
  19831. }
  19832. // clip must be known when specified via string
  19833. if ( clipObject === null ) return null;
  19834. // allocate all resources required to run it
  19835. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19836. this._bindAction( newAction, prototypeAction );
  19837. // and make the action known to the memory manager
  19838. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19839. return newAction;
  19840. }
  19841. // get an existing action
  19842. existingAction( clip, optionalRoot ) {
  19843. const root = optionalRoot || this._root,
  19844. rootUuid = root.uuid,
  19845. clipObject = typeof clip === 'string' ?
  19846. AnimationClip.findByName( root, clip ) : clip,
  19847. clipUuid = clipObject ? clipObject.uuid : clip,
  19848. actionsForClip = this._actionsByClip[ clipUuid ];
  19849. if ( actionsForClip !== undefined ) {
  19850. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19851. }
  19852. return null;
  19853. }
  19854. // deactivates all previously scheduled actions
  19855. stopAllAction() {
  19856. const actions = this._actions,
  19857. nActions = this._nActiveActions;
  19858. for ( let i = nActions - 1; i >= 0; -- i ) {
  19859. actions[ i ].stop();
  19860. }
  19861. return this;
  19862. }
  19863. // advance the time and update apply the animation
  19864. update( deltaTime ) {
  19865. deltaTime *= this.timeScale;
  19866. const actions = this._actions,
  19867. nActions = this._nActiveActions,
  19868. time = this.time += deltaTime,
  19869. timeDirection = Math.sign( deltaTime ),
  19870. accuIndex = this._accuIndex ^= 1;
  19871. // run active actions
  19872. for ( let i = 0; i !== nActions; ++ i ) {
  19873. const action = actions[ i ];
  19874. action._update( time, deltaTime, timeDirection, accuIndex );
  19875. }
  19876. // update scene graph
  19877. const bindings = this._bindings,
  19878. nBindings = this._nActiveBindings;
  19879. for ( let i = 0; i !== nBindings; ++ i ) {
  19880. bindings[ i ].apply( accuIndex );
  19881. }
  19882. return this;
  19883. }
  19884. // Allows you to seek to a specific time in an animation.
  19885. setTime( timeInSeconds ) {
  19886. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19887. for ( let i = 0; i < this._actions.length; i ++ ) {
  19888. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19889. }
  19890. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19891. }
  19892. // return this mixer's root target object
  19893. getRoot() {
  19894. return this._root;
  19895. }
  19896. // free all resources specific to a particular clip
  19897. uncacheClip( clip ) {
  19898. const actions = this._actions,
  19899. clipUuid = clip.uuid,
  19900. actionsByClip = this._actionsByClip,
  19901. actionsForClip = actionsByClip[ clipUuid ];
  19902. if ( actionsForClip !== undefined ) {
  19903. // note: just calling _removeInactiveAction would mess up the
  19904. // iteration state and also require updating the state we can
  19905. // just throw away
  19906. const actionsToRemove = actionsForClip.knownActions;
  19907. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19908. const action = actionsToRemove[ i ];
  19909. this._deactivateAction( action );
  19910. const cacheIndex = action._cacheIndex,
  19911. lastInactiveAction = actions[ actions.length - 1 ];
  19912. action._cacheIndex = null;
  19913. action._byClipCacheIndex = null;
  19914. lastInactiveAction._cacheIndex = cacheIndex;
  19915. actions[ cacheIndex ] = lastInactiveAction;
  19916. actions.pop();
  19917. this._removeInactiveBindingsForAction( action );
  19918. }
  19919. delete actionsByClip[ clipUuid ];
  19920. }
  19921. }
  19922. // free all resources specific to a particular root target object
  19923. uncacheRoot( root ) {
  19924. const rootUuid = root.uuid,
  19925. actionsByClip = this._actionsByClip;
  19926. for ( const clipUuid in actionsByClip ) {
  19927. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19928. action = actionByRoot[ rootUuid ];
  19929. if ( action !== undefined ) {
  19930. this._deactivateAction( action );
  19931. this._removeInactiveAction( action );
  19932. }
  19933. }
  19934. const bindingsByRoot = this._bindingsByRootAndName,
  19935. bindingByName = bindingsByRoot[ rootUuid ];
  19936. if ( bindingByName !== undefined ) {
  19937. for ( const trackName in bindingByName ) {
  19938. const binding = bindingByName[ trackName ];
  19939. binding.restoreOriginalState();
  19940. this._removeInactiveBinding( binding );
  19941. }
  19942. }
  19943. }
  19944. // remove a targeted clip from the cache
  19945. uncacheAction( clip, optionalRoot ) {
  19946. const action = this.existingAction( clip, optionalRoot );
  19947. if ( action !== null ) {
  19948. this._deactivateAction( action );
  19949. this._removeInactiveAction( action );
  19950. }
  19951. }
  19952. }
  19953. let Uniform$1 = class Uniform {
  19954. constructor( value ) {
  19955. this.value = value;
  19956. }
  19957. clone() {
  19958. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  19959. }
  19960. };
  19961. let _id$8 = 0;
  19962. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  19963. constructor() {
  19964. super();
  19965. this.isUniformsGroup = true;
  19966. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  19967. this.name = '';
  19968. this.usage = StaticDrawUsage;
  19969. this.uniforms = [];
  19970. }
  19971. add( uniform ) {
  19972. this.uniforms.push( uniform );
  19973. return this;
  19974. }
  19975. remove( uniform ) {
  19976. const index = this.uniforms.indexOf( uniform );
  19977. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  19978. return this;
  19979. }
  19980. setName( name ) {
  19981. this.name = name;
  19982. return this;
  19983. }
  19984. setUsage( value ) {
  19985. this.usage = value;
  19986. return this;
  19987. }
  19988. dispose() {
  19989. this.dispatchEvent( { type: 'dispose' } );
  19990. return this;
  19991. }
  19992. copy( source ) {
  19993. this.name = source.name;
  19994. this.usage = source.usage;
  19995. const uniformsSource = source.uniforms;
  19996. this.uniforms.length = 0;
  19997. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  19998. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  19999. for ( let j = 0; j < uniforms.length; j ++ ) {
  20000. this.uniforms.push( uniforms[ j ].clone() );
  20001. }
  20002. }
  20003. return this;
  20004. }
  20005. clone() {
  20006. return new this.constructor().copy( this );
  20007. }
  20008. };
  20009. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20010. constructor( array, stride, meshPerAttribute = 1 ) {
  20011. super( array, stride );
  20012. this.isInstancedInterleavedBuffer = true;
  20013. this.meshPerAttribute = meshPerAttribute;
  20014. }
  20015. copy( source ) {
  20016. super.copy( source );
  20017. this.meshPerAttribute = source.meshPerAttribute;
  20018. return this;
  20019. }
  20020. clone( data ) {
  20021. const ib = super.clone( data );
  20022. ib.meshPerAttribute = this.meshPerAttribute;
  20023. return ib;
  20024. }
  20025. toJSON( data ) {
  20026. const json = super.toJSON( data );
  20027. json.isInstancedInterleavedBuffer = true;
  20028. json.meshPerAttribute = this.meshPerAttribute;
  20029. return json;
  20030. }
  20031. }
  20032. class GLBufferAttribute {
  20033. constructor( buffer, type, itemSize, elementSize, count ) {
  20034. this.isGLBufferAttribute = true;
  20035. this.name = '';
  20036. this.buffer = buffer;
  20037. this.type = type;
  20038. this.itemSize = itemSize;
  20039. this.elementSize = elementSize;
  20040. this.count = count;
  20041. this.version = 0;
  20042. }
  20043. set needsUpdate( value ) {
  20044. if ( value === true ) this.version ++;
  20045. }
  20046. setBuffer( buffer ) {
  20047. this.buffer = buffer;
  20048. return this;
  20049. }
  20050. setType( type, elementSize ) {
  20051. this.type = type;
  20052. this.elementSize = elementSize;
  20053. return this;
  20054. }
  20055. setItemSize( itemSize ) {
  20056. this.itemSize = itemSize;
  20057. return this;
  20058. }
  20059. setCount( count ) {
  20060. this.count = count;
  20061. return this;
  20062. }
  20063. }
  20064. const _matrix = /*@__PURE__*/ new Matrix4();
  20065. class Raycaster {
  20066. constructor( origin, direction, near = 0, far = Infinity ) {
  20067. this.ray = new Ray( origin, direction );
  20068. // direction is assumed to be normalized (for accurate distance calculations)
  20069. this.near = near;
  20070. this.far = far;
  20071. this.camera = null;
  20072. this.layers = new Layers();
  20073. this.params = {
  20074. Mesh: {},
  20075. Line: { threshold: 1 },
  20076. LOD: {},
  20077. Points: { threshold: 1 },
  20078. Sprite: {}
  20079. };
  20080. }
  20081. set( origin, direction ) {
  20082. // direction is assumed to be normalized (for accurate distance calculations)
  20083. this.ray.set( origin, direction );
  20084. }
  20085. setFromCamera( coords, camera ) {
  20086. if ( camera.isPerspectiveCamera ) {
  20087. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20088. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20089. this.camera = camera;
  20090. } else if ( camera.isOrthographicCamera ) {
  20091. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20092. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20093. this.camera = camera;
  20094. } else {
  20095. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20096. }
  20097. }
  20098. setFromXRController( controller ) {
  20099. _matrix.identity().extractRotation( controller.matrixWorld );
  20100. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20101. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20102. return this;
  20103. }
  20104. intersectObject( object, recursive = true, intersects = [] ) {
  20105. intersect( object, this, intersects, recursive );
  20106. intersects.sort( ascSort );
  20107. return intersects;
  20108. }
  20109. intersectObjects( objects, recursive = true, intersects = [] ) {
  20110. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20111. intersect( objects[ i ], this, intersects, recursive );
  20112. }
  20113. intersects.sort( ascSort );
  20114. return intersects;
  20115. }
  20116. }
  20117. function ascSort( a, b ) {
  20118. return a.distance - b.distance;
  20119. }
  20120. function intersect( object, raycaster, intersects, recursive ) {
  20121. let propagate = true;
  20122. if ( object.layers.test( raycaster.layers ) ) {
  20123. const result = object.raycast( raycaster, intersects );
  20124. if ( result === false ) propagate = false;
  20125. }
  20126. if ( propagate === true && recursive === true ) {
  20127. const children = object.children;
  20128. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20129. intersect( children[ i ], raycaster, intersects, true );
  20130. }
  20131. }
  20132. }
  20133. /**
  20134. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20135. *
  20136. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20137. * theta (the azimuthal angle) is measured from the positive z-axis.
  20138. */
  20139. class Spherical {
  20140. constructor( radius = 1, phi = 0, theta = 0 ) {
  20141. this.radius = radius;
  20142. this.phi = phi; // polar angle
  20143. this.theta = theta; // azimuthal angle
  20144. return this;
  20145. }
  20146. set( radius, phi, theta ) {
  20147. this.radius = radius;
  20148. this.phi = phi;
  20149. this.theta = theta;
  20150. return this;
  20151. }
  20152. copy( other ) {
  20153. this.radius = other.radius;
  20154. this.phi = other.phi;
  20155. this.theta = other.theta;
  20156. return this;
  20157. }
  20158. // restrict phi to be between EPS and PI-EPS
  20159. makeSafe() {
  20160. const EPS = 0.000001;
  20161. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20162. return this;
  20163. }
  20164. setFromVector3( v ) {
  20165. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20166. }
  20167. setFromCartesianCoords( x, y, z ) {
  20168. this.radius = Math.sqrt( x * x + y * y + z * z );
  20169. if ( this.radius === 0 ) {
  20170. this.theta = 0;
  20171. this.phi = 0;
  20172. } else {
  20173. this.theta = Math.atan2( x, z );
  20174. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20175. }
  20176. return this;
  20177. }
  20178. clone() {
  20179. return new this.constructor().copy( this );
  20180. }
  20181. }
  20182. /**
  20183. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20184. */
  20185. class Cylindrical {
  20186. constructor( radius = 1, theta = 0, y = 0 ) {
  20187. this.radius = radius; // distance from the origin to a point in the x-z plane
  20188. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20189. this.y = y; // height above the x-z plane
  20190. return this;
  20191. }
  20192. set( radius, theta, y ) {
  20193. this.radius = radius;
  20194. this.theta = theta;
  20195. this.y = y;
  20196. return this;
  20197. }
  20198. copy( other ) {
  20199. this.radius = other.radius;
  20200. this.theta = other.theta;
  20201. this.y = other.y;
  20202. return this;
  20203. }
  20204. setFromVector3( v ) {
  20205. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20206. }
  20207. setFromCartesianCoords( x, y, z ) {
  20208. this.radius = Math.sqrt( x * x + z * z );
  20209. this.theta = Math.atan2( x, z );
  20210. this.y = y;
  20211. return this;
  20212. }
  20213. clone() {
  20214. return new this.constructor().copy( this );
  20215. }
  20216. }
  20217. class Matrix2 {
  20218. constructor( n11, n12, n21, n22 ) {
  20219. Matrix2.prototype.isMatrix2 = true;
  20220. this.elements = [
  20221. 1, 0,
  20222. 0, 1,
  20223. ];
  20224. if ( n11 !== undefined ) {
  20225. this.set( n11, n12, n21, n22 );
  20226. }
  20227. }
  20228. identity() {
  20229. this.set(
  20230. 1, 0,
  20231. 0, 1,
  20232. );
  20233. return this;
  20234. }
  20235. fromArray( array, offset = 0 ) {
  20236. for ( let i = 0; i < 4; i ++ ) {
  20237. this.elements[ i ] = array[ i + offset ];
  20238. }
  20239. return this;
  20240. }
  20241. set( n11, n12, n21, n22 ) {
  20242. const te = this.elements;
  20243. te[ 0 ] = n11; te[ 2 ] = n12;
  20244. te[ 1 ] = n21; te[ 3 ] = n22;
  20245. return this;
  20246. }
  20247. }
  20248. const _vector$4 = /*@__PURE__*/ new Vector2();
  20249. class Box2 {
  20250. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20251. this.isBox2 = true;
  20252. this.min = min;
  20253. this.max = max;
  20254. }
  20255. set( min, max ) {
  20256. this.min.copy( min );
  20257. this.max.copy( max );
  20258. return this;
  20259. }
  20260. setFromPoints( points ) {
  20261. this.makeEmpty();
  20262. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20263. this.expandByPoint( points[ i ] );
  20264. }
  20265. return this;
  20266. }
  20267. setFromCenterAndSize( center, size ) {
  20268. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20269. this.min.copy( center ).sub( halfSize );
  20270. this.max.copy( center ).add( halfSize );
  20271. return this;
  20272. }
  20273. clone() {
  20274. return new this.constructor().copy( this );
  20275. }
  20276. copy( box ) {
  20277. this.min.copy( box.min );
  20278. this.max.copy( box.max );
  20279. return this;
  20280. }
  20281. makeEmpty() {
  20282. this.min.x = this.min.y = + Infinity;
  20283. this.max.x = this.max.y = - Infinity;
  20284. return this;
  20285. }
  20286. isEmpty() {
  20287. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20288. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20289. }
  20290. getCenter( target ) {
  20291. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20292. }
  20293. getSize( target ) {
  20294. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20295. }
  20296. expandByPoint( point ) {
  20297. this.min.min( point );
  20298. this.max.max( point );
  20299. return this;
  20300. }
  20301. expandByVector( vector ) {
  20302. this.min.sub( vector );
  20303. this.max.add( vector );
  20304. return this;
  20305. }
  20306. expandByScalar( scalar ) {
  20307. this.min.addScalar( - scalar );
  20308. this.max.addScalar( scalar );
  20309. return this;
  20310. }
  20311. containsPoint( point ) {
  20312. return point.x >= this.min.x && point.x <= this.max.x &&
  20313. point.y >= this.min.y && point.y <= this.max.y;
  20314. }
  20315. containsBox( box ) {
  20316. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20317. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20318. }
  20319. getParameter( point, target ) {
  20320. // This can potentially have a divide by zero if the box
  20321. // has a size dimension of 0.
  20322. return target.set(
  20323. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20324. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20325. );
  20326. }
  20327. intersectsBox( box ) {
  20328. // using 4 splitting planes to rule out intersections
  20329. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20330. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20331. }
  20332. clampPoint( point, target ) {
  20333. return target.copy( point ).clamp( this.min, this.max );
  20334. }
  20335. distanceToPoint( point ) {
  20336. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20337. }
  20338. intersect( box ) {
  20339. this.min.max( box.min );
  20340. this.max.min( box.max );
  20341. if ( this.isEmpty() ) this.makeEmpty();
  20342. return this;
  20343. }
  20344. union( box ) {
  20345. this.min.min( box.min );
  20346. this.max.max( box.max );
  20347. return this;
  20348. }
  20349. translate( offset ) {
  20350. this.min.add( offset );
  20351. this.max.add( offset );
  20352. return this;
  20353. }
  20354. equals( box ) {
  20355. return box.min.equals( this.min ) && box.max.equals( this.max );
  20356. }
  20357. }
  20358. const _startP = /*@__PURE__*/ new Vector3();
  20359. const _startEnd = /*@__PURE__*/ new Vector3();
  20360. class Line3 {
  20361. constructor( start = new Vector3(), end = new Vector3() ) {
  20362. this.start = start;
  20363. this.end = end;
  20364. }
  20365. set( start, end ) {
  20366. this.start.copy( start );
  20367. this.end.copy( end );
  20368. return this;
  20369. }
  20370. copy( line ) {
  20371. this.start.copy( line.start );
  20372. this.end.copy( line.end );
  20373. return this;
  20374. }
  20375. getCenter( target ) {
  20376. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20377. }
  20378. delta( target ) {
  20379. return target.subVectors( this.end, this.start );
  20380. }
  20381. distanceSq() {
  20382. return this.start.distanceToSquared( this.end );
  20383. }
  20384. distance() {
  20385. return this.start.distanceTo( this.end );
  20386. }
  20387. at( t, target ) {
  20388. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20389. }
  20390. closestPointToPointParameter( point, clampToLine ) {
  20391. _startP.subVectors( point, this.start );
  20392. _startEnd.subVectors( this.end, this.start );
  20393. const startEnd2 = _startEnd.dot( _startEnd );
  20394. const startEnd_startP = _startEnd.dot( _startP );
  20395. let t = startEnd_startP / startEnd2;
  20396. if ( clampToLine ) {
  20397. t = clamp$1( t, 0, 1 );
  20398. }
  20399. return t;
  20400. }
  20401. closestPointToPoint( point, clampToLine, target ) {
  20402. const t = this.closestPointToPointParameter( point, clampToLine );
  20403. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20404. }
  20405. applyMatrix4( matrix ) {
  20406. this.start.applyMatrix4( matrix );
  20407. this.end.applyMatrix4( matrix );
  20408. return this;
  20409. }
  20410. equals( line ) {
  20411. return line.start.equals( this.start ) && line.end.equals( this.end );
  20412. }
  20413. clone() {
  20414. return new this.constructor().copy( this );
  20415. }
  20416. }
  20417. const _vector$3 = /*@__PURE__*/ new Vector3();
  20418. class SpotLightHelper extends Object3D {
  20419. constructor( light, color ) {
  20420. super();
  20421. this.light = light;
  20422. this.matrixAutoUpdate = false;
  20423. this.color = color;
  20424. this.type = 'SpotLightHelper';
  20425. const geometry = new BufferGeometry();
  20426. const positions = [
  20427. 0, 0, 0, 0, 0, 1,
  20428. 0, 0, 0, 1, 0, 1,
  20429. 0, 0, 0, - 1, 0, 1,
  20430. 0, 0, 0, 0, 1, 1,
  20431. 0, 0, 0, 0, - 1, 1
  20432. ];
  20433. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20434. const p1 = ( i / l ) * Math.PI * 2;
  20435. const p2 = ( j / l ) * Math.PI * 2;
  20436. positions.push(
  20437. Math.cos( p1 ), Math.sin( p1 ), 1,
  20438. Math.cos( p2 ), Math.sin( p2 ), 1
  20439. );
  20440. }
  20441. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20442. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20443. this.cone = new LineSegments( geometry, material );
  20444. this.add( this.cone );
  20445. this.update();
  20446. }
  20447. dispose() {
  20448. this.cone.geometry.dispose();
  20449. this.cone.material.dispose();
  20450. }
  20451. update() {
  20452. this.light.updateWorldMatrix( true, false );
  20453. this.light.target.updateWorldMatrix( true, false );
  20454. // update the local matrix based on the parent and light target transforms
  20455. if ( this.parent ) {
  20456. this.parent.updateWorldMatrix( true );
  20457. this.matrix
  20458. .copy( this.parent.matrixWorld )
  20459. .invert()
  20460. .multiply( this.light.matrixWorld );
  20461. } else {
  20462. this.matrix.copy( this.light.matrixWorld );
  20463. }
  20464. this.matrixWorld.copy( this.light.matrixWorld );
  20465. const coneLength = this.light.distance ? this.light.distance : 1000;
  20466. const coneWidth = coneLength * Math.tan( this.light.angle );
  20467. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20468. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20469. this.cone.lookAt( _vector$3 );
  20470. if ( this.color !== undefined ) {
  20471. this.cone.material.color.set( this.color );
  20472. } else {
  20473. this.cone.material.color.copy( this.light.color );
  20474. }
  20475. }
  20476. }
  20477. const _vector$2 = /*@__PURE__*/ new Vector3();
  20478. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20479. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20480. class SkeletonHelper extends LineSegments {
  20481. constructor( object ) {
  20482. const bones = getBoneList( object );
  20483. const geometry = new BufferGeometry();
  20484. const vertices = [];
  20485. const colors = [];
  20486. const color1 = new Color( 0, 0, 1 );
  20487. const color2 = new Color( 0, 1, 0 );
  20488. for ( let i = 0; i < bones.length; i ++ ) {
  20489. const bone = bones[ i ];
  20490. if ( bone.parent && bone.parent.isBone ) {
  20491. vertices.push( 0, 0, 0 );
  20492. vertices.push( 0, 0, 0 );
  20493. colors.push( color1.r, color1.g, color1.b );
  20494. colors.push( color2.r, color2.g, color2.b );
  20495. }
  20496. }
  20497. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20498. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20499. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20500. super( geometry, material );
  20501. this.isSkeletonHelper = true;
  20502. this.type = 'SkeletonHelper';
  20503. this.root = object;
  20504. this.bones = bones;
  20505. this.matrix = object.matrixWorld;
  20506. this.matrixAutoUpdate = false;
  20507. }
  20508. updateMatrixWorld( force ) {
  20509. const bones = this.bones;
  20510. const geometry = this.geometry;
  20511. const position = geometry.getAttribute( 'position' );
  20512. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20513. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20514. const bone = bones[ i ];
  20515. if ( bone.parent && bone.parent.isBone ) {
  20516. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20517. _vector$2.setFromMatrixPosition( _boneMatrix );
  20518. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20519. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20520. _vector$2.setFromMatrixPosition( _boneMatrix );
  20521. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20522. j += 2;
  20523. }
  20524. }
  20525. geometry.getAttribute( 'position' ).needsUpdate = true;
  20526. super.updateMatrixWorld( force );
  20527. }
  20528. dispose() {
  20529. this.geometry.dispose();
  20530. this.material.dispose();
  20531. }
  20532. }
  20533. function getBoneList( object ) {
  20534. const boneList = [];
  20535. if ( object.isBone === true ) {
  20536. boneList.push( object );
  20537. }
  20538. for ( let i = 0; i < object.children.length; i ++ ) {
  20539. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20540. }
  20541. return boneList;
  20542. }
  20543. class PointLightHelper extends Mesh {
  20544. constructor( light, sphereSize, color ) {
  20545. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20546. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20547. super( geometry, material );
  20548. this.light = light;
  20549. this.color = color;
  20550. this.type = 'PointLightHelper';
  20551. this.matrix = this.light.matrixWorld;
  20552. this.matrixAutoUpdate = false;
  20553. this.update();
  20554. /*
  20555. // TODO: delete this comment?
  20556. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20557. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20558. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20559. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20560. const d = light.distance;
  20561. if ( d === 0.0 ) {
  20562. this.lightDistance.visible = false;
  20563. } else {
  20564. this.lightDistance.scale.set( d, d, d );
  20565. }
  20566. this.add( this.lightDistance );
  20567. */
  20568. }
  20569. dispose() {
  20570. this.geometry.dispose();
  20571. this.material.dispose();
  20572. }
  20573. update() {
  20574. this.light.updateWorldMatrix( true, false );
  20575. if ( this.color !== undefined ) {
  20576. this.material.color.set( this.color );
  20577. } else {
  20578. this.material.color.copy( this.light.color );
  20579. }
  20580. /*
  20581. const d = this.light.distance;
  20582. if ( d === 0.0 ) {
  20583. this.lightDistance.visible = false;
  20584. } else {
  20585. this.lightDistance.visible = true;
  20586. this.lightDistance.scale.set( d, d, d );
  20587. }
  20588. */
  20589. }
  20590. }
  20591. const _vector$1 = /*@__PURE__*/ new Vector3();
  20592. const _color1 = /*@__PURE__*/ new Color();
  20593. const _color2 = /*@__PURE__*/ new Color();
  20594. class HemisphereLightHelper extends Object3D {
  20595. constructor( light, size, color ) {
  20596. super();
  20597. this.light = light;
  20598. this.matrix = light.matrixWorld;
  20599. this.matrixAutoUpdate = false;
  20600. this.color = color;
  20601. this.type = 'HemisphereLightHelper';
  20602. const geometry = new OctahedronGeometry( size );
  20603. geometry.rotateY( Math.PI * 0.5 );
  20604. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20605. if ( this.color === undefined ) this.material.vertexColors = true;
  20606. const position = geometry.getAttribute( 'position' );
  20607. const colors = new Float32Array( position.count * 3 );
  20608. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20609. this.add( new Mesh( geometry, this.material ) );
  20610. this.update();
  20611. }
  20612. dispose() {
  20613. this.children[ 0 ].geometry.dispose();
  20614. this.children[ 0 ].material.dispose();
  20615. }
  20616. update() {
  20617. const mesh = this.children[ 0 ];
  20618. if ( this.color !== undefined ) {
  20619. this.material.color.set( this.color );
  20620. } else {
  20621. const colors = mesh.geometry.getAttribute( 'color' );
  20622. _color1.copy( this.light.color );
  20623. _color2.copy( this.light.groundColor );
  20624. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20625. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20626. colors.setXYZ( i, color.r, color.g, color.b );
  20627. }
  20628. colors.needsUpdate = true;
  20629. }
  20630. this.light.updateWorldMatrix( true, false );
  20631. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20632. }
  20633. }
  20634. class GridHelper extends LineSegments {
  20635. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20636. color1 = new Color( color1 );
  20637. color2 = new Color( color2 );
  20638. const center = divisions / 2;
  20639. const step = size / divisions;
  20640. const halfSize = size / 2;
  20641. const vertices = [], colors = [];
  20642. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20643. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20644. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20645. const color = i === center ? color1 : color2;
  20646. color.toArray( colors, j ); j += 3;
  20647. color.toArray( colors, j ); j += 3;
  20648. color.toArray( colors, j ); j += 3;
  20649. color.toArray( colors, j ); j += 3;
  20650. }
  20651. const geometry = new BufferGeometry();
  20652. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20653. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20654. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20655. super( geometry, material );
  20656. this.type = 'GridHelper';
  20657. }
  20658. dispose() {
  20659. this.geometry.dispose();
  20660. this.material.dispose();
  20661. }
  20662. }
  20663. class PolarGridHelper extends LineSegments {
  20664. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20665. color1 = new Color( color1 );
  20666. color2 = new Color( color2 );
  20667. const vertices = [];
  20668. const colors = [];
  20669. // create the sectors
  20670. if ( sectors > 1 ) {
  20671. for ( let i = 0; i < sectors; i ++ ) {
  20672. const v = ( i / sectors ) * ( Math.PI * 2 );
  20673. const x = Math.sin( v ) * radius;
  20674. const z = Math.cos( v ) * radius;
  20675. vertices.push( 0, 0, 0 );
  20676. vertices.push( x, 0, z );
  20677. const color = ( i & 1 ) ? color1 : color2;
  20678. colors.push( color.r, color.g, color.b );
  20679. colors.push( color.r, color.g, color.b );
  20680. }
  20681. }
  20682. // create the rings
  20683. for ( let i = 0; i < rings; i ++ ) {
  20684. const color = ( i & 1 ) ? color1 : color2;
  20685. const r = radius - ( radius / rings * i );
  20686. for ( let j = 0; j < divisions; j ++ ) {
  20687. // first vertex
  20688. let v = ( j / divisions ) * ( Math.PI * 2 );
  20689. let x = Math.sin( v ) * r;
  20690. let z = Math.cos( v ) * r;
  20691. vertices.push( x, 0, z );
  20692. colors.push( color.r, color.g, color.b );
  20693. // second vertex
  20694. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20695. x = Math.sin( v ) * r;
  20696. z = Math.cos( v ) * r;
  20697. vertices.push( x, 0, z );
  20698. colors.push( color.r, color.g, color.b );
  20699. }
  20700. }
  20701. const geometry = new BufferGeometry();
  20702. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20703. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20704. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20705. super( geometry, material );
  20706. this.type = 'PolarGridHelper';
  20707. }
  20708. dispose() {
  20709. this.geometry.dispose();
  20710. this.material.dispose();
  20711. }
  20712. }
  20713. const _v1 = /*@__PURE__*/ new Vector3();
  20714. const _v2 = /*@__PURE__*/ new Vector3();
  20715. const _v3 = /*@__PURE__*/ new Vector3();
  20716. class DirectionalLightHelper extends Object3D {
  20717. constructor( light, size, color ) {
  20718. super();
  20719. this.light = light;
  20720. this.matrix = light.matrixWorld;
  20721. this.matrixAutoUpdate = false;
  20722. this.color = color;
  20723. this.type = 'DirectionalLightHelper';
  20724. if ( size === undefined ) size = 1;
  20725. let geometry = new BufferGeometry();
  20726. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20727. - size, size, 0,
  20728. size, size, 0,
  20729. size, - size, 0,
  20730. - size, - size, 0,
  20731. - size, size, 0
  20732. ], 3 ) );
  20733. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20734. this.lightPlane = new Line( geometry, material );
  20735. this.add( this.lightPlane );
  20736. geometry = new BufferGeometry();
  20737. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20738. this.targetLine = new Line( geometry, material );
  20739. this.add( this.targetLine );
  20740. this.update();
  20741. }
  20742. dispose() {
  20743. this.lightPlane.geometry.dispose();
  20744. this.lightPlane.material.dispose();
  20745. this.targetLine.geometry.dispose();
  20746. this.targetLine.material.dispose();
  20747. }
  20748. update() {
  20749. this.light.updateWorldMatrix( true, false );
  20750. this.light.target.updateWorldMatrix( true, false );
  20751. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20752. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20753. _v3.subVectors( _v2, _v1 );
  20754. this.lightPlane.lookAt( _v2 );
  20755. if ( this.color !== undefined ) {
  20756. this.lightPlane.material.color.set( this.color );
  20757. this.targetLine.material.color.set( this.color );
  20758. } else {
  20759. this.lightPlane.material.color.copy( this.light.color );
  20760. this.targetLine.material.color.copy( this.light.color );
  20761. }
  20762. this.targetLine.lookAt( _v2 );
  20763. this.targetLine.scale.z = _v3.length();
  20764. }
  20765. }
  20766. const _vector = /*@__PURE__*/ new Vector3();
  20767. const _camera$1 = /*@__PURE__*/ new Camera();
  20768. /**
  20769. * - shows frustum, line of sight and up of the camera
  20770. * - suitable for fast updates
  20771. * - based on frustum visualization in lightgl.js shadowmap example
  20772. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20773. */
  20774. class CameraHelper extends LineSegments {
  20775. constructor( camera ) {
  20776. const geometry = new BufferGeometry();
  20777. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20778. const vertices = [];
  20779. const colors = [];
  20780. const pointMap = {};
  20781. // near
  20782. addLine( 'n1', 'n2' );
  20783. addLine( 'n2', 'n4' );
  20784. addLine( 'n4', 'n3' );
  20785. addLine( 'n3', 'n1' );
  20786. // far
  20787. addLine( 'f1', 'f2' );
  20788. addLine( 'f2', 'f4' );
  20789. addLine( 'f4', 'f3' );
  20790. addLine( 'f3', 'f1' );
  20791. // sides
  20792. addLine( 'n1', 'f1' );
  20793. addLine( 'n2', 'f2' );
  20794. addLine( 'n3', 'f3' );
  20795. addLine( 'n4', 'f4' );
  20796. // cone
  20797. addLine( 'p', 'n1' );
  20798. addLine( 'p', 'n2' );
  20799. addLine( 'p', 'n3' );
  20800. addLine( 'p', 'n4' );
  20801. // up
  20802. addLine( 'u1', 'u2' );
  20803. addLine( 'u2', 'u3' );
  20804. addLine( 'u3', 'u1' );
  20805. // target
  20806. addLine( 'c', 't' );
  20807. addLine( 'p', 'c' );
  20808. // cross
  20809. addLine( 'cn1', 'cn2' );
  20810. addLine( 'cn3', 'cn4' );
  20811. addLine( 'cf1', 'cf2' );
  20812. addLine( 'cf3', 'cf4' );
  20813. function addLine( a, b ) {
  20814. addPoint( a );
  20815. addPoint( b );
  20816. }
  20817. function addPoint( id ) {
  20818. vertices.push( 0, 0, 0 );
  20819. colors.push( 0, 0, 0 );
  20820. if ( pointMap[ id ] === undefined ) {
  20821. pointMap[ id ] = [];
  20822. }
  20823. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20824. }
  20825. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20826. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20827. super( geometry, material );
  20828. this.type = 'CameraHelper';
  20829. this.camera = camera;
  20830. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20831. this.matrix = camera.matrixWorld;
  20832. this.matrixAutoUpdate = false;
  20833. this.pointMap = pointMap;
  20834. this.update();
  20835. // colors
  20836. const colorFrustum = new Color( 0xffaa00 );
  20837. const colorCone = new Color( 0xff0000 );
  20838. const colorUp = new Color( 0x00aaff );
  20839. const colorTarget = new Color( 0xffffff );
  20840. const colorCross = new Color( 0x333333 );
  20841. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20842. }
  20843. setColors( frustum, cone, up, target, cross ) {
  20844. const geometry = this.geometry;
  20845. const colorAttribute = geometry.getAttribute( 'color' );
  20846. // near
  20847. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20848. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20849. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20850. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20851. // far
  20852. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20853. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20854. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20855. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20856. // sides
  20857. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20858. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20859. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20860. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20861. // cone
  20862. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20863. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20864. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20865. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20866. // up
  20867. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20868. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20869. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20870. // target
  20871. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20872. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20873. // cross
  20874. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20875. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20876. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20877. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20878. colorAttribute.needsUpdate = true;
  20879. }
  20880. update() {
  20881. const geometry = this.geometry;
  20882. const pointMap = this.pointMap;
  20883. const w = 1, h = 1;
  20884. // we need just camera projection matrix inverse
  20885. // world matrix must be identity
  20886. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20887. // center / target
  20888. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20889. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20890. // near
  20891. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20892. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20893. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20894. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20895. // far
  20896. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20897. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20898. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20899. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20900. // up
  20901. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20902. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20903. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20904. // cross
  20905. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20906. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20907. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20908. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20909. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20910. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20911. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20912. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20913. geometry.getAttribute( 'position' ).needsUpdate = true;
  20914. }
  20915. dispose() {
  20916. this.geometry.dispose();
  20917. this.material.dispose();
  20918. }
  20919. }
  20920. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20921. _vector.set( x, y, z ).unproject( camera );
  20922. const points = pointMap[ point ];
  20923. if ( points !== undefined ) {
  20924. const position = geometry.getAttribute( 'position' );
  20925. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20926. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20927. }
  20928. }
  20929. }
  20930. const _box = /*@__PURE__*/ new Box3();
  20931. class BoxHelper extends LineSegments {
  20932. constructor( object, color = 0xffff00 ) {
  20933. 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 ] );
  20934. const positions = new Float32Array( 8 * 3 );
  20935. const geometry = new BufferGeometry();
  20936. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20937. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20938. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20939. this.object = object;
  20940. this.type = 'BoxHelper';
  20941. this.matrixAutoUpdate = false;
  20942. this.update();
  20943. }
  20944. update( object ) {
  20945. if ( object !== undefined ) {
  20946. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20947. }
  20948. if ( this.object !== undefined ) {
  20949. _box.setFromObject( this.object );
  20950. }
  20951. if ( _box.isEmpty() ) return;
  20952. const min = _box.min;
  20953. const max = _box.max;
  20954. /*
  20955. 5____4
  20956. 1/___0/|
  20957. | 6__|_7
  20958. 2/___3/
  20959. 0: max.x, max.y, max.z
  20960. 1: min.x, max.y, max.z
  20961. 2: min.x, min.y, max.z
  20962. 3: max.x, min.y, max.z
  20963. 4: max.x, max.y, min.z
  20964. 5: min.x, max.y, min.z
  20965. 6: min.x, min.y, min.z
  20966. 7: max.x, min.y, min.z
  20967. */
  20968. const position = this.geometry.attributes.position;
  20969. const array = position.array;
  20970. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20971. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20972. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20973. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20974. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20975. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20976. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20977. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20978. position.needsUpdate = true;
  20979. this.geometry.computeBoundingSphere();
  20980. }
  20981. setFromObject( object ) {
  20982. this.object = object;
  20983. this.update();
  20984. return this;
  20985. }
  20986. copy( source, recursive ) {
  20987. super.copy( source, recursive );
  20988. this.object = source.object;
  20989. return this;
  20990. }
  20991. dispose() {
  20992. this.geometry.dispose();
  20993. this.material.dispose();
  20994. }
  20995. }
  20996. class Box3Helper extends LineSegments {
  20997. constructor( box, color = 0xffff00 ) {
  20998. 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 ] );
  20999. 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 ];
  21000. const geometry = new BufferGeometry();
  21001. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21002. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21003. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21004. this.box = box;
  21005. this.type = 'Box3Helper';
  21006. this.geometry.computeBoundingSphere();
  21007. }
  21008. updateMatrixWorld( force ) {
  21009. const box = this.box;
  21010. if ( box.isEmpty() ) return;
  21011. box.getCenter( this.position );
  21012. box.getSize( this.scale );
  21013. this.scale.multiplyScalar( 0.5 );
  21014. super.updateMatrixWorld( force );
  21015. }
  21016. dispose() {
  21017. this.geometry.dispose();
  21018. this.material.dispose();
  21019. }
  21020. }
  21021. class PlaneHelper extends Line {
  21022. constructor( plane, size = 1, hex = 0xffff00 ) {
  21023. const color = hex;
  21024. 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 ];
  21025. const geometry = new BufferGeometry();
  21026. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21027. geometry.computeBoundingSphere();
  21028. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21029. this.type = 'PlaneHelper';
  21030. this.plane = plane;
  21031. this.size = size;
  21032. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21033. const geometry2 = new BufferGeometry();
  21034. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21035. geometry2.computeBoundingSphere();
  21036. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21037. }
  21038. updateMatrixWorld( force ) {
  21039. this.position.set( 0, 0, 0 );
  21040. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21041. this.lookAt( this.plane.normal );
  21042. this.translateZ( - this.plane.constant );
  21043. super.updateMatrixWorld( force );
  21044. }
  21045. dispose() {
  21046. this.geometry.dispose();
  21047. this.material.dispose();
  21048. this.children[ 0 ].geometry.dispose();
  21049. this.children[ 0 ].material.dispose();
  21050. }
  21051. }
  21052. const _axis = /*@__PURE__*/ new Vector3();
  21053. let _lineGeometry, _coneGeometry;
  21054. class ArrowHelper extends Object3D {
  21055. // dir is assumed to be normalized
  21056. 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 ) {
  21057. super();
  21058. this.type = 'ArrowHelper';
  21059. if ( _lineGeometry === undefined ) {
  21060. _lineGeometry = new BufferGeometry();
  21061. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21062. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21063. _coneGeometry.translate( 0, - 0.5, 0 );
  21064. }
  21065. this.position.copy( origin );
  21066. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21067. this.line.matrixAutoUpdate = false;
  21068. this.add( this.line );
  21069. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21070. this.cone.matrixAutoUpdate = false;
  21071. this.add( this.cone );
  21072. this.setDirection( dir );
  21073. this.setLength( length, headLength, headWidth );
  21074. }
  21075. setDirection( dir ) {
  21076. // dir is assumed to be normalized
  21077. if ( dir.y > 0.99999 ) {
  21078. this.quaternion.set( 0, 0, 0, 1 );
  21079. } else if ( dir.y < - 0.99999 ) {
  21080. this.quaternion.set( 1, 0, 0, 0 );
  21081. } else {
  21082. _axis.set( dir.z, 0, - dir.x ).normalize();
  21083. const radians = Math.acos( dir.y );
  21084. this.quaternion.setFromAxisAngle( _axis, radians );
  21085. }
  21086. }
  21087. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21088. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21089. this.line.updateMatrix();
  21090. this.cone.scale.set( headWidth, headLength, headWidth );
  21091. this.cone.position.y = length;
  21092. this.cone.updateMatrix();
  21093. }
  21094. setColor( color ) {
  21095. this.line.material.color.set( color );
  21096. this.cone.material.color.set( color );
  21097. }
  21098. copy( source ) {
  21099. super.copy( source, false );
  21100. this.line.copy( source.line );
  21101. this.cone.copy( source.cone );
  21102. return this;
  21103. }
  21104. dispose() {
  21105. this.line.geometry.dispose();
  21106. this.line.material.dispose();
  21107. this.cone.geometry.dispose();
  21108. this.cone.material.dispose();
  21109. }
  21110. }
  21111. class AxesHelper extends LineSegments {
  21112. constructor( size = 1 ) {
  21113. const vertices = [
  21114. 0, 0, 0, size, 0, 0,
  21115. 0, 0, 0, 0, size, 0,
  21116. 0, 0, 0, 0, 0, size
  21117. ];
  21118. const colors = [
  21119. 1, 0, 0, 1, 0.6, 0,
  21120. 0, 1, 0, 0.6, 1, 0,
  21121. 0, 0, 1, 0, 0.6, 1
  21122. ];
  21123. const geometry = new BufferGeometry();
  21124. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21125. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21126. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21127. super( geometry, material );
  21128. this.type = 'AxesHelper';
  21129. }
  21130. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21131. const color = new Color();
  21132. const array = this.geometry.attributes.color.array;
  21133. color.set( xAxisColor );
  21134. color.toArray( array, 0 );
  21135. color.toArray( array, 3 );
  21136. color.set( yAxisColor );
  21137. color.toArray( array, 6 );
  21138. color.toArray( array, 9 );
  21139. color.set( zAxisColor );
  21140. color.toArray( array, 12 );
  21141. color.toArray( array, 15 );
  21142. this.geometry.attributes.color.needsUpdate = true;
  21143. return this;
  21144. }
  21145. dispose() {
  21146. this.geometry.dispose();
  21147. this.material.dispose();
  21148. }
  21149. }
  21150. class ShapePath {
  21151. constructor() {
  21152. this.type = 'ShapePath';
  21153. this.color = new Color();
  21154. this.subPaths = [];
  21155. this.currentPath = null;
  21156. }
  21157. moveTo( x, y ) {
  21158. this.currentPath = new Path();
  21159. this.subPaths.push( this.currentPath );
  21160. this.currentPath.moveTo( x, y );
  21161. return this;
  21162. }
  21163. lineTo( x, y ) {
  21164. this.currentPath.lineTo( x, y );
  21165. return this;
  21166. }
  21167. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21168. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21169. return this;
  21170. }
  21171. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21172. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21173. return this;
  21174. }
  21175. splineThru( pts ) {
  21176. this.currentPath.splineThru( pts );
  21177. return this;
  21178. }
  21179. toShapes( isCCW ) {
  21180. function toShapesNoHoles( inSubpaths ) {
  21181. const shapes = [];
  21182. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21183. const tmpPath = inSubpaths[ i ];
  21184. const tmpShape = new Shape();
  21185. tmpShape.curves = tmpPath.curves;
  21186. shapes.push( tmpShape );
  21187. }
  21188. return shapes;
  21189. }
  21190. function isPointInsidePolygon( inPt, inPolygon ) {
  21191. const polyLen = inPolygon.length;
  21192. // inPt on polygon contour => immediate success or
  21193. // toggling of inside/outside at every single! intersection point of an edge
  21194. // with the horizontal line through inPt, left of inPt
  21195. // not counting lowerY endpoints of edges and whole edges on that line
  21196. let inside = false;
  21197. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21198. let edgeLowPt = inPolygon[ p ];
  21199. let edgeHighPt = inPolygon[ q ];
  21200. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21201. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21202. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21203. // not parallel
  21204. if ( edgeDy < 0 ) {
  21205. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21206. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21207. }
  21208. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21209. if ( inPt.y === edgeLowPt.y ) {
  21210. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21211. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21212. } else {
  21213. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21214. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21215. if ( perpEdge < 0 ) continue;
  21216. inside = ! inside; // true intersection left of inPt
  21217. }
  21218. } else {
  21219. // parallel or collinear
  21220. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21221. // edge lies on the same horizontal line as inPt
  21222. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21223. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21224. // continue;
  21225. }
  21226. }
  21227. return inside;
  21228. }
  21229. const isClockWise = ShapeUtils.isClockWise;
  21230. const subPaths = this.subPaths;
  21231. if ( subPaths.length === 0 ) return [];
  21232. let solid, tmpPath, tmpShape;
  21233. const shapes = [];
  21234. if ( subPaths.length === 1 ) {
  21235. tmpPath = subPaths[ 0 ];
  21236. tmpShape = new Shape();
  21237. tmpShape.curves = tmpPath.curves;
  21238. shapes.push( tmpShape );
  21239. return shapes;
  21240. }
  21241. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21242. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21243. // console.log("Holes first", holesFirst);
  21244. const betterShapeHoles = [];
  21245. const newShapes = [];
  21246. let newShapeHoles = [];
  21247. let mainIdx = 0;
  21248. let tmpPoints;
  21249. newShapes[ mainIdx ] = undefined;
  21250. newShapeHoles[ mainIdx ] = [];
  21251. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21252. tmpPath = subPaths[ i ];
  21253. tmpPoints = tmpPath.getPoints();
  21254. solid = isClockWise( tmpPoints );
  21255. solid = isCCW ? ! solid : solid;
  21256. if ( solid ) {
  21257. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21258. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21259. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21260. if ( holesFirst ) mainIdx ++;
  21261. newShapeHoles[ mainIdx ] = [];
  21262. //console.log('cw', i);
  21263. } else {
  21264. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21265. //console.log('ccw', i);
  21266. }
  21267. }
  21268. // only Holes? -> probably all Shapes with wrong orientation
  21269. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21270. if ( newShapes.length > 1 ) {
  21271. let ambiguous = false;
  21272. let toChange = 0;
  21273. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21274. betterShapeHoles[ sIdx ] = [];
  21275. }
  21276. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21277. const sho = newShapeHoles[ sIdx ];
  21278. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21279. const ho = sho[ hIdx ];
  21280. let hole_unassigned = true;
  21281. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21282. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21283. if ( sIdx !== s2Idx ) toChange ++;
  21284. if ( hole_unassigned ) {
  21285. hole_unassigned = false;
  21286. betterShapeHoles[ s2Idx ].push( ho );
  21287. } else {
  21288. ambiguous = true;
  21289. }
  21290. }
  21291. }
  21292. if ( hole_unassigned ) {
  21293. betterShapeHoles[ sIdx ].push( ho );
  21294. }
  21295. }
  21296. }
  21297. if ( toChange > 0 && ambiguous === false ) {
  21298. newShapeHoles = betterShapeHoles;
  21299. }
  21300. }
  21301. let tmpHoles;
  21302. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21303. tmpShape = newShapes[ i ].s;
  21304. shapes.push( tmpShape );
  21305. tmpHoles = newShapeHoles[ i ];
  21306. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21307. tmpShape.holes.push( tmpHoles[ j ].h );
  21308. }
  21309. }
  21310. //console.log("shape", shapes);
  21311. return shapes;
  21312. }
  21313. }
  21314. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21315. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21316. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21317. super( width, height, { ...options, count } );
  21318. this.isWebGLMultipleRenderTargets = true;
  21319. }
  21320. get texture() {
  21321. return this.textures;
  21322. }
  21323. }
  21324. if ( self.GPUShaderStage === undefined ) {
  21325. self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  21326. }
  21327. // statics
  21328. let isAvailable = navigator.gpu !== undefined;
  21329. if ( typeof window !== 'undefined' && isAvailable ) {
  21330. isAvailable = await navigator.gpu.requestAdapter();
  21331. }
  21332. class WebGPU {
  21333. static isAvailable() {
  21334. return Boolean( isAvailable );
  21335. }
  21336. static getStaticAdapter() {
  21337. return isAvailable;
  21338. }
  21339. static getErrorMessage() {
  21340. const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:blue">WebGPU</a> yet';
  21341. const element = document.createElement( 'div' );
  21342. element.id = 'webgpumessage';
  21343. element.style.fontFamily = 'monospace';
  21344. element.style.fontSize = '13px';
  21345. element.style.fontWeight = 'normal';
  21346. element.style.textAlign = 'center';
  21347. element.style.background = '#fff';
  21348. element.style.color = '#000';
  21349. element.style.padding = '1.5em';
  21350. element.style.maxWidth = '400px';
  21351. element.style.margin = '5em auto 0';
  21352. element.innerHTML = message;
  21353. return element;
  21354. }
  21355. }
  21356. class Animation {
  21357. constructor( nodes, info ) {
  21358. this.nodes = nodes;
  21359. this.info = info;
  21360. this.animationLoop = null;
  21361. this.requestId = null;
  21362. this._init();
  21363. }
  21364. _init() {
  21365. const update = ( time, frame ) => {
  21366. this.requestId = self.requestAnimationFrame( update );
  21367. if ( this.info.autoReset === true ) this.info.reset();
  21368. this.nodes.nodeFrame.update();
  21369. this.info.frame = this.nodes.nodeFrame.frameId;
  21370. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  21371. };
  21372. update();
  21373. }
  21374. dispose() {
  21375. self.cancelAnimationFrame( this.requestId );
  21376. this.requestId = null;
  21377. }
  21378. setAnimationLoop( callback ) {
  21379. this.animationLoop = callback;
  21380. }
  21381. }
  21382. class ChainMap {
  21383. constructor() {
  21384. this.weakMap = new WeakMap();
  21385. }
  21386. get( keys ) {
  21387. let map = this.weakMap;
  21388. for ( let i = 0; i < keys.length; i ++ ) {
  21389. map = map.get( keys[ i ] );
  21390. if ( map === undefined ) return undefined;
  21391. }
  21392. return map.get( keys[ keys.length - 1 ] );
  21393. }
  21394. set( keys, value ) {
  21395. let map = this.weakMap;
  21396. for ( let i = 0; i < keys.length; i ++ ) {
  21397. const key = keys[ i ];
  21398. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  21399. map = map.get( key );
  21400. }
  21401. return map.set( keys[ keys.length - 1 ], value );
  21402. }
  21403. delete( keys ) {
  21404. let map = this.weakMap;
  21405. for ( let i = 0; i < keys.length; i ++ ) {
  21406. map = map.get( keys[ i ] );
  21407. if ( map === undefined ) return false;
  21408. }
  21409. return map.delete( keys[ keys.length - 1 ] );
  21410. }
  21411. }
  21412. const _plane = /*@__PURE__*/ new Plane();
  21413. let _clippingContextVersion = 0;
  21414. class ClippingContext {
  21415. constructor() {
  21416. this.version = ++ _clippingContextVersion;
  21417. this.globalClippingCount = 0;
  21418. this.localClippingCount = 0;
  21419. this.localClippingEnabled = false;
  21420. this.localClipIntersection = false;
  21421. this.planes = [];
  21422. this.parentVersion = 0;
  21423. this.viewNormalMatrix = new Matrix3();
  21424. }
  21425. projectPlanes( source, offset ) {
  21426. const l = source.length;
  21427. const planes = this.planes;
  21428. for ( let i = 0; i < l; i ++ ) {
  21429. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21430. const v = planes[ offset + i ];
  21431. const normal = _plane.normal;
  21432. v.x = - normal.x;
  21433. v.y = - normal.y;
  21434. v.z = - normal.z;
  21435. v.w = _plane.constant;
  21436. }
  21437. }
  21438. updateGlobal( renderer, camera ) {
  21439. const rendererClippingPlanes = renderer.clippingPlanes;
  21440. this.viewMatrix = camera.matrixWorldInverse;
  21441. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21442. let update = false;
  21443. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  21444. const l = rendererClippingPlanes.length;
  21445. if ( l !== this.globalClippingCount ) {
  21446. const planes = [];
  21447. for ( let i = 0; i < l; i ++ ) {
  21448. planes.push( new Vector4() );
  21449. }
  21450. this.globalClippingCount = l;
  21451. this.planes = planes;
  21452. update = true;
  21453. }
  21454. this.projectPlanes( rendererClippingPlanes, 0 );
  21455. } else if ( this.globalClippingCount !== 0 ) {
  21456. this.globalClippingCount = 0;
  21457. this.planes = [];
  21458. update = true;
  21459. }
  21460. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  21461. this.localClippingEnabled = renderer.localClippingEnabled;
  21462. update = true;
  21463. }
  21464. if ( update ) this.version = _clippingContextVersion ++;
  21465. }
  21466. update( parent, material ) {
  21467. let update = false;
  21468. if ( this !== parent && parent.version !== this.parentVersion ) {
  21469. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  21470. this.localClippingEnabled = parent.localClippingEnabled;
  21471. this.planes = Array.from( parent.planes );
  21472. this.parentVersion = parent.version;
  21473. this.viewMatrix = parent.viewMatrix;
  21474. this.viewNormalMatrix = parent.viewNormalMatrix;
  21475. update = true;
  21476. }
  21477. if ( this.localClippingEnabled ) {
  21478. const localClippingPlanes = material.clippingPlanes;
  21479. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  21480. const l = localClippingPlanes.length;
  21481. const planes = this.planes;
  21482. const offset = this.globalClippingCount;
  21483. if ( update || l !== this.localClippingCount ) {
  21484. planes.length = offset + l;
  21485. for ( let i = 0; i < l; i ++ ) {
  21486. planes[ offset + i ] = new Vector4();
  21487. }
  21488. this.localClippingCount = l;
  21489. update = true;
  21490. }
  21491. this.projectPlanes( localClippingPlanes, offset );
  21492. } else if ( this.localClippingCount !== 0 ) {
  21493. this.localClippingCount = 0;
  21494. update = true;
  21495. }
  21496. if ( this.localClipIntersection !== material.clipIntersection ) {
  21497. this.localClipIntersection = material.clipIntersection;
  21498. update = true;
  21499. }
  21500. }
  21501. if ( update ) this.version = _clippingContextVersion ++;
  21502. }
  21503. }
  21504. let _id$7 = 0;
  21505. function getKeys( obj ) {
  21506. const keys = Object.keys( obj );
  21507. let proto = Object.getPrototypeOf( obj );
  21508. while ( proto ) {
  21509. const descriptors = Object.getOwnPropertyDescriptors( proto );
  21510. for ( const key in descriptors ) {
  21511. if ( descriptors[ key ] !== undefined ) {
  21512. const descriptor = descriptors[ key ];
  21513. if ( descriptor && typeof descriptor.get === 'function' ) {
  21514. keys.push( key );
  21515. }
  21516. }
  21517. }
  21518. proto = Object.getPrototypeOf( proto );
  21519. }
  21520. return keys;
  21521. }
  21522. class RenderObject {
  21523. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  21524. this._nodes = nodes;
  21525. this._geometries = geometries;
  21526. this.id = _id$7 ++;
  21527. this.renderer = renderer;
  21528. this.object = object;
  21529. this.material = material;
  21530. this.scene = scene;
  21531. this.camera = camera;
  21532. this.lightsNode = lightsNode;
  21533. this.context = renderContext;
  21534. this.geometry = object.geometry;
  21535. this.version = material.version;
  21536. this.drawRange = null;
  21537. this.attributes = null;
  21538. this.pipeline = null;
  21539. this.vertexBuffers = null;
  21540. this.updateClipping( renderContext.clippingContext );
  21541. this.clippingContextVersion = this.clippingContext.version;
  21542. this.initialNodesCacheKey = this.getNodesCacheKey();
  21543. this.initialCacheKey = this.getCacheKey();
  21544. this._nodeBuilderState = null;
  21545. this._bindings = null;
  21546. this.onDispose = null;
  21547. this.isRenderObject = true;
  21548. this.onMaterialDispose = () => {
  21549. this.dispose();
  21550. };
  21551. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21552. }
  21553. updateClipping( parent ) {
  21554. const material = this.material;
  21555. let clippingContext = this.clippingContext;
  21556. if ( Array.isArray( material.clippingPlanes ) ) {
  21557. if ( clippingContext === parent || ! clippingContext ) {
  21558. clippingContext = new ClippingContext();
  21559. this.clippingContext = clippingContext;
  21560. }
  21561. clippingContext.update( parent, material );
  21562. } else if ( this.clippingContext !== parent ) {
  21563. this.clippingContext = parent;
  21564. }
  21565. }
  21566. get clippingNeedsUpdate() {
  21567. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  21568. this.clippingContextVersion = this.clippingContext.version;
  21569. return true;
  21570. }
  21571. getNodeBuilderState() {
  21572. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21573. }
  21574. getBindings() {
  21575. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21576. }
  21577. getIndex() {
  21578. return this._geometries.getIndex( this );
  21579. }
  21580. getChainArray() {
  21581. return [ this.object, this.material, this.context, this.lightsNode ];
  21582. }
  21583. getAttributes() {
  21584. if ( this.attributes !== null ) return this.attributes;
  21585. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21586. const geometry = this.geometry;
  21587. const attributes = [];
  21588. const vertexBuffers = new Set();
  21589. for ( const nodeAttribute of nodeAttributes ) {
  21590. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  21591. if ( attribute === undefined ) continue;
  21592. attributes.push( attribute );
  21593. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21594. vertexBuffers.add( bufferAttribute );
  21595. }
  21596. this.attributes = attributes;
  21597. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21598. return attributes;
  21599. }
  21600. getVertexBuffers() {
  21601. if ( this.vertexBuffers === null ) this.getAttributes();
  21602. return this.vertexBuffers;
  21603. }
  21604. getMaterialCacheKey() {
  21605. const { object, material } = this;
  21606. let cacheKey = material.customProgramCacheKey();
  21607. for ( const property of getKeys( material ) ) {
  21608. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21609. const value = material[ property ];
  21610. let valueKey;
  21611. if ( value !== null ) {
  21612. // some material values require a formatting
  21613. const type = typeof value;
  21614. if ( type === 'number' ) {
  21615. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21616. } else if ( type === 'object' ) {
  21617. valueKey = '{';
  21618. if ( value.isTexture ) {
  21619. valueKey += value.mapping;
  21620. }
  21621. valueKey += '}';
  21622. } else {
  21623. valueKey = String( value );
  21624. }
  21625. } else {
  21626. valueKey = String( value );
  21627. }
  21628. cacheKey += /*property + ':' +*/ valueKey + ',';
  21629. }
  21630. cacheKey += this.clippingContextVersion + ',';
  21631. if ( object.skeleton ) {
  21632. cacheKey += object.skeleton.bones.length + ',';
  21633. }
  21634. if ( object.morphTargetInfluences ) {
  21635. cacheKey += object.morphTargetInfluences.length + ',';
  21636. }
  21637. if ( object.isBatchedMesh ) {
  21638. cacheKey += object._matricesTexture.uuid + ',';
  21639. if ( object._colorsTexture !== null ) {
  21640. cacheKey += object._colorsTexture.uuid + ',';
  21641. }
  21642. }
  21643. if ( object.count > 1 ) {
  21644. cacheKey += object.count + ',';
  21645. }
  21646. return cacheKey;
  21647. }
  21648. get needsUpdate() {
  21649. return this.initialNodesCacheKey !== this.getNodesCacheKey() || this.clippingNeedsUpdate;
  21650. }
  21651. getNodesCacheKey() {
  21652. // Environment Nodes Cache Key
  21653. return this._nodes.getCacheKey( this.scene, this.lightsNode );
  21654. }
  21655. getCacheKey() {
  21656. return this.getMaterialCacheKey() + ',' + this.getNodesCacheKey();
  21657. }
  21658. dispose() {
  21659. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21660. this.onDispose();
  21661. }
  21662. }
  21663. class RenderObjects {
  21664. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21665. this.renderer = renderer;
  21666. this.nodes = nodes;
  21667. this.geometries = geometries;
  21668. this.pipelines = pipelines;
  21669. this.bindings = bindings;
  21670. this.info = info;
  21671. this.chainMaps = {};
  21672. }
  21673. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  21674. const chainMap = this.getChainMap( passId );
  21675. const chainArray = [ object, material, renderContext, lightsNode ];
  21676. let renderObject = chainMap.get( chainArray );
  21677. if ( renderObject === undefined ) {
  21678. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  21679. chainMap.set( chainArray, renderObject );
  21680. } else {
  21681. renderObject.updateClipping( renderContext.clippingContext );
  21682. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21683. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21684. renderObject.dispose();
  21685. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  21686. } else {
  21687. renderObject.version = material.version;
  21688. }
  21689. }
  21690. }
  21691. return renderObject;
  21692. }
  21693. getChainMap( passId = 'default' ) {
  21694. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21695. }
  21696. dispose() {
  21697. this.chainMaps = {};
  21698. }
  21699. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  21700. const chainMap = this.getChainMap( passId );
  21701. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  21702. renderObject.onDispose = () => {
  21703. this.pipelines.delete( renderObject );
  21704. this.bindings.delete( renderObject );
  21705. this.nodes.delete( renderObject );
  21706. chainMap.delete( renderObject.getChainArray() );
  21707. };
  21708. return renderObject;
  21709. }
  21710. }
  21711. class DataMap {
  21712. constructor() {
  21713. this.data = new WeakMap();
  21714. }
  21715. get( object ) {
  21716. let map = this.data.get( object );
  21717. if ( map === undefined ) {
  21718. map = {};
  21719. this.data.set( object, map );
  21720. }
  21721. return map;
  21722. }
  21723. delete( object ) {
  21724. let map;
  21725. if ( this.data.has( object ) ) {
  21726. map = this.data.get( object );
  21727. this.data.delete( object );
  21728. }
  21729. return map;
  21730. }
  21731. has( object ) {
  21732. return this.data.has( object );
  21733. }
  21734. dispose() {
  21735. this.data = new WeakMap();
  21736. }
  21737. }
  21738. const AttributeType = {
  21739. VERTEX: 1,
  21740. INDEX: 2,
  21741. STORAGE: 4
  21742. };
  21743. // size of a chunk in bytes (STD140 layout)
  21744. const GPU_CHUNK_BYTES = 16;
  21745. // @TODO: Move to src/constants.js
  21746. const BlendColorFactor = 211;
  21747. const OneMinusBlendColorFactor = 212;
  21748. class Attributes extends DataMap {
  21749. constructor( backend ) {
  21750. super();
  21751. this.backend = backend;
  21752. }
  21753. delete( attribute ) {
  21754. const attributeData = super.delete( attribute );
  21755. if ( attributeData !== undefined ) {
  21756. this.backend.destroyAttribute( attribute );
  21757. }
  21758. return attributeData;
  21759. }
  21760. update( attribute, type ) {
  21761. const data = this.get( attribute );
  21762. if ( data.version === undefined ) {
  21763. if ( type === AttributeType.VERTEX ) {
  21764. this.backend.createAttribute( attribute );
  21765. } else if ( type === AttributeType.INDEX ) {
  21766. this.backend.createIndexAttribute( attribute );
  21767. } else if ( type === AttributeType.STORAGE ) {
  21768. this.backend.createStorageAttribute( attribute );
  21769. }
  21770. data.version = this._getBufferAttribute( attribute ).version;
  21771. } else {
  21772. const bufferAttribute = this._getBufferAttribute( attribute );
  21773. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21774. this.backend.updateAttribute( attribute );
  21775. data.version = bufferAttribute.version;
  21776. }
  21777. }
  21778. }
  21779. _getBufferAttribute( attribute ) {
  21780. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21781. return attribute;
  21782. }
  21783. }
  21784. function arrayNeedsUint32( array ) {
  21785. // assumes larger values usually on last
  21786. for ( let i = array.length - 1; i >= 0; -- i ) {
  21787. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  21788. }
  21789. return false;
  21790. }
  21791. function getWireframeVersion( geometry ) {
  21792. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21793. }
  21794. function getWireframeIndex( geometry ) {
  21795. const indices = [];
  21796. const geometryIndex = geometry.index;
  21797. const geometryPosition = geometry.attributes.position;
  21798. if ( geometryIndex !== null ) {
  21799. const array = geometryIndex.array;
  21800. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21801. const a = array[ i + 0 ];
  21802. const b = array[ i + 1 ];
  21803. const c = array[ i + 2 ];
  21804. indices.push( a, b, b, c, c, a );
  21805. }
  21806. } else {
  21807. const array = geometryPosition.array;
  21808. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21809. const a = i + 0;
  21810. const b = i + 1;
  21811. const c = i + 2;
  21812. indices.push( a, b, b, c, c, a );
  21813. }
  21814. }
  21815. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21816. attribute.version = getWireframeVersion( geometry );
  21817. return attribute;
  21818. }
  21819. class Geometries extends DataMap {
  21820. constructor( attributes, info ) {
  21821. super();
  21822. this.attributes = attributes;
  21823. this.info = info;
  21824. this.wireframes = new WeakMap();
  21825. this.attributeCall = new WeakMap();
  21826. }
  21827. has( renderObject ) {
  21828. const geometry = renderObject.geometry;
  21829. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21830. }
  21831. updateForRender( renderObject ) {
  21832. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21833. this.updateAttributes( renderObject );
  21834. }
  21835. initGeometry( renderObject ) {
  21836. const geometry = renderObject.geometry;
  21837. const geometryData = this.get( geometry );
  21838. geometryData.initialized = true;
  21839. this.info.memory.geometries ++;
  21840. const onDispose = () => {
  21841. this.info.memory.geometries --;
  21842. const index = geometry.index;
  21843. const geometryAttributes = renderObject.getAttributes();
  21844. if ( index !== null ) {
  21845. this.attributes.delete( index );
  21846. }
  21847. for ( const geometryAttribute of geometryAttributes ) {
  21848. this.attributes.delete( geometryAttribute );
  21849. }
  21850. const wireframeAttribute = this.wireframes.get( geometry );
  21851. if ( wireframeAttribute !== undefined ) {
  21852. this.attributes.delete( wireframeAttribute );
  21853. }
  21854. geometry.removeEventListener( 'dispose', onDispose );
  21855. };
  21856. geometry.addEventListener( 'dispose', onDispose );
  21857. }
  21858. updateAttributes( renderObject ) {
  21859. const attributes = renderObject.getAttributes();
  21860. for ( const attribute of attributes ) {
  21861. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21862. this.updateAttribute( attribute, AttributeType.STORAGE );
  21863. } else {
  21864. this.updateAttribute( attribute, AttributeType.VERTEX );
  21865. }
  21866. }
  21867. const index = this.getIndex( renderObject );
  21868. if ( index !== null ) {
  21869. this.updateAttribute( index, AttributeType.INDEX );
  21870. }
  21871. }
  21872. updateAttribute( attribute, type ) {
  21873. const callId = this.info.render.calls;
  21874. if ( ! attribute.isInterleavedBufferAttribute ) {
  21875. if ( this.attributeCall.get( attribute ) !== callId ) {
  21876. this.attributes.update( attribute, type );
  21877. this.attributeCall.set( attribute, callId );
  21878. }
  21879. } else {
  21880. if ( this.attributeCall.get( attribute ) === undefined ) {
  21881. this.attributes.update( attribute, type );
  21882. this.attributeCall.set( attribute, callId );
  21883. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21884. this.attributes.update( attribute, type );
  21885. this.attributeCall.set( attribute.data, callId );
  21886. this.attributeCall.set( attribute, callId );
  21887. }
  21888. }
  21889. }
  21890. getIndex( renderObject ) {
  21891. const { geometry, material } = renderObject;
  21892. let index = geometry.index;
  21893. if ( material.wireframe === true ) {
  21894. const wireframes = this.wireframes;
  21895. let wireframeAttribute = wireframes.get( geometry );
  21896. if ( wireframeAttribute === undefined ) {
  21897. wireframeAttribute = getWireframeIndex( geometry );
  21898. wireframes.set( geometry, wireframeAttribute );
  21899. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21900. this.attributes.delete( wireframeAttribute );
  21901. wireframeAttribute = getWireframeIndex( geometry );
  21902. wireframes.set( geometry, wireframeAttribute );
  21903. }
  21904. index = wireframeAttribute;
  21905. }
  21906. return index;
  21907. }
  21908. }
  21909. class Info {
  21910. constructor() {
  21911. this.autoReset = true;
  21912. this.frame = 0;
  21913. this.calls = 0;
  21914. this.render = {
  21915. calls: 0,
  21916. frameCalls: 0,
  21917. drawCalls: 0,
  21918. triangles: 0,
  21919. points: 0,
  21920. lines: 0,
  21921. timestamp: 0,
  21922. previousFrameCalls: 0,
  21923. timestampCalls: 0
  21924. };
  21925. this.compute = {
  21926. calls: 0,
  21927. frameCalls: 0,
  21928. timestamp: 0,
  21929. previousFrameCalls: 0,
  21930. timestampCalls: 0
  21931. };
  21932. this.memory = {
  21933. geometries: 0,
  21934. textures: 0
  21935. };
  21936. }
  21937. update( object, count, instanceCount ) {
  21938. this.render.drawCalls ++;
  21939. if ( object.isMesh || object.isSprite ) {
  21940. this.render.triangles += instanceCount * ( count / 3 );
  21941. } else if ( object.isPoints ) {
  21942. this.render.points += instanceCount * count;
  21943. } else if ( object.isLineSegments ) {
  21944. this.render.lines += instanceCount * ( count / 2 );
  21945. } else if ( object.isLine ) {
  21946. this.render.lines += instanceCount * ( count - 1 );
  21947. } else {
  21948. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  21949. }
  21950. }
  21951. updateTimestamp( type, time ) {
  21952. if ( this[ type ].timestampCalls === 0 ) {
  21953. this[ type ].timestamp = 0;
  21954. }
  21955. this[ type ].timestamp += time;
  21956. this[ type ].timestampCalls ++;
  21957. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  21958. this[ type ].timestampCalls = 0;
  21959. }
  21960. }
  21961. reset() {
  21962. const previousRenderFrameCalls = this.render.frameCalls;
  21963. this.render.previousFrameCalls = previousRenderFrameCalls;
  21964. const previousComputeFrameCalls = this.compute.frameCalls;
  21965. this.compute.previousFrameCalls = previousComputeFrameCalls;
  21966. this.render.drawCalls = 0;
  21967. this.render.frameCalls = 0;
  21968. this.compute.frameCalls = 0;
  21969. this.render.triangles = 0;
  21970. this.render.points = 0;
  21971. this.render.lines = 0;
  21972. }
  21973. dispose() {
  21974. this.reset();
  21975. this.calls = 0;
  21976. this.render.calls = 0;
  21977. this.compute.calls = 0;
  21978. this.render.timestamp = 0;
  21979. this.compute.timestamp = 0;
  21980. this.memory.geometries = 0;
  21981. this.memory.textures = 0;
  21982. }
  21983. }
  21984. class Pipeline {
  21985. constructor( cacheKey ) {
  21986. this.cacheKey = cacheKey;
  21987. this.usedTimes = 0;
  21988. }
  21989. }
  21990. class RenderPipeline extends Pipeline {
  21991. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21992. super( cacheKey );
  21993. this.vertexProgram = vertexProgram;
  21994. this.fragmentProgram = fragmentProgram;
  21995. }
  21996. }
  21997. class ComputePipeline extends Pipeline {
  21998. constructor( cacheKey, computeProgram ) {
  21999. super( cacheKey );
  22000. this.computeProgram = computeProgram;
  22001. this.isComputePipeline = true;
  22002. }
  22003. }
  22004. let _id$6 = 0;
  22005. class ProgrammableStage {
  22006. constructor( code, type, transforms = null, attributes = null ) {
  22007. this.id = _id$6 ++;
  22008. this.code = code;
  22009. this.stage = type;
  22010. this.transforms = transforms;
  22011. this.attributes = attributes;
  22012. this.usedTimes = 0;
  22013. }
  22014. }
  22015. class Pipelines extends DataMap {
  22016. constructor( backend, nodes ) {
  22017. super();
  22018. this.backend = backend;
  22019. this.nodes = nodes;
  22020. this.bindings = null; // set by the bindings
  22021. this.caches = new Map();
  22022. this.programs = {
  22023. vertex: new Map(),
  22024. fragment: new Map(),
  22025. compute: new Map()
  22026. };
  22027. }
  22028. getForCompute( computeNode, bindings ) {
  22029. const { backend } = this;
  22030. const data = this.get( computeNode );
  22031. if ( this._needsComputeUpdate( computeNode ) ) {
  22032. const previousPipeline = data.pipeline;
  22033. if ( previousPipeline ) {
  22034. previousPipeline.usedTimes --;
  22035. previousPipeline.computeProgram.usedTimes --;
  22036. }
  22037. // get shader
  22038. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  22039. // programmable stage
  22040. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  22041. if ( stageCompute === undefined ) {
  22042. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22043. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22044. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22045. backend.createProgram( stageCompute );
  22046. }
  22047. // determine compute pipeline
  22048. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22049. let pipeline = this.caches.get( cacheKey );
  22050. if ( pipeline === undefined ) {
  22051. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22052. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22053. }
  22054. // keep track of all used times
  22055. pipeline.usedTimes ++;
  22056. stageCompute.usedTimes ++;
  22057. //
  22058. data.version = computeNode.version;
  22059. data.pipeline = pipeline;
  22060. }
  22061. return data.pipeline;
  22062. }
  22063. getForRender( renderObject, promises = null ) {
  22064. const { backend } = this;
  22065. const data = this.get( renderObject );
  22066. if ( this._needsRenderUpdate( renderObject ) ) {
  22067. const previousPipeline = data.pipeline;
  22068. if ( previousPipeline ) {
  22069. previousPipeline.usedTimes --;
  22070. previousPipeline.vertexProgram.usedTimes --;
  22071. previousPipeline.fragmentProgram.usedTimes --;
  22072. }
  22073. // get shader
  22074. const nodeBuilderState = renderObject.getNodeBuilderState();
  22075. // programmable stages
  22076. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22077. if ( stageVertex === undefined ) {
  22078. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22079. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  22080. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22081. backend.createProgram( stageVertex );
  22082. }
  22083. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22084. if ( stageFragment === undefined ) {
  22085. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22086. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  22087. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22088. backend.createProgram( stageFragment );
  22089. }
  22090. // determine render pipeline
  22091. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22092. let pipeline = this.caches.get( cacheKey );
  22093. if ( pipeline === undefined ) {
  22094. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22095. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22096. } else {
  22097. renderObject.pipeline = pipeline;
  22098. }
  22099. // keep track of all used times
  22100. pipeline.usedTimes ++;
  22101. stageVertex.usedTimes ++;
  22102. stageFragment.usedTimes ++;
  22103. //
  22104. data.pipeline = pipeline;
  22105. }
  22106. return data.pipeline;
  22107. }
  22108. delete( object ) {
  22109. const pipeline = this.get( object ).pipeline;
  22110. if ( pipeline ) {
  22111. // pipeline
  22112. pipeline.usedTimes --;
  22113. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22114. // programs
  22115. if ( pipeline.isComputePipeline ) {
  22116. pipeline.computeProgram.usedTimes --;
  22117. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22118. } else {
  22119. pipeline.fragmentProgram.usedTimes --;
  22120. pipeline.vertexProgram.usedTimes --;
  22121. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22122. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22123. }
  22124. }
  22125. return super.delete( object );
  22126. }
  22127. dispose() {
  22128. super.dispose();
  22129. this.caches = new Map();
  22130. this.programs = {
  22131. vertex: new Map(),
  22132. fragment: new Map(),
  22133. compute: new Map()
  22134. };
  22135. }
  22136. updateForRender( renderObject ) {
  22137. this.getForRender( renderObject );
  22138. }
  22139. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22140. // check for existing pipeline
  22141. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22142. let pipeline = this.caches.get( cacheKey );
  22143. if ( pipeline === undefined ) {
  22144. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22145. this.caches.set( cacheKey, pipeline );
  22146. this.backend.createComputePipeline( pipeline, bindings );
  22147. }
  22148. return pipeline;
  22149. }
  22150. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22151. // check for existing pipeline
  22152. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22153. let pipeline = this.caches.get( cacheKey );
  22154. if ( pipeline === undefined ) {
  22155. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22156. this.caches.set( cacheKey, pipeline );
  22157. renderObject.pipeline = pipeline;
  22158. this.backend.createRenderPipeline( renderObject, promises );
  22159. }
  22160. return pipeline;
  22161. }
  22162. _getComputeCacheKey( computeNode, stageCompute ) {
  22163. return computeNode.id + ',' + stageCompute.id;
  22164. }
  22165. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22166. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22167. }
  22168. _releasePipeline( pipeline ) {
  22169. this.caches.delete( pipeline.cacheKey );
  22170. }
  22171. _releaseProgram( program ) {
  22172. const code = program.code;
  22173. const stage = program.stage;
  22174. this.programs[ stage ].delete( code );
  22175. }
  22176. _needsComputeUpdate( computeNode ) {
  22177. const data = this.get( computeNode );
  22178. return data.pipeline === undefined || data.version !== computeNode.version;
  22179. }
  22180. _needsRenderUpdate( renderObject ) {
  22181. const data = this.get( renderObject );
  22182. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22183. }
  22184. }
  22185. class Bindings extends DataMap {
  22186. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22187. super();
  22188. this.backend = backend;
  22189. this.textures = textures;
  22190. this.pipelines = pipelines;
  22191. this.attributes = attributes;
  22192. this.nodes = nodes;
  22193. this.info = info;
  22194. this.pipelines.bindings = this; // assign bindings to pipelines
  22195. }
  22196. getForRender( renderObject ) {
  22197. const bindings = renderObject.getBindings();
  22198. for ( const bindGroup of bindings ) {
  22199. const groupData = this.get( bindGroup );
  22200. if ( groupData.bindGroup === undefined ) {
  22201. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22202. this._init( bindGroup );
  22203. this.backend.createBindings( bindGroup, bindings );
  22204. groupData.bindGroup = bindGroup;
  22205. }
  22206. }
  22207. return bindings;
  22208. }
  22209. getForCompute( computeNode ) {
  22210. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22211. for ( const bindGroup of bindings ) {
  22212. const groupData = this.get( bindGroup );
  22213. if ( groupData.bindGroup === undefined ) {
  22214. this._init( bindGroup );
  22215. this.backend.createBindings( bindGroup, bindings );
  22216. groupData.bindGroup = bindGroup;
  22217. }
  22218. }
  22219. return bindings;
  22220. }
  22221. updateForCompute( computeNode ) {
  22222. this._updateBindings( computeNode, this.getForCompute( computeNode ) );
  22223. }
  22224. updateForRender( renderObject ) {
  22225. this._updateBindings( renderObject, this.getForRender( renderObject ) );
  22226. }
  22227. _updateBindings( object, bindings ) {
  22228. for ( const bindGroup of bindings ) {
  22229. this._update( object, bindGroup, bindings );
  22230. }
  22231. }
  22232. _init( bindGroup ) {
  22233. for ( const binding of bindGroup.bindings ) {
  22234. if ( binding.isSampledTexture ) {
  22235. this.textures.updateTexture( binding.texture );
  22236. } else if ( binding.isStorageBuffer ) {
  22237. const attribute = binding.attribute;
  22238. this.attributes.update( attribute, AttributeType.STORAGE );
  22239. }
  22240. }
  22241. }
  22242. _update( object, bindGroup, bindings ) {
  22243. const { backend } = this;
  22244. let needsBindingsUpdate = false;
  22245. // iterate over all bindings and check if buffer updates or a new binding group is required
  22246. for ( const binding of bindGroup.bindings ) {
  22247. if ( binding.isNodeUniformsGroup ) {
  22248. const updated = this.nodes.updateGroup( binding );
  22249. if ( ! updated ) continue;
  22250. }
  22251. if ( binding.isUniformBuffer ) {
  22252. const updated = binding.update();
  22253. if ( updated ) {
  22254. backend.updateBinding( binding );
  22255. }
  22256. } else if ( binding.isSampler ) {
  22257. binding.update();
  22258. } else if ( binding.isSampledTexture ) {
  22259. const texture = binding.texture;
  22260. if ( binding.needsBindingsUpdate ) needsBindingsUpdate = true;
  22261. const updated = binding.update();
  22262. if ( updated ) {
  22263. this.textures.updateTexture( binding.texture );
  22264. }
  22265. const textureData = backend.get( binding.texture );
  22266. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  22267. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  22268. console.error( 'Bindings._update: binding should be available:', binding, updated, binding.texture, binding.textureNode.value );
  22269. this.textures.updateTexture( binding.texture );
  22270. needsBindingsUpdate = true;
  22271. }
  22272. if ( texture.isStorageTexture === true ) {
  22273. const textureData = this.get( texture );
  22274. if ( binding.store === true ) {
  22275. textureData.needsMipmap = true;
  22276. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22277. this.backend.generateMipmaps( texture );
  22278. textureData.needsMipmap = false;
  22279. }
  22280. }
  22281. }
  22282. }
  22283. if ( needsBindingsUpdate === true ) {
  22284. const pipeline = this.pipelines.getForRender( object );
  22285. this.backend.updateBindings( bindGroup, bindings, pipeline );
  22286. }
  22287. }
  22288. }
  22289. const NodeShaderStage = {
  22290. VERTEX: 'vertex',
  22291. FRAGMENT: 'fragment'
  22292. };
  22293. const NodeUpdateType = {
  22294. NONE: 'none',
  22295. FRAME: 'frame',
  22296. RENDER: 'render',
  22297. OBJECT: 'object'
  22298. };
  22299. const NodeType = {
  22300. BOOLEAN: 'bool',
  22301. INTEGER: 'int',
  22302. FLOAT: 'float',
  22303. VECTOR2: 'vec2',
  22304. VECTOR3: 'vec3',
  22305. VECTOR4: 'vec4',
  22306. MATRIX2: 'mat2',
  22307. MATRIX3: 'mat3',
  22308. MATRIX4: 'mat4'
  22309. };
  22310. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22311. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22312. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22313. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22314. function getCacheKey( object, force = false ) {
  22315. let cacheKey = '{';
  22316. if ( object.isNode === true ) {
  22317. cacheKey += object.id;
  22318. }
  22319. for ( const { property, childNode } of getNodeChildren( object ) ) {
  22320. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  22321. }
  22322. cacheKey += '}';
  22323. return cacheKey;
  22324. }
  22325. function* getNodeChildren( node, toJSON = false ) {
  22326. for ( const property in node ) {
  22327. // Ignore private properties.
  22328. if ( property.startsWith( '_' ) === true ) continue;
  22329. const object = node[ property ];
  22330. if ( Array.isArray( object ) === true ) {
  22331. for ( let i = 0; i < object.length; i ++ ) {
  22332. const child = object[ i ];
  22333. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22334. yield { property, index: i, childNode: child };
  22335. }
  22336. }
  22337. } else if ( object && object.isNode === true ) {
  22338. yield { property, childNode: object };
  22339. } else if ( typeof object === 'object' ) {
  22340. for ( const subProperty in object ) {
  22341. const child = object[ subProperty ];
  22342. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22343. yield { property, index: subProperty, childNode: child };
  22344. }
  22345. }
  22346. }
  22347. }
  22348. }
  22349. function getValueType( value ) {
  22350. if ( value === undefined || value === null ) return null;
  22351. const typeOf = typeof value;
  22352. if ( value.isNode === true ) {
  22353. return 'node';
  22354. } else if ( typeOf === 'number' ) {
  22355. return 'float';
  22356. } else if ( typeOf === 'boolean' ) {
  22357. return 'bool';
  22358. } else if ( typeOf === 'string' ) {
  22359. return 'string';
  22360. } else if ( typeOf === 'function' ) {
  22361. return 'shader';
  22362. } else if ( value.isVector2 === true ) {
  22363. return 'vec2';
  22364. } else if ( value.isVector3 === true ) {
  22365. return 'vec3';
  22366. } else if ( value.isVector4 === true ) {
  22367. return 'vec4';
  22368. } else if ( value.isMatrix3 === true ) {
  22369. return 'mat3';
  22370. } else if ( value.isMatrix4 === true ) {
  22371. return 'mat4';
  22372. } else if ( value.isColor === true ) {
  22373. return 'color';
  22374. } else if ( value instanceof ArrayBuffer ) {
  22375. return 'ArrayBuffer';
  22376. }
  22377. return null;
  22378. }
  22379. function getValueFromType( type, ...params ) {
  22380. const last4 = type ? type.slice( - 4 ) : undefined;
  22381. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  22382. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  22383. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  22384. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  22385. }
  22386. if ( type === 'color' ) {
  22387. return new Color( ...params );
  22388. } else if ( last4 === 'vec2' ) {
  22389. return new Vector2( ...params );
  22390. } else if ( last4 === 'vec3' ) {
  22391. return new Vector3( ...params );
  22392. } else if ( last4 === 'vec4' ) {
  22393. return new Vector4( ...params );
  22394. } else if ( last4 === 'mat3' ) {
  22395. return new Matrix3( ...params );
  22396. } else if ( last4 === 'mat4' ) {
  22397. return new Matrix4( ...params );
  22398. } else if ( type === 'bool' ) {
  22399. return params[ 0 ] || false;
  22400. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  22401. return params[ 0 ] || 0;
  22402. } else if ( type === 'string' ) {
  22403. return params[ 0 ] || '';
  22404. } else if ( type === 'ArrayBuffer' ) {
  22405. return base64ToArrayBuffer( params[ 0 ] );
  22406. }
  22407. return null;
  22408. }
  22409. function arrayBufferToBase64( arrayBuffer ) {
  22410. let chars = '';
  22411. const array = new Uint8Array( arrayBuffer );
  22412. for ( let i = 0; i < array.length; i ++ ) {
  22413. chars += String.fromCharCode( array[ i ] );
  22414. }
  22415. return btoa( chars );
  22416. }
  22417. function base64ToArrayBuffer( base64 ) {
  22418. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  22419. }
  22420. var NodeUtils = /*#__PURE__*/Object.freeze({
  22421. __proto__: null,
  22422. arrayBufferToBase64: arrayBufferToBase64,
  22423. base64ToArrayBuffer: base64ToArrayBuffer,
  22424. getCacheKey: getCacheKey,
  22425. getNodeChildren: getNodeChildren,
  22426. getValueFromType: getValueFromType,
  22427. getValueType: getValueType
  22428. });
  22429. const NodeClasses = new Map();
  22430. let _nodeId = 0;
  22431. class Node extends EventDispatcher {
  22432. constructor( nodeType = null ) {
  22433. super();
  22434. this.nodeType = nodeType;
  22435. this.updateType = NodeUpdateType.NONE;
  22436. this.updateBeforeType = NodeUpdateType.NONE;
  22437. this.updateAfterType = NodeUpdateType.NONE;
  22438. this.uuid = MathUtils.generateUUID();
  22439. this.version = 0;
  22440. this._cacheKey = null;
  22441. this._cacheKeyVersion = 0;
  22442. this.global = false;
  22443. this.isNode = true;
  22444. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22445. }
  22446. set needsUpdate( value ) {
  22447. if ( value === true ) {
  22448. this.version ++;
  22449. }
  22450. }
  22451. get type() {
  22452. return this.constructor.type;
  22453. }
  22454. onUpdate( callback, updateType ) {
  22455. this.updateType = updateType;
  22456. this.update = callback.bind( this.getSelf() );
  22457. return this;
  22458. }
  22459. onFrameUpdate( callback ) {
  22460. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22461. }
  22462. onRenderUpdate( callback ) {
  22463. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22464. }
  22465. onObjectUpdate( callback ) {
  22466. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22467. }
  22468. onReference( callback ) {
  22469. this.updateReference = callback.bind( this.getSelf() );
  22470. return this;
  22471. }
  22472. getSelf() {
  22473. // Returns non-node object.
  22474. return this.self || this;
  22475. }
  22476. updateReference( /*state*/ ) {
  22477. return this;
  22478. }
  22479. isGlobal( /*builder*/ ) {
  22480. return this.global;
  22481. }
  22482. * getChildren() {
  22483. for ( const { childNode } of getNodeChildren( this ) ) {
  22484. yield childNode;
  22485. }
  22486. }
  22487. dispose() {
  22488. this.dispatchEvent( { type: 'dispose' } );
  22489. }
  22490. traverse( callback ) {
  22491. callback( this );
  22492. for ( const childNode of this.getChildren() ) {
  22493. childNode.traverse( callback );
  22494. }
  22495. }
  22496. getCacheKey( force = false ) {
  22497. force = force || this.version !== this._cacheKeyVersion;
  22498. if ( force === true || this._cacheKey === null ) {
  22499. this._cacheKey = getCacheKey( this, force );
  22500. this._cacheKeyVersion = this.version;
  22501. }
  22502. return this._cacheKey;
  22503. }
  22504. getHash( /*builder*/ ) {
  22505. return this.uuid;
  22506. }
  22507. getUpdateType() {
  22508. return this.updateType;
  22509. }
  22510. getUpdateBeforeType() {
  22511. return this.updateBeforeType;
  22512. }
  22513. getUpdateAfterType() {
  22514. return this.updateAfterType;
  22515. }
  22516. getElementType( builder ) {
  22517. const type = this.getNodeType( builder );
  22518. const elementType = builder.getElementType( type );
  22519. return elementType;
  22520. }
  22521. getNodeType( builder ) {
  22522. const nodeProperties = builder.getNodeProperties( this );
  22523. if ( nodeProperties.outputNode ) {
  22524. return nodeProperties.outputNode.getNodeType( builder );
  22525. }
  22526. return this.nodeType;
  22527. }
  22528. getShared( builder ) {
  22529. const hash = this.getHash( builder );
  22530. const nodeFromHash = builder.getNodeFromHash( hash );
  22531. return nodeFromHash || this;
  22532. }
  22533. setup( builder ) {
  22534. const nodeProperties = builder.getNodeProperties( this );
  22535. let index = 0;
  22536. for ( const childNode of this.getChildren() ) {
  22537. nodeProperties[ 'node' + index ++ ] = childNode;
  22538. }
  22539. // return a outputNode if exists
  22540. return null;
  22541. }
  22542. increaseUsage( builder ) {
  22543. const nodeData = builder.getDataFromNode( this );
  22544. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  22545. return nodeData.usageCount;
  22546. }
  22547. analyze( builder ) {
  22548. const usageCount = this.increaseUsage( builder );
  22549. if ( usageCount === 1 ) {
  22550. // node flow children
  22551. const nodeProperties = builder.getNodeProperties( this );
  22552. for ( const childNode of Object.values( nodeProperties ) ) {
  22553. if ( childNode && childNode.isNode === true ) {
  22554. childNode.build( builder );
  22555. }
  22556. }
  22557. }
  22558. }
  22559. generate( builder, output ) {
  22560. const { outputNode } = builder.getNodeProperties( this );
  22561. if ( outputNode && outputNode.isNode === true ) {
  22562. return outputNode.build( builder, output );
  22563. }
  22564. }
  22565. updateBefore( /*frame*/ ) {
  22566. console.warn( 'Abstract function.' );
  22567. }
  22568. updateAfter( /*frame*/ ) {
  22569. console.warn( 'Abstract function.' );
  22570. }
  22571. update( /*frame*/ ) {
  22572. console.warn( 'Abstract function.' );
  22573. }
  22574. build( builder, output = null ) {
  22575. const refNode = this.getShared( builder );
  22576. if ( this !== refNode ) {
  22577. return refNode.build( builder, output );
  22578. }
  22579. builder.addNode( this );
  22580. builder.addChain( this );
  22581. /* Build stages expected results:
  22582. - "setup" -> Node
  22583. - "analyze" -> null
  22584. - "generate" -> String
  22585. */
  22586. let result = null;
  22587. const buildStage = builder.getBuildStage();
  22588. if ( buildStage === 'setup' ) {
  22589. this.updateReference( builder );
  22590. const properties = builder.getNodeProperties( this );
  22591. if ( properties.initialized !== true ) {
  22592. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22593. properties.initialized = true;
  22594. properties.outputNode = this.setup( builder );
  22595. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  22596. properties.outputNode = builder.stack;
  22597. }
  22598. for ( const childNode of Object.values( properties ) ) {
  22599. if ( childNode && childNode.isNode === true ) {
  22600. childNode.build( builder );
  22601. }
  22602. }
  22603. }
  22604. } else if ( buildStage === 'analyze' ) {
  22605. this.analyze( builder );
  22606. } else if ( buildStage === 'generate' ) {
  22607. const isGenerateOnce = this.generate.length === 1;
  22608. if ( isGenerateOnce ) {
  22609. const type = this.getNodeType( builder );
  22610. const nodeData = builder.getDataFromNode( this );
  22611. result = nodeData.snippet;
  22612. if ( result === undefined ) {
  22613. result = this.generate( builder ) || '';
  22614. nodeData.snippet = result;
  22615. }
  22616. result = builder.format( result, type, output );
  22617. } else {
  22618. result = this.generate( builder, output ) || '';
  22619. }
  22620. }
  22621. builder.removeChain( this );
  22622. return result;
  22623. }
  22624. getSerializeChildren() {
  22625. return getNodeChildren( this );
  22626. }
  22627. serialize( json ) {
  22628. const nodeChildren = this.getSerializeChildren();
  22629. const inputNodes = {};
  22630. for ( const { property, index, childNode } of nodeChildren ) {
  22631. if ( index !== undefined ) {
  22632. if ( inputNodes[ property ] === undefined ) {
  22633. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22634. }
  22635. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22636. } else {
  22637. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22638. }
  22639. }
  22640. if ( Object.keys( inputNodes ).length > 0 ) {
  22641. json.inputNodes = inputNodes;
  22642. }
  22643. }
  22644. deserialize( json ) {
  22645. if ( json.inputNodes !== undefined ) {
  22646. const nodes = json.meta.nodes;
  22647. for ( const property in json.inputNodes ) {
  22648. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22649. const inputArray = [];
  22650. for ( const uuid of json.inputNodes[ property ] ) {
  22651. inputArray.push( nodes[ uuid ] );
  22652. }
  22653. this[ property ] = inputArray;
  22654. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22655. const inputObject = {};
  22656. for ( const subProperty in json.inputNodes[ property ] ) {
  22657. const uuid = json.inputNodes[ property ][ subProperty ];
  22658. inputObject[ subProperty ] = nodes[ uuid ];
  22659. }
  22660. this[ property ] = inputObject;
  22661. } else {
  22662. const uuid = json.inputNodes[ property ];
  22663. this[ property ] = nodes[ uuid ];
  22664. }
  22665. }
  22666. }
  22667. }
  22668. toJSON( meta ) {
  22669. const { uuid, type } = this;
  22670. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22671. if ( isRoot ) {
  22672. meta = {
  22673. textures: {},
  22674. images: {},
  22675. nodes: {}
  22676. };
  22677. }
  22678. // serialize
  22679. let data = meta.nodes[ uuid ];
  22680. if ( data === undefined ) {
  22681. data = {
  22682. uuid,
  22683. type,
  22684. meta,
  22685. metadata: {
  22686. version: 4.6,
  22687. type: 'Node',
  22688. generator: 'Node.toJSON'
  22689. }
  22690. };
  22691. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22692. this.serialize( data );
  22693. delete data.meta;
  22694. }
  22695. // TODO: Copied from Object3D.toJSON
  22696. function extractFromCache( cache ) {
  22697. const values = [];
  22698. for ( const key in cache ) {
  22699. const data = cache[ key ];
  22700. delete data.metadata;
  22701. values.push( data );
  22702. }
  22703. return values;
  22704. }
  22705. if ( isRoot ) {
  22706. const textures = extractFromCache( meta.textures );
  22707. const images = extractFromCache( meta.images );
  22708. const nodes = extractFromCache( meta.nodes );
  22709. if ( textures.length > 0 ) data.textures = textures;
  22710. if ( images.length > 0 ) data.images = images;
  22711. if ( nodes.length > 0 ) data.nodes = nodes;
  22712. }
  22713. return data;
  22714. }
  22715. }
  22716. function addNodeClass( type, nodeClass ) {
  22717. if ( typeof nodeClass !== 'function' || ! type ) throw new Error( `Node class ${ type } is not a class` );
  22718. if ( NodeClasses.has( type ) ) {
  22719. console.warn( `Redefinition of node class ${ type }` );
  22720. return;
  22721. }
  22722. NodeClasses.set( type, nodeClass );
  22723. nodeClass.type = type;
  22724. }
  22725. function createNodeFromType( type ) {
  22726. const Class = NodeClasses.get( type );
  22727. if ( Class !== undefined ) {
  22728. return new Class();
  22729. }
  22730. }
  22731. class TempNode extends Node {
  22732. constructor( type ) {
  22733. super( type );
  22734. this.isTempNode = true;
  22735. }
  22736. hasDependencies( builder ) {
  22737. return builder.getDataFromNode( this ).usageCount > 1;
  22738. }
  22739. build( builder, output ) {
  22740. const buildStage = builder.getBuildStage();
  22741. if ( buildStage === 'generate' ) {
  22742. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22743. const nodeData = builder.getDataFromNode( this );
  22744. if ( nodeData.propertyName !== undefined ) {
  22745. return builder.format( nodeData.propertyName, type, output );
  22746. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22747. const snippet = super.build( builder, type );
  22748. const nodeVar = builder.getVarFromNode( this, null, type );
  22749. const propertyName = builder.getPropertyName( nodeVar );
  22750. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22751. nodeData.snippet = snippet;
  22752. nodeData.propertyName = propertyName;
  22753. return builder.format( nodeData.propertyName, type, output );
  22754. }
  22755. }
  22756. return super.build( builder, output );
  22757. }
  22758. }
  22759. addNodeClass( 'TempNode', TempNode );
  22760. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  22761. constructor( node, indexNode ) {
  22762. super();
  22763. this.node = node;
  22764. this.indexNode = indexNode;
  22765. this.isArrayElementNode = true;
  22766. }
  22767. getNodeType( builder ) {
  22768. return this.node.getElementType( builder );
  22769. }
  22770. generate( builder ) {
  22771. const nodeSnippet = this.node.build( builder );
  22772. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22773. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22774. }
  22775. }
  22776. addNodeClass( 'ArrayElementNode', ArrayElementNode );
  22777. class ConvertNode extends Node {
  22778. constructor( node, convertTo ) {
  22779. super();
  22780. this.node = node;
  22781. this.convertTo = convertTo;
  22782. }
  22783. getNodeType( builder ) {
  22784. const requestType = this.node.getNodeType( builder );
  22785. let convertTo = null;
  22786. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22787. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22788. convertTo = overloadingType;
  22789. }
  22790. }
  22791. return convertTo;
  22792. }
  22793. serialize( data ) {
  22794. super.serialize( data );
  22795. data.convertTo = this.convertTo;
  22796. }
  22797. deserialize( data ) {
  22798. super.deserialize( data );
  22799. this.convertTo = data.convertTo;
  22800. }
  22801. generate( builder, output ) {
  22802. const node = this.node;
  22803. const type = this.getNodeType( builder );
  22804. const snippet = node.build( builder, type );
  22805. return builder.format( snippet, type, output );
  22806. }
  22807. }
  22808. addNodeClass( 'ConvertNode', ConvertNode );
  22809. class JoinNode extends TempNode {
  22810. constructor( nodes = [], nodeType = null ) {
  22811. super( nodeType );
  22812. this.nodes = nodes;
  22813. }
  22814. getNodeType( builder ) {
  22815. if ( this.nodeType !== null ) {
  22816. return builder.getVectorType( this.nodeType );
  22817. }
  22818. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22819. }
  22820. generate( builder, output ) {
  22821. const type = this.getNodeType( builder );
  22822. const nodes = this.nodes;
  22823. const primitiveType = builder.getComponentType( type );
  22824. const snippetValues = [];
  22825. for ( const input of nodes ) {
  22826. let inputSnippet = input.build( builder );
  22827. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22828. if ( inputPrimitiveType !== primitiveType ) {
  22829. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22830. }
  22831. snippetValues.push( inputSnippet );
  22832. }
  22833. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22834. return builder.format( snippet, type, output );
  22835. }
  22836. }
  22837. addNodeClass( 'JoinNode', JoinNode );
  22838. const stringVectorComponents = vectorComponents.join( '' );
  22839. class SplitNode extends Node {
  22840. constructor( node, components = 'x' ) {
  22841. super();
  22842. this.node = node;
  22843. this.components = components;
  22844. this.isSplitNode = true;
  22845. }
  22846. getVectorLength() {
  22847. let vectorLength = this.components.length;
  22848. for ( const c of this.components ) {
  22849. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22850. }
  22851. return vectorLength;
  22852. }
  22853. getComponentType( builder ) {
  22854. return builder.getComponentType( this.node.getNodeType( builder ) );
  22855. }
  22856. getNodeType( builder ) {
  22857. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22858. }
  22859. generate( builder, output ) {
  22860. const node = this.node;
  22861. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22862. let snippet = null;
  22863. if ( nodeTypeLength > 1 ) {
  22864. let type = null;
  22865. const componentsLength = this.getVectorLength();
  22866. if ( componentsLength >= nodeTypeLength ) {
  22867. // needed expand the input node
  22868. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22869. }
  22870. const nodeSnippet = node.build( builder, type );
  22871. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22872. // unnecessary swizzle
  22873. snippet = builder.format( nodeSnippet, type, output );
  22874. } else {
  22875. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22876. }
  22877. } else {
  22878. // ignore .components if .node returns float/integer
  22879. snippet = node.build( builder, output );
  22880. }
  22881. return snippet;
  22882. }
  22883. serialize( data ) {
  22884. super.serialize( data );
  22885. data.components = this.components;
  22886. }
  22887. deserialize( data ) {
  22888. super.deserialize( data );
  22889. this.components = data.components;
  22890. }
  22891. }
  22892. addNodeClass( 'SplitNode', SplitNode );
  22893. class SetNode extends TempNode {
  22894. constructor( sourceNode, components, targetNode ) {
  22895. super();
  22896. this.sourceNode = sourceNode;
  22897. this.components = components;
  22898. this.targetNode = targetNode;
  22899. }
  22900. getNodeType( builder ) {
  22901. return this.sourceNode.getNodeType( builder );
  22902. }
  22903. generate( builder ) {
  22904. const { sourceNode, components, targetNode } = this;
  22905. const sourceType = this.getNodeType( builder );
  22906. const targetType = builder.getTypeFromLength( components.length );
  22907. const targetSnippet = targetNode.build( builder, targetType );
  22908. const sourceSnippet = sourceNode.build( builder, sourceType );
  22909. const length = builder.getTypeLength( sourceType );
  22910. const snippetValues = [];
  22911. for ( let i = 0; i < length; i ++ ) {
  22912. const component = vectorComponents[ i ];
  22913. if ( component === components[ 0 ] ) {
  22914. snippetValues.push( targetSnippet );
  22915. i += components.length - 1;
  22916. } else {
  22917. snippetValues.push( sourceSnippet + '.' + component );
  22918. }
  22919. }
  22920. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22921. }
  22922. }
  22923. addNodeClass( 'SetNode', SetNode );
  22924. class InputNode extends Node {
  22925. constructor( value, nodeType = null ) {
  22926. super( nodeType );
  22927. this.isInputNode = true;
  22928. this.value = value;
  22929. this.precision = null;
  22930. }
  22931. getNodeType( /*builder*/ ) {
  22932. if ( this.nodeType === null ) {
  22933. return getValueType( this.value );
  22934. }
  22935. return this.nodeType;
  22936. }
  22937. getInputType( builder ) {
  22938. return this.getNodeType( builder );
  22939. }
  22940. setPrecision( precision ) {
  22941. this.precision = precision;
  22942. return this;
  22943. }
  22944. serialize( data ) {
  22945. super.serialize( data );
  22946. data.value = this.value;
  22947. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22948. data.valueType = getValueType( this.value );
  22949. data.nodeType = this.nodeType;
  22950. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22951. data.precision = this.precision;
  22952. }
  22953. deserialize( data ) {
  22954. super.deserialize( data );
  22955. this.nodeType = data.nodeType;
  22956. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22957. this.precision = data.precision || null;
  22958. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22959. }
  22960. generate( /*builder, output*/ ) {
  22961. console.warn( 'Abstract function.' );
  22962. }
  22963. }
  22964. addNodeClass( 'InputNode', InputNode );
  22965. class ConstNode extends InputNode {
  22966. constructor( value, nodeType = null ) {
  22967. super( value, nodeType );
  22968. this.isConstNode = true;
  22969. }
  22970. generateConst( builder ) {
  22971. return builder.generateConst( this.getNodeType( builder ), this.value );
  22972. }
  22973. generate( builder, output ) {
  22974. const type = this.getNodeType( builder );
  22975. return builder.format( this.generateConst( builder ), type, output );
  22976. }
  22977. }
  22978. addNodeClass( 'ConstNode', ConstNode );
  22979. //
  22980. let currentStack = null;
  22981. const NodeElements = new Map(); // @TODO: Currently only a few nodes are added, probably also add others
  22982. function addNodeElement( name, nodeElement ) {
  22983. if ( NodeElements.has( name ) ) {
  22984. console.warn( `Redefinition of node element ${ name }` );
  22985. return;
  22986. }
  22987. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22988. NodeElements.set( name, nodeElement );
  22989. }
  22990. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22991. const shaderNodeHandler = {
  22992. setup( NodeClosure, params ) {
  22993. const inputs = params.shift();
  22994. return NodeClosure( nodeObjects( inputs ), ...params );
  22995. },
  22996. get( node, prop, nodeObj ) {
  22997. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22998. if ( node.isStackNode !== true && prop === 'assign' ) {
  22999. return ( ...params ) => {
  23000. currentStack.assign( nodeObj, ...params );
  23001. return nodeObj;
  23002. };
  23003. } else if ( NodeElements.has( prop ) ) {
  23004. const nodeElement = NodeElements.get( prop );
  23005. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  23006. } else if ( prop === 'self' ) {
  23007. return node;
  23008. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  23009. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  23010. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  23011. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  23012. // accessing properties ( swizzle )
  23013. prop = parseSwizzle( prop );
  23014. return nodeObject( new SplitNode( nodeObj, prop ) );
  23015. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  23016. // set properties ( swizzle )
  23017. prop = parseSwizzle( prop.slice( 3 ).toLowerCase() );
  23018. // sort to xyzw sequence
  23019. prop = prop.split( '' ).sort().join( '' );
  23020. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  23021. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  23022. // accessing property
  23023. if ( prop === 'width' ) prop = 'x';
  23024. else if ( prop === 'height' ) prop = 'y';
  23025. else if ( prop === 'depth' ) prop = 'z';
  23026. return nodeObject( new SplitNode( node, prop ) );
  23027. } else if ( /^\d+$/.test( prop ) === true ) {
  23028. // accessing array
  23029. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  23030. }
  23031. }
  23032. return Reflect.get( node, prop, nodeObj );
  23033. },
  23034. set( node, prop, value, nodeObj ) {
  23035. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  23036. // setting properties
  23037. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  23038. nodeObj[ prop ].assign( value );
  23039. return true;
  23040. }
  23041. }
  23042. return Reflect.set( node, prop, value, nodeObj );
  23043. }
  23044. };
  23045. const nodeObjectsCacheMap = new WeakMap();
  23046. const nodeBuilderFunctionsCacheMap = new WeakMap();
  23047. const ShaderNodeObject = function ( obj, altType = null ) {
  23048. const type = getValueType( obj );
  23049. if ( type === 'node' ) {
  23050. let nodeObject = nodeObjectsCacheMap.get( obj );
  23051. if ( nodeObject === undefined ) {
  23052. nodeObject = new Proxy( obj, shaderNodeHandler );
  23053. nodeObjectsCacheMap.set( obj, nodeObject );
  23054. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  23055. }
  23056. return nodeObject;
  23057. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  23058. return nodeObject( getConstNode( obj, altType ) );
  23059. } else if ( type === 'shader' ) {
  23060. return tslFn( obj );
  23061. }
  23062. return obj;
  23063. };
  23064. const ShaderNodeObjects = function ( objects, altType = null ) {
  23065. for ( const name in objects ) {
  23066. objects[ name ] = nodeObject( objects[ name ], altType );
  23067. }
  23068. return objects;
  23069. };
  23070. const ShaderNodeArray = function ( array, altType = null ) {
  23071. const len = array.length;
  23072. for ( let i = 0; i < len; i ++ ) {
  23073. array[ i ] = nodeObject( array[ i ], altType );
  23074. }
  23075. return array;
  23076. };
  23077. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  23078. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  23079. if ( scope === null ) {
  23080. return ( ...params ) => {
  23081. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  23082. };
  23083. } else if ( factor !== null ) {
  23084. factor = nodeObject( factor );
  23085. return ( ...params ) => {
  23086. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  23087. };
  23088. } else {
  23089. return ( ...params ) => {
  23090. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  23091. };
  23092. }
  23093. };
  23094. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  23095. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  23096. };
  23097. class ShaderCallNodeInternal extends Node {
  23098. constructor( shaderNode, inputNodes ) {
  23099. super();
  23100. this.shaderNode = shaderNode;
  23101. this.inputNodes = inputNodes;
  23102. }
  23103. getNodeType( builder ) {
  23104. const properties = builder.getNodeProperties( this );
  23105. if ( properties.outputNode === null ) {
  23106. properties.outputNode = this.setupOutput( builder );
  23107. }
  23108. return properties.outputNode.getNodeType( builder );
  23109. }
  23110. call( builder ) {
  23111. const { shaderNode, inputNodes } = this;
  23112. if ( shaderNode.layout ) {
  23113. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  23114. if ( functionNodesCacheMap === undefined ) {
  23115. functionNodesCacheMap = new WeakMap();
  23116. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  23117. }
  23118. let functionNode = functionNodesCacheMap.get( shaderNode );
  23119. if ( functionNode === undefined ) {
  23120. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  23121. functionNodesCacheMap.set( shaderNode, functionNode );
  23122. }
  23123. if ( builder.currentFunctionNode !== null ) {
  23124. builder.currentFunctionNode.includes.push( functionNode );
  23125. }
  23126. return nodeObject( functionNode.call( inputNodes ) );
  23127. }
  23128. const jsFunc = shaderNode.jsFunc;
  23129. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder.stack, builder ) : jsFunc( builder.stack, builder );
  23130. return nodeObject( outputNode );
  23131. }
  23132. setup( builder ) {
  23133. const { outputNode } = builder.getNodeProperties( this );
  23134. return outputNode || this.setupOutput( builder );
  23135. }
  23136. setupOutput( builder ) {
  23137. builder.addStack();
  23138. builder.stack.outputNode = this.call( builder );
  23139. return builder.removeStack();
  23140. }
  23141. generate( builder, output ) {
  23142. const { outputNode } = builder.getNodeProperties( this );
  23143. if ( outputNode === null ) {
  23144. // TSL: It's recommended to use `tslFn` in setup() pass.
  23145. return this.call( builder ).build( builder, output );
  23146. }
  23147. return super.generate( builder, output );
  23148. }
  23149. }
  23150. class ShaderNodeInternal extends Node {
  23151. constructor( jsFunc ) {
  23152. super();
  23153. this.jsFunc = jsFunc;
  23154. this.layout = null;
  23155. this.global = true;
  23156. }
  23157. get isArrayInput() {
  23158. return /^\((\s+)?\[/.test( this.jsFunc.toString() );
  23159. }
  23160. setLayout( layout ) {
  23161. this.layout = layout;
  23162. return this;
  23163. }
  23164. call( inputs = null ) {
  23165. nodeObjects( inputs );
  23166. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  23167. }
  23168. setup() {
  23169. return this.call();
  23170. }
  23171. }
  23172. const bools = [ false, true ];
  23173. const uints = [ 0, 1, 2, 3 ];
  23174. const ints = [ - 1, - 2 ];
  23175. 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 ];
  23176. const boolsCacheMap = new Map();
  23177. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  23178. const uintsCacheMap = new Map();
  23179. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  23180. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  23181. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  23182. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  23183. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  23184. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  23185. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  23186. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  23187. const getConstNode = ( value, type ) => {
  23188. if ( constNodesCacheMap.has( value ) ) {
  23189. return constNodesCacheMap.get( value );
  23190. } else if ( value.isNode === true ) {
  23191. return value;
  23192. } else {
  23193. return new ConstNode( value, type );
  23194. }
  23195. };
  23196. const safeGetNodeType = ( node ) => {
  23197. try {
  23198. return node.getNodeType();
  23199. } catch ( _ ) {
  23200. return undefined;
  23201. }
  23202. };
  23203. const ConvertType = function ( type, cacheMap = null ) {
  23204. return ( ...params ) => {
  23205. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  23206. params = [ getValueFromType( type, ...params ) ];
  23207. }
  23208. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  23209. return nodeObject( cacheMap.get( params[ 0 ] ) );
  23210. }
  23211. if ( params.length === 1 ) {
  23212. const node = getConstNode( params[ 0 ], type );
  23213. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  23214. return nodeObject( new ConvertNode( node, type ) );
  23215. }
  23216. const nodes = params.map( param => getConstNode( param ) );
  23217. return nodeObject( new JoinNode( nodes, type ) );
  23218. };
  23219. };
  23220. // exports
  23221. const defined = ( value ) => value && value.value;
  23222. // utils
  23223. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  23224. // shader node base
  23225. function ShaderNode( jsFunc ) {
  23226. return new Proxy( new ShaderNodeInternal( jsFunc ), shaderNodeHandler );
  23227. }
  23228. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  23229. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  23230. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  23231. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  23232. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  23233. const tslFn = ( jsFunc ) => {
  23234. const shaderNode = new ShaderNode( jsFunc );
  23235. const fn = ( ...params ) => {
  23236. let inputs;
  23237. nodeObjects( params );
  23238. if ( params[ 0 ] && params[ 0 ].isNode ) {
  23239. inputs = [ ...params ];
  23240. } else {
  23241. inputs = params[ 0 ];
  23242. }
  23243. return shaderNode.call( inputs );
  23244. };
  23245. fn.shaderNode = shaderNode;
  23246. fn.setLayout = ( layout ) => {
  23247. shaderNode.setLayout( layout );
  23248. return fn;
  23249. };
  23250. return fn;
  23251. };
  23252. addNodeClass( 'ShaderNode', ShaderNode );
  23253. //
  23254. addNodeElement( 'toGlobal', ( node ) => {
  23255. node.global = true;
  23256. return node;
  23257. } );
  23258. //
  23259. const setCurrentStack = ( stack ) => {
  23260. currentStack = stack;
  23261. };
  23262. const getCurrentStack = () => currentStack;
  23263. const If = ( ...params ) => currentStack.if( ...params );
  23264. function append( node ) {
  23265. if ( currentStack ) currentStack.add( node );
  23266. return node;
  23267. }
  23268. addNodeElement( 'append', append );
  23269. // types
  23270. // @TODO: Maybe export from ConstNode.js?
  23271. const color = new ConvertType( 'color' );
  23272. const float = new ConvertType( 'float', cacheMaps.float );
  23273. const int = new ConvertType( 'int', cacheMaps.ints );
  23274. const uint = new ConvertType( 'uint', cacheMaps.uint );
  23275. const bool = new ConvertType( 'bool', cacheMaps.bool );
  23276. const vec2 = new ConvertType( 'vec2' );
  23277. const ivec2 = new ConvertType( 'ivec2' );
  23278. const uvec2 = new ConvertType( 'uvec2' );
  23279. const bvec2 = new ConvertType( 'bvec2' );
  23280. const vec3 = new ConvertType( 'vec3' );
  23281. const ivec3 = new ConvertType( 'ivec3' );
  23282. const uvec3 = new ConvertType( 'uvec3' );
  23283. const bvec3 = new ConvertType( 'bvec3' );
  23284. const vec4 = new ConvertType( 'vec4' );
  23285. const ivec4 = new ConvertType( 'ivec4' );
  23286. const uvec4 = new ConvertType( 'uvec4' );
  23287. const bvec4 = new ConvertType( 'bvec4' );
  23288. const mat2 = new ConvertType( 'mat2' );
  23289. const imat2 = new ConvertType( 'imat2' );
  23290. const umat2 = new ConvertType( 'umat2' );
  23291. const bmat2 = new ConvertType( 'bmat2' );
  23292. const mat3 = new ConvertType( 'mat3' );
  23293. const imat3 = new ConvertType( 'imat3' );
  23294. const umat3 = new ConvertType( 'umat3' );
  23295. const bmat3 = new ConvertType( 'bmat3' );
  23296. const mat4 = new ConvertType( 'mat4' );
  23297. const imat4 = new ConvertType( 'imat4' );
  23298. const umat4 = new ConvertType( 'umat4' );
  23299. const bmat4 = new ConvertType( 'bmat4' );
  23300. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  23301. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  23302. addNodeElement( 'toColor', color );
  23303. addNodeElement( 'toFloat', float );
  23304. addNodeElement( 'toInt', int );
  23305. addNodeElement( 'toUint', uint );
  23306. addNodeElement( 'toBool', bool );
  23307. addNodeElement( 'toVec2', vec2 );
  23308. addNodeElement( 'toIvec2', ivec2 );
  23309. addNodeElement( 'toUvec2', uvec2 );
  23310. addNodeElement( 'toBvec2', bvec2 );
  23311. addNodeElement( 'toVec3', vec3 );
  23312. addNodeElement( 'toIvec3', ivec3 );
  23313. addNodeElement( 'toUvec3', uvec3 );
  23314. addNodeElement( 'toBvec3', bvec3 );
  23315. addNodeElement( 'toVec4', vec4 );
  23316. addNodeElement( 'toIvec4', ivec4 );
  23317. addNodeElement( 'toUvec4', uvec4 );
  23318. addNodeElement( 'toBvec4', bvec4 );
  23319. addNodeElement( 'toMat2', mat2 );
  23320. addNodeElement( 'toImat2', imat2 );
  23321. addNodeElement( 'toUmat2', umat2 );
  23322. addNodeElement( 'toBmat2', bmat2 );
  23323. addNodeElement( 'toMat3', mat3 );
  23324. addNodeElement( 'toImat3', imat3 );
  23325. addNodeElement( 'toUmat3', umat3 );
  23326. addNodeElement( 'toBmat3', bmat3 );
  23327. addNodeElement( 'toMat4', mat4 );
  23328. addNodeElement( 'toImat4', imat4 );
  23329. addNodeElement( 'toUmat4', umat4 );
  23330. addNodeElement( 'toBmat4', bmat4 );
  23331. // basic nodes
  23332. // HACK - we cannot export them from the corresponding files because of the cyclic dependency
  23333. const element = nodeProxy( ArrayElementNode );
  23334. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  23335. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  23336. addNodeElement( 'element', element );
  23337. addNodeElement( 'convert', convert );
  23338. class AssignNode extends TempNode {
  23339. constructor( targetNode, sourceNode ) {
  23340. super();
  23341. this.targetNode = targetNode;
  23342. this.sourceNode = sourceNode;
  23343. }
  23344. hasDependencies() {
  23345. return false;
  23346. }
  23347. getNodeType( builder, output ) {
  23348. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23349. }
  23350. needsSplitAssign( builder ) {
  23351. const { targetNode } = this;
  23352. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23353. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23354. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23355. return assignDiferentVector;
  23356. }
  23357. return false;
  23358. }
  23359. generate( builder, output ) {
  23360. const { targetNode, sourceNode } = this;
  23361. const needsSplitAssign = this.needsSplitAssign( builder );
  23362. const targetType = targetNode.getNodeType( builder );
  23363. const target = targetNode.context( { assign: true } ).build( builder );
  23364. const source = sourceNode.build( builder, targetType );
  23365. const sourceType = sourceNode.getNodeType( builder );
  23366. const nodeData = builder.getDataFromNode( this );
  23367. //
  23368. let snippet;
  23369. if ( nodeData.initialized === true ) {
  23370. if ( output !== 'void' ) {
  23371. snippet = target;
  23372. }
  23373. } else if ( needsSplitAssign ) {
  23374. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23375. const sourceProperty = builder.getPropertyName( sourceVar );
  23376. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  23377. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23378. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23379. const component = targetNode.components[ i ];
  23380. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  23381. }
  23382. if ( output !== 'void' ) {
  23383. snippet = target;
  23384. }
  23385. } else {
  23386. snippet = `${ target } = ${ source }`;
  23387. if ( output === 'void' || sourceType === 'void' ) {
  23388. builder.addLineFlowCode( snippet );
  23389. if ( output !== 'void' ) {
  23390. snippet = target;
  23391. }
  23392. }
  23393. }
  23394. nodeData.initialized = true;
  23395. return builder.format( snippet, targetType, output );
  23396. }
  23397. }
  23398. const assign = nodeProxy( AssignNode );
  23399. addNodeClass( 'AssignNode', AssignNode );
  23400. addNodeElement( 'assign', assign );
  23401. class VaryingNode extends Node {
  23402. constructor( node, name = null ) {
  23403. super();
  23404. this.node = node;
  23405. this.name = name;
  23406. this.isVaryingNode = true;
  23407. }
  23408. isGlobal() {
  23409. return true;
  23410. }
  23411. getHash( builder ) {
  23412. return this.name || super.getHash( builder );
  23413. }
  23414. getNodeType( builder ) {
  23415. // VaryingNode is auto type
  23416. return this.node.getNodeType( builder );
  23417. }
  23418. setupVarying( builder ) {
  23419. const properties = builder.getNodeProperties( this );
  23420. let varying = properties.varying;
  23421. if ( varying === undefined ) {
  23422. const name = this.name;
  23423. const type = this.getNodeType( builder );
  23424. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23425. properties.node = this.node;
  23426. }
  23427. // this property can be used to check if the varying can be optimized for a variable
  23428. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23429. return varying;
  23430. }
  23431. setup( builder ) {
  23432. this.setupVarying( builder );
  23433. }
  23434. analyze( builder ) {
  23435. this.setupVarying( builder );
  23436. return this.node.analyze( builder );
  23437. }
  23438. generate( builder ) {
  23439. const properties = builder.getNodeProperties( this );
  23440. const varying = this.setupVarying( builder );
  23441. if ( properties.propertyName === undefined ) {
  23442. const type = this.getNodeType( builder );
  23443. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23444. // force node run in vertex stage
  23445. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23446. properties.propertyName = propertyName;
  23447. }
  23448. return builder.getPropertyName( varying );
  23449. }
  23450. }
  23451. const varying = nodeProxy( VaryingNode );
  23452. addNodeElement( 'varying', varying );
  23453. addNodeClass( 'VaryingNode', VaryingNode );
  23454. class AttributeNode extends Node {
  23455. constructor( attributeName, nodeType = null, defaultNode = null ) {
  23456. super( nodeType );
  23457. this.defaultNode = defaultNode;
  23458. this.global = true;
  23459. this._attributeName = attributeName;
  23460. }
  23461. getHash( builder ) {
  23462. return this.getAttributeName( builder );
  23463. }
  23464. getNodeType( builder ) {
  23465. let nodeType = super.getNodeType( builder );
  23466. if ( nodeType === null ) {
  23467. const attributeName = this.getAttributeName( builder );
  23468. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23469. const attribute = builder.geometry.getAttribute( attributeName );
  23470. nodeType = builder.getTypeFromAttribute( attribute );
  23471. } else {
  23472. nodeType = 'float';
  23473. }
  23474. }
  23475. return nodeType;
  23476. }
  23477. setAttributeName( attributeName ) {
  23478. this._attributeName = attributeName;
  23479. return this;
  23480. }
  23481. getAttributeName( /*builder*/ ) {
  23482. return this._attributeName;
  23483. }
  23484. generate( builder ) {
  23485. const attributeName = this.getAttributeName( builder );
  23486. const nodeType = this.getNodeType( builder );
  23487. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23488. if ( geometryAttribute === true ) {
  23489. const attribute = builder.geometry.getAttribute( attributeName );
  23490. const attributeType = builder.getTypeFromAttribute( attribute );
  23491. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23492. if ( builder.shaderStage === 'vertex' ) {
  23493. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23494. } else {
  23495. const nodeVarying = varying( this );
  23496. return nodeVarying.build( builder, nodeType );
  23497. }
  23498. } else {
  23499. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23500. const { defaultNode } = this;
  23501. if ( defaultNode !== null ) {
  23502. return defaultNode.build( builder, nodeType );
  23503. } else {
  23504. return builder.generateConst( nodeType );
  23505. }
  23506. }
  23507. }
  23508. }
  23509. const attribute = ( name, nodeType, defaultNode ) => nodeObject( new AttributeNode( name, nodeType, nodeObject( defaultNode ) ) );
  23510. addNodeClass( 'AttributeNode', AttributeNode );
  23511. class BypassNode extends Node {
  23512. constructor( returnNode, callNode ) {
  23513. super();
  23514. this.isBypassNode = true;
  23515. this.outputNode = returnNode;
  23516. this.callNode = callNode;
  23517. }
  23518. getNodeType( builder ) {
  23519. return this.outputNode.getNodeType( builder );
  23520. }
  23521. generate( builder ) {
  23522. const snippet = this.callNode.build( builder, 'void' );
  23523. if ( snippet !== '' ) {
  23524. builder.addLineFlowCode( snippet );
  23525. }
  23526. return this.outputNode.build( builder );
  23527. }
  23528. }
  23529. const bypass = nodeProxy( BypassNode );
  23530. addNodeElement( 'bypass', bypass );
  23531. addNodeClass( 'BypassNode', BypassNode );
  23532. class CacheNode extends Node {
  23533. constructor( node, parent = true ) {
  23534. super();
  23535. this.node = node;
  23536. this.parent = parent;
  23537. this.isCacheNode = true;
  23538. }
  23539. getNodeType( builder ) {
  23540. return this.node.getNodeType( builder );
  23541. }
  23542. build( builder, ...params ) {
  23543. const previousCache = builder.getCache();
  23544. const cache = builder.getCacheFromNode( this, parent );
  23545. builder.setCache( cache );
  23546. const data = this.node.build( builder, ...params );
  23547. builder.setCache( previousCache );
  23548. return data;
  23549. }
  23550. }
  23551. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23552. addNodeElement( 'cache', cache );
  23553. addNodeClass( 'CacheNode', CacheNode );
  23554. class ContextNode extends Node {
  23555. constructor( node, context = {} ) {
  23556. super();
  23557. this.isContextNode = true;
  23558. this.node = node;
  23559. this.context = context;
  23560. }
  23561. getNodeType( builder ) {
  23562. return this.node.getNodeType( builder );
  23563. }
  23564. analyze( builder ) {
  23565. this.node.build( builder );
  23566. }
  23567. setup( builder ) {
  23568. const previousContext = builder.getContext();
  23569. builder.setContext( { ...builder.context, ...this.context } );
  23570. const node = this.node.build( builder );
  23571. builder.setContext( previousContext );
  23572. return node;
  23573. }
  23574. generate( builder, output ) {
  23575. const previousContext = builder.getContext();
  23576. builder.setContext( { ...builder.context, ...this.context } );
  23577. const snippet = this.node.build( builder, output );
  23578. builder.setContext( previousContext );
  23579. return snippet;
  23580. }
  23581. }
  23582. const context = nodeProxy( ContextNode );
  23583. const label = ( node, name ) => context( node, { label: name } );
  23584. addNodeElement( 'context', context );
  23585. addNodeElement( 'label', label );
  23586. addNodeClass( 'ContextNode', ContextNode );
  23587. class IndexNode extends Node {
  23588. constructor( scope ) {
  23589. super( 'uint' );
  23590. this.scope = scope;
  23591. this.isInstanceIndexNode = true;
  23592. }
  23593. generate( builder ) {
  23594. const nodeType = this.getNodeType( builder );
  23595. const scope = this.scope;
  23596. let propertyName;
  23597. if ( scope === IndexNode.VERTEX ) {
  23598. propertyName = builder.getVertexIndex();
  23599. } else if ( scope === IndexNode.INSTANCE ) {
  23600. propertyName = builder.getInstanceIndex();
  23601. } else if ( scope === IndexNode.DRAW ) {
  23602. propertyName = builder.getDrawIndex();
  23603. } else {
  23604. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  23605. }
  23606. let output;
  23607. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23608. output = propertyName;
  23609. } else {
  23610. const nodeVarying = varying( this );
  23611. output = nodeVarying.build( builder, nodeType );
  23612. }
  23613. return output;
  23614. }
  23615. }
  23616. IndexNode.VERTEX = 'vertex';
  23617. IndexNode.INSTANCE = 'instance';
  23618. IndexNode.DRAW = 'draw';
  23619. const vertexIndex = nodeImmutable( IndexNode, IndexNode.VERTEX );
  23620. const instanceIndex = nodeImmutable( IndexNode, IndexNode.INSTANCE );
  23621. const drawIndex = nodeImmutable( IndexNode, IndexNode.DRAW );
  23622. addNodeClass( 'IndexNode', IndexNode );
  23623. class LightingModel {
  23624. start( /*input, stack, builder*/ ) { }
  23625. finish( /*input, stack, builder*/ ) { }
  23626. direct( /*input, stack, builder*/ ) { }
  23627. directRectArea( /*input, stack, builder*/ ) {}
  23628. indirect( /*input, stack, builder*/ ) { }
  23629. ambientOcclusion( /*input, stack, builder*/ ) { }
  23630. }
  23631. class VarNode extends Node {
  23632. constructor( node, name = null ) {
  23633. super();
  23634. this.node = node;
  23635. this.name = name;
  23636. this.global = true;
  23637. this.isVarNode = true;
  23638. }
  23639. getHash( builder ) {
  23640. return this.name || super.getHash( builder );
  23641. }
  23642. getNodeType( builder ) {
  23643. return this.node.getNodeType( builder );
  23644. }
  23645. generate( builder ) {
  23646. const { node, name } = this;
  23647. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23648. const propertyName = builder.getPropertyName( nodeVar );
  23649. const snippet = node.build( builder, nodeVar.type );
  23650. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23651. return propertyName;
  23652. }
  23653. }
  23654. const temp = nodeProxy( VarNode );
  23655. addNodeElement( 'temp', temp ); // @TODO: Will be removed in the future
  23656. addNodeElement( 'toVar', ( ...params ) => temp( ...params ).append() );
  23657. addNodeClass( 'VarNode', VarNode );
  23658. class NodeAttribute {
  23659. constructor( name, type, node = null ) {
  23660. this.isNodeAttribute = true;
  23661. this.name = name;
  23662. this.type = type;
  23663. this.node = node;
  23664. }
  23665. }
  23666. class NodeUniform {
  23667. constructor( name, type, node ) {
  23668. this.isNodeUniform = true;
  23669. this.name = name;
  23670. this.type = type;
  23671. this.node = node.getSelf();
  23672. }
  23673. get value() {
  23674. return this.node.value;
  23675. }
  23676. set value( val ) {
  23677. this.node.value = val;
  23678. }
  23679. get id() {
  23680. return this.node.id;
  23681. }
  23682. get groupNode() {
  23683. return this.node.groupNode;
  23684. }
  23685. }
  23686. class NodeVar {
  23687. constructor( name, type ) {
  23688. this.isNodeVar = true;
  23689. this.name = name;
  23690. this.type = type;
  23691. }
  23692. }
  23693. class NodeVarying extends NodeVar {
  23694. constructor( name, type ) {
  23695. super( name, type );
  23696. this.needsInterpolation = false;
  23697. this.isNodeVarying = true;
  23698. }
  23699. }
  23700. class NodeCode {
  23701. constructor( name, type, code = '' ) {
  23702. this.name = name;
  23703. this.type = type;
  23704. this.code = code;
  23705. Object.defineProperty( this, 'isNodeCode', { value: true } );
  23706. }
  23707. }
  23708. class NodeKeywords {
  23709. constructor() {
  23710. this.keywords = [];
  23711. this.nodes = {};
  23712. this.keywordsCallback = {};
  23713. }
  23714. getNode( name ) {
  23715. let node = this.nodes[ name ];
  23716. if ( node === undefined && this.keywordsCallback[ name ] !== undefined ) {
  23717. node = this.keywordsCallback[ name ]( name );
  23718. this.nodes[ name ] = node;
  23719. }
  23720. return node;
  23721. }
  23722. addKeyword( name, callback ) {
  23723. this.keywords.push( name );
  23724. this.keywordsCallback[ name ] = callback;
  23725. return this;
  23726. }
  23727. parse( code ) {
  23728. const keywordNames = this.keywords;
  23729. const regExp = new RegExp( `\\b${keywordNames.join( '\\b|\\b' )}\\b`, 'g' );
  23730. const codeKeywords = code.match( regExp );
  23731. const keywordNodes = [];
  23732. if ( codeKeywords !== null ) {
  23733. for ( const keyword of codeKeywords ) {
  23734. const node = this.getNode( keyword );
  23735. if ( node !== undefined && keywordNodes.indexOf( node ) === - 1 ) {
  23736. keywordNodes.push( node );
  23737. }
  23738. }
  23739. }
  23740. return keywordNodes;
  23741. }
  23742. include( builder, code ) {
  23743. const keywordNodes = this.parse( code );
  23744. for ( const keywordNode of keywordNodes ) {
  23745. keywordNode.build( builder );
  23746. }
  23747. }
  23748. }
  23749. let id$1 = 0;
  23750. class NodeCache {
  23751. constructor( parent = null ) {
  23752. this.id = id$1 ++;
  23753. this.nodesData = new WeakMap();
  23754. this.parent = parent;
  23755. }
  23756. getData( node ) {
  23757. let data = this.nodesData.get( node );
  23758. if ( data === undefined && this.parent !== null ) {
  23759. data = this.parent.getData( node );
  23760. }
  23761. return data;
  23762. }
  23763. setData( node, data ) {
  23764. this.nodesData.set( node, data );
  23765. }
  23766. }
  23767. class PropertyNode extends Node {
  23768. constructor( nodeType, name = null, varying = false ) {
  23769. super( nodeType );
  23770. this.name = name;
  23771. this.varying = varying;
  23772. this.isPropertyNode = true;
  23773. }
  23774. getHash( builder ) {
  23775. return this.name || super.getHash( builder );
  23776. }
  23777. isGlobal( /*builder*/ ) {
  23778. return true;
  23779. }
  23780. generate( builder ) {
  23781. let nodeVar;
  23782. if ( this.varying === true ) {
  23783. nodeVar = builder.getVaryingFromNode( this, this.name );
  23784. nodeVar.needsInterpolation = true;
  23785. } else {
  23786. nodeVar = builder.getVarFromNode( this, this.name );
  23787. }
  23788. return builder.getPropertyName( nodeVar );
  23789. }
  23790. }
  23791. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23792. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23793. const diffuseColor = nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23794. const emissive = nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23795. const roughness = nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23796. const metalness = nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23797. const clearcoat = nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23798. const clearcoatRoughness = nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23799. const sheen = nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23800. const sheenRoughness = nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23801. const iridescence = nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23802. const iridescenceIOR = nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23803. const iridescenceThickness = nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23804. const alphaT = nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23805. const anisotropy = nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23806. const anisotropyT = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23807. const anisotropyB = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23808. const specularColor = nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23809. const specularF90 = nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23810. const shininess = nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23811. const output = nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23812. const dashSize = nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23813. const gapSize = nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23814. const pointWidth = nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23815. const ior = nodeImmutable( PropertyNode, 'float', 'IOR' );
  23816. const transmission = nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23817. const thickness = nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23818. const attenuationDistance = nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23819. const attenuationColor = nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23820. const dispersion = nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23821. addNodeClass( 'PropertyNode', PropertyNode );
  23822. class ParameterNode extends PropertyNode {
  23823. constructor( nodeType, name = null ) {
  23824. super( nodeType, name );
  23825. this.isParameterNode = true;
  23826. }
  23827. getHash() {
  23828. return this.uuid;
  23829. }
  23830. generate() {
  23831. return this.name;
  23832. }
  23833. }
  23834. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23835. addNodeClass( 'ParameterNode', ParameterNode );
  23836. class CodeNode extends Node {
  23837. constructor( code = '', includes = [], language = '' ) {
  23838. super( 'code' );
  23839. this.isCodeNode = true;
  23840. this.code = code;
  23841. this.language = language;
  23842. this.includes = includes;
  23843. }
  23844. isGlobal() {
  23845. return true;
  23846. }
  23847. setIncludes( includes ) {
  23848. this.includes = includes;
  23849. return this;
  23850. }
  23851. getIncludes( /*builder*/ ) {
  23852. return this.includes;
  23853. }
  23854. generate( builder ) {
  23855. const includes = this.getIncludes( builder );
  23856. for ( const include of includes ) {
  23857. include.build( builder );
  23858. }
  23859. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23860. nodeCode.code = this.code;
  23861. return nodeCode.code;
  23862. }
  23863. serialize( data ) {
  23864. super.serialize( data );
  23865. data.code = this.code;
  23866. data.language = this.language;
  23867. }
  23868. deserialize( data ) {
  23869. super.deserialize( data );
  23870. this.code = data.code;
  23871. this.language = data.language;
  23872. }
  23873. }
  23874. const code = nodeProxy( CodeNode );
  23875. const js = ( src, includes ) => code( src, includes, 'js' );
  23876. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23877. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23878. addNodeClass( 'CodeNode', CodeNode );
  23879. class FunctionNode extends CodeNode {
  23880. constructor( code = '', includes = [], language = '' ) {
  23881. super( code, includes, language );
  23882. this.keywords = {};
  23883. }
  23884. getNodeType( builder ) {
  23885. return this.getNodeFunction( builder ).type;
  23886. }
  23887. getInputs( builder ) {
  23888. return this.getNodeFunction( builder ).inputs;
  23889. }
  23890. getNodeFunction( builder ) {
  23891. const nodeData = builder.getDataFromNode( this );
  23892. let nodeFunction = nodeData.nodeFunction;
  23893. if ( nodeFunction === undefined ) {
  23894. nodeFunction = builder.parser.parseFunction( this.code );
  23895. nodeData.nodeFunction = nodeFunction;
  23896. }
  23897. return nodeFunction;
  23898. }
  23899. generate( builder, output ) {
  23900. super.generate( builder );
  23901. const nodeFunction = this.getNodeFunction( builder );
  23902. const name = nodeFunction.name;
  23903. const type = nodeFunction.type;
  23904. const nodeCode = builder.getCodeFromNode( this, type );
  23905. if ( name !== '' ) {
  23906. // use a custom property name
  23907. nodeCode.name = name;
  23908. }
  23909. const propertyName = builder.getPropertyName( nodeCode );
  23910. let code = this.getNodeFunction( builder ).getCode( propertyName );
  23911. const keywords = this.keywords;
  23912. const keywordsProperties = Object.keys( keywords );
  23913. if ( keywordsProperties.length > 0 ) {
  23914. for ( const property of keywordsProperties ) {
  23915. const propertyRegExp = new RegExp( `\\b${property}\\b`, 'g' );
  23916. const nodeProperty = keywords[ property ].build( builder, 'property' );
  23917. code = code.replace( propertyRegExp, nodeProperty );
  23918. }
  23919. }
  23920. nodeCode.code = code + '\n';
  23921. if ( output === 'property' ) {
  23922. return propertyName;
  23923. } else {
  23924. return builder.format( `${ propertyName }()`, type, output );
  23925. }
  23926. }
  23927. }
  23928. const nativeFn = ( code, includes = [], language = '' ) => {
  23929. for ( let i = 0; i < includes.length; i ++ ) {
  23930. const include = includes[ i ];
  23931. // TSL Function: glslFn, wgslFn
  23932. if ( typeof include === 'function' ) {
  23933. includes[ i ] = include.functionNode;
  23934. }
  23935. }
  23936. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23937. const fn = ( ...params ) => functionNode.call( ...params );
  23938. fn.functionNode = functionNode;
  23939. return fn;
  23940. };
  23941. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23942. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23943. addNodeClass( 'FunctionNode', FunctionNode );
  23944. class UniformGroupNode extends Node {
  23945. constructor( name, shared = false ) {
  23946. super( 'string' );
  23947. this.name = name;
  23948. this.version = 0;
  23949. this.shared = shared;
  23950. this.isUniformGroup = true;
  23951. }
  23952. set needsUpdate( value ) {
  23953. if ( value === true ) this.version ++;
  23954. }
  23955. }
  23956. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23957. const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true );
  23958. const frameGroup = sharedUniformGroup( 'frame' );
  23959. const renderGroup = sharedUniformGroup( 'render' );
  23960. const objectGroup = uniformGroup( 'object' );
  23961. addNodeClass( 'UniformGroupNode', UniformGroupNode );
  23962. class UniformNode extends InputNode {
  23963. constructor( value, nodeType = null ) {
  23964. super( value, nodeType );
  23965. this.isUniformNode = true;
  23966. this.name = '';
  23967. this.groupNode = objectGroup;
  23968. }
  23969. label( name ) {
  23970. this.name = name;
  23971. return this;
  23972. }
  23973. setGroup( group ) {
  23974. this.groupNode = group;
  23975. return this;
  23976. }
  23977. getGroup() {
  23978. return this.groupNode;
  23979. }
  23980. getUniformHash( builder ) {
  23981. return this.getHash( builder );
  23982. }
  23983. onUpdate( callback, updateType ) {
  23984. const self = this.getSelf();
  23985. callback = callback.bind( self );
  23986. return super.onUpdate( ( frame ) => {
  23987. const value = callback( frame, self );
  23988. if ( value !== undefined ) {
  23989. this.value = value;
  23990. }
  23991. }, updateType );
  23992. }
  23993. generate( builder, output ) {
  23994. const type = this.getNodeType( builder );
  23995. const hash = this.getUniformHash( builder );
  23996. let sharedNode = builder.getNodeFromHash( hash );
  23997. if ( sharedNode === undefined ) {
  23998. builder.setHashNode( this, hash );
  23999. sharedNode = this;
  24000. }
  24001. const sharedNodeType = sharedNode.getInputType( builder );
  24002. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  24003. const propertyName = builder.getPropertyName( nodeUniform );
  24004. if ( builder.context.label !== undefined ) delete builder.context.label;
  24005. return builder.format( propertyName, type, output );
  24006. }
  24007. }
  24008. const uniform = ( arg1, arg2 ) => {
  24009. const nodeType = getConstNodeType( arg2 || arg1 );
  24010. // @TODO: get ConstNode from .traverse() in the future
  24011. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  24012. return nodeObject( new UniformNode( value, nodeType ) );
  24013. };
  24014. addNodeClass( 'UniformNode', UniformNode );
  24015. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24016. class TextureSizeNode extends Node {
  24017. constructor( textureNode, levelNode = null ) {
  24018. super( 'uvec2' );
  24019. this.isTextureSizeNode = true;
  24020. this.textureNode = textureNode;
  24021. this.levelNode = levelNode;
  24022. }
  24023. generate( builder, output ) {
  24024. const textureProperty = this.textureNode.build( builder, 'property' );
  24025. const levelNode = this.levelNode.build( builder, 'int' );
  24026. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  24027. }
  24028. }
  24029. const textureSize = nodeProxy( TextureSizeNode );
  24030. addNodeElement( 'textureSize', textureSize );
  24031. addNodeClass( 'TextureSizeNode', TextureSizeNode );
  24032. class OperatorNode extends TempNode {
  24033. constructor( op, aNode, bNode, ...params ) {
  24034. super();
  24035. if ( params.length > 0 ) {
  24036. let finalOp = new OperatorNode( op, aNode, bNode );
  24037. for ( let i = 0; i < params.length - 1; i ++ ) {
  24038. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  24039. }
  24040. aNode = finalOp;
  24041. bNode = params[ params.length - 1 ];
  24042. }
  24043. this.op = op;
  24044. this.aNode = aNode;
  24045. this.bNode = bNode;
  24046. }
  24047. getNodeType( builder, output ) {
  24048. const op = this.op;
  24049. const aNode = this.aNode;
  24050. const bNode = this.bNode;
  24051. const typeA = aNode.getNodeType( builder );
  24052. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24053. if ( typeA === 'void' || typeB === 'void' ) {
  24054. return 'void';
  24055. } else if ( op === '%' ) {
  24056. return typeA;
  24057. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  24058. return builder.getIntegerType( typeA );
  24059. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  24060. return 'bool';
  24061. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  24062. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  24063. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  24064. } else {
  24065. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  24066. return typeB;
  24067. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24068. // matrix x vector
  24069. return builder.getVectorFromMatrix( typeA );
  24070. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24071. // vector x matrix
  24072. return builder.getVectorFromMatrix( typeB );
  24073. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  24074. // anytype x anytype: use the greater length vector
  24075. return typeB;
  24076. }
  24077. return typeA;
  24078. }
  24079. }
  24080. generate( builder, output ) {
  24081. const op = this.op;
  24082. const aNode = this.aNode;
  24083. const bNode = this.bNode;
  24084. const type = this.getNodeType( builder, output );
  24085. let typeA = null;
  24086. let typeB = null;
  24087. if ( type !== 'void' ) {
  24088. typeA = aNode.getNodeType( builder );
  24089. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24090. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  24091. if ( builder.isVector( typeA ) ) {
  24092. typeB = typeA;
  24093. } else {
  24094. typeA = typeB = 'float';
  24095. }
  24096. } else if ( op === '>>' || op === '<<' ) {
  24097. typeA = type;
  24098. typeB = builder.changeComponentType( typeB, 'uint' );
  24099. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24100. // matrix x vector
  24101. typeB = builder.getVectorFromMatrix( typeA );
  24102. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24103. // vector x matrix
  24104. typeA = builder.getVectorFromMatrix( typeB );
  24105. } else {
  24106. // anytype x anytype
  24107. typeA = typeB = type;
  24108. }
  24109. } else {
  24110. typeA = typeB = type;
  24111. }
  24112. const a = aNode.build( builder, typeA );
  24113. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  24114. const outputLength = builder.getTypeLength( output );
  24115. const fnOpSnippet = builder.getFunctionOperator( op );
  24116. if ( output !== 'void' ) {
  24117. if ( op === '<' && outputLength > 1 ) {
  24118. return builder.format( `${ builder.getMethod( 'lessThan' ) }( ${ a }, ${ b } )`, type, output );
  24119. } else if ( op === '<=' && outputLength > 1 ) {
  24120. return builder.format( `${ builder.getMethod( 'lessThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24121. } else if ( op === '>' && outputLength > 1 ) {
  24122. return builder.format( `${ builder.getMethod( 'greaterThan' ) }( ${ a }, ${ b } )`, type, output );
  24123. } else if ( op === '>=' && outputLength > 1 ) {
  24124. return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24125. } else if ( op === '!' || op === '~' ) {
  24126. return builder.format( `(${op}${a})`, typeA, output );
  24127. } else if ( fnOpSnippet ) {
  24128. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24129. } else {
  24130. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  24131. }
  24132. } else if ( typeA !== 'void' ) {
  24133. if ( fnOpSnippet ) {
  24134. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24135. } else {
  24136. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  24137. }
  24138. }
  24139. }
  24140. serialize( data ) {
  24141. super.serialize( data );
  24142. data.op = this.op;
  24143. }
  24144. deserialize( data ) {
  24145. super.deserialize( data );
  24146. this.op = data.op;
  24147. }
  24148. }
  24149. const add = nodeProxy( OperatorNode, '+' );
  24150. const sub = nodeProxy( OperatorNode, '-' );
  24151. const mul = nodeProxy( OperatorNode, '*' );
  24152. const div = nodeProxy( OperatorNode, '/' );
  24153. const remainder = nodeProxy( OperatorNode, '%' );
  24154. const equal = nodeProxy( OperatorNode, '==' );
  24155. const notEqual = nodeProxy( OperatorNode, '!=' );
  24156. const lessThan = nodeProxy( OperatorNode, '<' );
  24157. const greaterThan = nodeProxy( OperatorNode, '>' );
  24158. const lessThanEqual = nodeProxy( OperatorNode, '<=' );
  24159. const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
  24160. const and = nodeProxy( OperatorNode, '&&' );
  24161. const or = nodeProxy( OperatorNode, '||' );
  24162. const not = nodeProxy( OperatorNode, '!' );
  24163. const xor = nodeProxy( OperatorNode, '^^' );
  24164. const bitAnd = nodeProxy( OperatorNode, '&' );
  24165. const bitNot = nodeProxy( OperatorNode, '~' );
  24166. const bitOr = nodeProxy( OperatorNode, '|' );
  24167. const bitXor = nodeProxy( OperatorNode, '^' );
  24168. const shiftLeft = nodeProxy( OperatorNode, '<<' );
  24169. const shiftRight = nodeProxy( OperatorNode, '>>' );
  24170. addNodeElement( 'add', add );
  24171. addNodeElement( 'sub', sub );
  24172. addNodeElement( 'mul', mul );
  24173. addNodeElement( 'div', div );
  24174. addNodeElement( 'remainder', remainder );
  24175. addNodeElement( 'equal', equal );
  24176. addNodeElement( 'notEqual', notEqual );
  24177. addNodeElement( 'lessThan', lessThan );
  24178. addNodeElement( 'greaterThan', greaterThan );
  24179. addNodeElement( 'lessThanEqual', lessThanEqual );
  24180. addNodeElement( 'greaterThanEqual', greaterThanEqual );
  24181. addNodeElement( 'and', and );
  24182. addNodeElement( 'or', or );
  24183. addNodeElement( 'not', not );
  24184. addNodeElement( 'xor', xor );
  24185. addNodeElement( 'bitAnd', bitAnd );
  24186. addNodeElement( 'bitNot', bitNot );
  24187. addNodeElement( 'bitOr', bitOr );
  24188. addNodeElement( 'bitXor', bitXor );
  24189. addNodeElement( 'shiftLeft', shiftLeft );
  24190. addNodeElement( 'shiftRight', shiftRight );
  24191. addNodeClass( 'OperatorNode', OperatorNode );
  24192. class MathNode extends TempNode {
  24193. constructor( method, aNode, bNode = null, cNode = null ) {
  24194. super();
  24195. this.method = method;
  24196. this.aNode = aNode;
  24197. this.bNode = bNode;
  24198. this.cNode = cNode;
  24199. }
  24200. getInputType( builder ) {
  24201. const aType = this.aNode.getNodeType( builder );
  24202. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  24203. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  24204. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  24205. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  24206. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  24207. if ( aLen > bLen && aLen > cLen ) {
  24208. return aType;
  24209. } else if ( bLen > cLen ) {
  24210. return bType;
  24211. } else if ( cLen > aLen ) {
  24212. return cType;
  24213. }
  24214. return aType;
  24215. }
  24216. getNodeType( builder ) {
  24217. const method = this.method;
  24218. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  24219. return 'float';
  24220. } else if ( method === MathNode.CROSS ) {
  24221. return 'vec3';
  24222. } else if ( method === MathNode.ALL ) {
  24223. return 'bool';
  24224. } else if ( method === MathNode.EQUALS ) {
  24225. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  24226. } else if ( method === MathNode.MOD ) {
  24227. return this.aNode.getNodeType( builder );
  24228. } else {
  24229. return this.getInputType( builder );
  24230. }
  24231. }
  24232. generate( builder, output ) {
  24233. const method = this.method;
  24234. const type = this.getNodeType( builder );
  24235. const inputType = this.getInputType( builder );
  24236. const a = this.aNode;
  24237. const b = this.bNode;
  24238. const c = this.cNode;
  24239. const isWebGL = builder.renderer.isWebGLRenderer === true;
  24240. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  24241. // dir can be either a direction vector or a normal vector
  24242. // upper-left 3x3 of matrix is assumed to be orthogonal
  24243. let tA = a;
  24244. let tB = b;
  24245. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  24246. tB = vec4( vec3( tB ), 0.0 );
  24247. } else {
  24248. tA = vec4( vec3( tA ), 0.0 );
  24249. }
  24250. const mulNode = mul( tA, tB ).xyz;
  24251. return normalize( mulNode ).build( builder, output );
  24252. } else if ( method === MathNode.NEGATE ) {
  24253. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  24254. } else if ( method === MathNode.ONE_MINUS ) {
  24255. return sub( 1.0, a ).build( builder, output );
  24256. } else if ( method === MathNode.RECIPROCAL ) {
  24257. return div( 1.0, a ).build( builder, output );
  24258. } else if ( method === MathNode.DIFFERENCE ) {
  24259. return abs( sub( a, b ) ).build( builder, output );
  24260. } else {
  24261. const params = [];
  24262. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  24263. params.push(
  24264. a.build( builder, type ),
  24265. b.build( builder, type )
  24266. );
  24267. } else if ( method === MathNode.STEP ) {
  24268. params.push(
  24269. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  24270. b.build( builder, inputType )
  24271. );
  24272. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  24273. params.push(
  24274. a.build( builder, inputType ),
  24275. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24276. );
  24277. } else if ( method === MathNode.REFRACT ) {
  24278. params.push(
  24279. a.build( builder, inputType ),
  24280. b.build( builder, inputType ),
  24281. c.build( builder, 'float' )
  24282. );
  24283. } else if ( method === MathNode.MIX ) {
  24284. params.push(
  24285. a.build( builder, inputType ),
  24286. b.build( builder, inputType ),
  24287. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24288. );
  24289. } else {
  24290. params.push( a.build( builder, inputType ) );
  24291. if ( b !== null ) params.push( b.build( builder, inputType ) );
  24292. if ( c !== null ) params.push( c.build( builder, inputType ) );
  24293. }
  24294. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  24295. }
  24296. }
  24297. serialize( data ) {
  24298. super.serialize( data );
  24299. data.method = this.method;
  24300. }
  24301. deserialize( data ) {
  24302. super.deserialize( data );
  24303. this.method = data.method;
  24304. }
  24305. }
  24306. // 1 input
  24307. MathNode.ALL = 'all';
  24308. MathNode.ANY = 'any';
  24309. MathNode.EQUALS = 'equals';
  24310. MathNode.RADIANS = 'radians';
  24311. MathNode.DEGREES = 'degrees';
  24312. MathNode.EXP = 'exp';
  24313. MathNode.EXP2 = 'exp2';
  24314. MathNode.LOG = 'log';
  24315. MathNode.LOG2 = 'log2';
  24316. MathNode.SQRT = 'sqrt';
  24317. MathNode.INVERSE_SQRT = 'inversesqrt';
  24318. MathNode.FLOOR = 'floor';
  24319. MathNode.CEIL = 'ceil';
  24320. MathNode.NORMALIZE = 'normalize';
  24321. MathNode.FRACT = 'fract';
  24322. MathNode.SIN = 'sin';
  24323. MathNode.COS = 'cos';
  24324. MathNode.TAN = 'tan';
  24325. MathNode.ASIN = 'asin';
  24326. MathNode.ACOS = 'acos';
  24327. MathNode.ATAN = 'atan';
  24328. MathNode.ABS = 'abs';
  24329. MathNode.SIGN = 'sign';
  24330. MathNode.LENGTH = 'length';
  24331. MathNode.NEGATE = 'negate';
  24332. MathNode.ONE_MINUS = 'oneMinus';
  24333. MathNode.DFDX = 'dFdx';
  24334. MathNode.DFDY = 'dFdy';
  24335. MathNode.ROUND = 'round';
  24336. MathNode.RECIPROCAL = 'reciprocal';
  24337. MathNode.TRUNC = 'trunc';
  24338. MathNode.FWIDTH = 'fwidth';
  24339. MathNode.BITCAST = 'bitcast';
  24340. MathNode.TRANSPOSE = 'transpose';
  24341. // 2 inputs
  24342. MathNode.ATAN2 = 'atan2';
  24343. MathNode.MIN = 'min';
  24344. MathNode.MAX = 'max';
  24345. MathNode.MOD = 'mod';
  24346. MathNode.STEP = 'step';
  24347. MathNode.REFLECT = 'reflect';
  24348. MathNode.DISTANCE = 'distance';
  24349. MathNode.DIFFERENCE = 'difference';
  24350. MathNode.DOT = 'dot';
  24351. MathNode.CROSS = 'cross';
  24352. MathNode.POW = 'pow';
  24353. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  24354. // 3 inputs
  24355. MathNode.MIX = 'mix';
  24356. MathNode.CLAMP = 'clamp';
  24357. MathNode.REFRACT = 'refract';
  24358. MathNode.SMOOTHSTEP = 'smoothstep';
  24359. MathNode.FACEFORWARD = 'faceforward';
  24360. const EPSILON = float( 1e-6 );
  24361. const INFINITY = float( 1e6 );
  24362. const PI = float( Math.PI );
  24363. const PI2 = float( Math.PI * 2 );
  24364. const all = nodeProxy( MathNode, MathNode.ALL );
  24365. const any = nodeProxy( MathNode, MathNode.ANY );
  24366. const equals = nodeProxy( MathNode, MathNode.EQUALS );
  24367. const radians = nodeProxy( MathNode, MathNode.RADIANS );
  24368. const degrees = nodeProxy( MathNode, MathNode.DEGREES );
  24369. const exp = nodeProxy( MathNode, MathNode.EXP );
  24370. const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
  24371. const log = nodeProxy( MathNode, MathNode.LOG );
  24372. const log2 = nodeProxy( MathNode, MathNode.LOG2 );
  24373. const sqrt = nodeProxy( MathNode, MathNode.SQRT );
  24374. const inverseSqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  24375. const floor = nodeProxy( MathNode, MathNode.FLOOR );
  24376. const ceil = nodeProxy( MathNode, MathNode.CEIL );
  24377. const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
  24378. const fract = nodeProxy( MathNode, MathNode.FRACT );
  24379. const sin = nodeProxy( MathNode, MathNode.SIN );
  24380. const cos = nodeProxy( MathNode, MathNode.COS );
  24381. const tan = nodeProxy( MathNode, MathNode.TAN );
  24382. const asin = nodeProxy( MathNode, MathNode.ASIN );
  24383. const acos = nodeProxy( MathNode, MathNode.ACOS );
  24384. const atan = nodeProxy( MathNode, MathNode.ATAN );
  24385. const abs = nodeProxy( MathNode, MathNode.ABS );
  24386. const sign = nodeProxy( MathNode, MathNode.SIGN );
  24387. const length = nodeProxy( MathNode, MathNode.LENGTH );
  24388. const negate = nodeProxy( MathNode, MathNode.NEGATE );
  24389. const oneMinus = nodeProxy( MathNode, MathNode.ONE_MINUS );
  24390. const dFdx = nodeProxy( MathNode, MathNode.DFDX );
  24391. const dFdy = nodeProxy( MathNode, MathNode.DFDY );
  24392. const round = nodeProxy( MathNode, MathNode.ROUND );
  24393. const reciprocal = nodeProxy( MathNode, MathNode.RECIPROCAL );
  24394. const trunc = nodeProxy( MathNode, MathNode.TRUNC );
  24395. const fwidth = nodeProxy( MathNode, MathNode.FWIDTH );
  24396. const bitcast = nodeProxy( MathNode, MathNode.BITCAST );
  24397. const transpose = nodeProxy( MathNode, MathNode.TRANSPOSE );
  24398. const atan2 = nodeProxy( MathNode, MathNode.ATAN2 );
  24399. const min$1 = nodeProxy( MathNode, MathNode.MIN );
  24400. const max$1 = nodeProxy( MathNode, MathNode.MAX );
  24401. const mod = nodeProxy( MathNode, MathNode.MOD );
  24402. const step = nodeProxy( MathNode, MathNode.STEP );
  24403. const reflect = nodeProxy( MathNode, MathNode.REFLECT );
  24404. const distance = nodeProxy( MathNode, MathNode.DISTANCE );
  24405. const difference = nodeProxy( MathNode, MathNode.DIFFERENCE );
  24406. const dot = nodeProxy( MathNode, MathNode.DOT );
  24407. const cross = nodeProxy( MathNode, MathNode.CROSS );
  24408. const pow = nodeProxy( MathNode, MathNode.POW );
  24409. const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
  24410. const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
  24411. const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
  24412. const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  24413. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  24414. const lengthSq = ( a ) => dot( a, a );
  24415. const mix = nodeProxy( MathNode, MathNode.MIX );
  24416. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  24417. const saturate = ( value ) => clamp( value );
  24418. const refract = nodeProxy( MathNode, MathNode.REFRACT );
  24419. const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  24420. const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD );
  24421. const rand = tslFn( ( [ uv ] ) => {
  24422. const a = 12.9898, b = 78.233, c = 43758.5453;
  24423. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  24424. return fract( sin( sn ).mul( c ) );
  24425. } );
  24426. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  24427. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  24428. addNodeElement( 'all', all );
  24429. addNodeElement( 'any', any );
  24430. addNodeElement( 'equals', equals );
  24431. addNodeElement( 'radians', radians );
  24432. addNodeElement( 'degrees', degrees );
  24433. addNodeElement( 'exp', exp );
  24434. addNodeElement( 'exp2', exp2 );
  24435. addNodeElement( 'log', log );
  24436. addNodeElement( 'log2', log2 );
  24437. addNodeElement( 'sqrt', sqrt );
  24438. addNodeElement( 'inverseSqrt', inverseSqrt );
  24439. addNodeElement( 'floor', floor );
  24440. addNodeElement( 'ceil', ceil );
  24441. addNodeElement( 'normalize', normalize );
  24442. addNodeElement( 'fract', fract );
  24443. addNodeElement( 'sin', sin );
  24444. addNodeElement( 'cos', cos );
  24445. addNodeElement( 'tan', tan );
  24446. addNodeElement( 'asin', asin );
  24447. addNodeElement( 'acos', acos );
  24448. addNodeElement( 'atan', atan );
  24449. addNodeElement( 'abs', abs );
  24450. addNodeElement( 'sign', sign );
  24451. addNodeElement( 'length', length );
  24452. addNodeElement( 'lengthSq', lengthSq );
  24453. addNodeElement( 'negate', negate );
  24454. addNodeElement( 'oneMinus', oneMinus );
  24455. addNodeElement( 'dFdx', dFdx );
  24456. addNodeElement( 'dFdy', dFdy );
  24457. addNodeElement( 'round', round );
  24458. addNodeElement( 'reciprocal', reciprocal );
  24459. addNodeElement( 'trunc', trunc );
  24460. addNodeElement( 'fwidth', fwidth );
  24461. addNodeElement( 'atan2', atan2 );
  24462. addNodeElement( 'min', min$1 );
  24463. addNodeElement( 'max', max$1 );
  24464. addNodeElement( 'mod', mod );
  24465. addNodeElement( 'step', step );
  24466. addNodeElement( 'reflect', reflect );
  24467. addNodeElement( 'distance', distance );
  24468. addNodeElement( 'dot', dot );
  24469. addNodeElement( 'cross', cross );
  24470. addNodeElement( 'pow', pow );
  24471. addNodeElement( 'pow2', pow2 );
  24472. addNodeElement( 'pow3', pow3 );
  24473. addNodeElement( 'pow4', pow4 );
  24474. addNodeElement( 'transformDirection', transformDirection );
  24475. addNodeElement( 'mix', mixElement );
  24476. addNodeElement( 'clamp', clamp );
  24477. addNodeElement( 'refract', refract );
  24478. addNodeElement( 'smoothstep', smoothstepElement );
  24479. addNodeElement( 'faceForward', faceForward );
  24480. addNodeElement( 'difference', difference );
  24481. addNodeElement( 'saturate', saturate );
  24482. addNodeElement( 'cbrt', cbrt );
  24483. addNodeElement( 'transpose', transpose );
  24484. addNodeElement( 'rand', rand );
  24485. addNodeClass( 'MathNode', MathNode );
  24486. const sRGBToLinearShader = tslFn( ( inputs ) => {
  24487. const { value } = inputs;
  24488. const { rgb } = value;
  24489. const a = rgb.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  24490. const b = rgb.mul( 0.0773993808 );
  24491. const factor = rgb.lessThanEqual( 0.04045 );
  24492. const rgbResult = mix( a, b, factor );
  24493. return vec4( rgbResult, value.a );
  24494. } );
  24495. const LinearTosRGBShader = tslFn( ( inputs ) => {
  24496. const { value } = inputs;
  24497. const { rgb } = value;
  24498. const a = rgb.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  24499. const b = rgb.mul( 12.92 );
  24500. const factor = rgb.lessThanEqual( 0.0031308 );
  24501. const rgbResult = mix( a, b, factor );
  24502. return vec4( rgbResult, value.a );
  24503. } );
  24504. const getColorSpaceMethod = ( colorSpace ) => {
  24505. let method = null;
  24506. if ( colorSpace === LinearSRGBColorSpace ) {
  24507. method = 'Linear';
  24508. } else if ( colorSpace === SRGBColorSpace ) {
  24509. method = 'sRGB';
  24510. }
  24511. return method;
  24512. };
  24513. const getMethod = ( source, target ) => {
  24514. return getColorSpaceMethod( source ) + 'To' + getColorSpaceMethod( target );
  24515. };
  24516. class ColorSpaceNode extends TempNode {
  24517. constructor( method, node ) {
  24518. super( 'vec4' );
  24519. this.method = method;
  24520. this.node = node;
  24521. }
  24522. setup() {
  24523. const { method, node } = this;
  24524. if ( method === ColorSpaceNode.LINEAR_TO_LINEAR )
  24525. return node;
  24526. return Methods[ method ]( { value: node } );
  24527. }
  24528. }
  24529. ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
  24530. ColorSpaceNode.LINEAR_TO_sRGB = 'LinearTosRGB';
  24531. ColorSpaceNode.sRGB_TO_LINEAR = 'sRGBToLinear';
  24532. const Methods = {
  24533. [ ColorSpaceNode.LINEAR_TO_sRGB ]: LinearTosRGBShader,
  24534. [ ColorSpaceNode.sRGB_TO_LINEAR ]: sRGBToLinearShader
  24535. };
  24536. const linearToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( LinearSRGBColorSpace, colorSpace ), nodeObject( node ) ) );
  24537. const colorSpaceToLinear = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( colorSpace, LinearSRGBColorSpace ), nodeObject( node ) ) );
  24538. const linearTosRGB = nodeProxy( ColorSpaceNode, ColorSpaceNode.LINEAR_TO_sRGB );
  24539. const sRGBToLinear = nodeProxy( ColorSpaceNode, ColorSpaceNode.sRGB_TO_LINEAR );
  24540. addNodeElement( 'linearTosRGB', linearTosRGB );
  24541. addNodeElement( 'sRGBToLinear', sRGBToLinear );
  24542. addNodeElement( 'linearToColorSpace', linearToColorSpace );
  24543. addNodeElement( 'colorSpaceToLinear', colorSpaceToLinear );
  24544. addNodeClass( 'ColorSpaceNode', ColorSpaceNode );
  24545. class ExpressionNode extends Node {
  24546. constructor( snippet = '', nodeType = 'void' ) {
  24547. super( nodeType );
  24548. this.snippet = snippet;
  24549. }
  24550. generate( builder, output ) {
  24551. const type = this.getNodeType( builder );
  24552. const snippet = this.snippet;
  24553. if ( type === 'void' ) {
  24554. builder.addLineFlowCode( snippet );
  24555. } else {
  24556. return builder.format( `( ${ snippet } )`, type, output );
  24557. }
  24558. }
  24559. }
  24560. const expression = nodeProxy( ExpressionNode );
  24561. addNodeClass( 'ExpressionNode', ExpressionNode );
  24562. class MaxMipLevelNode extends UniformNode {
  24563. constructor( textureNode ) {
  24564. super( 0 );
  24565. this._textureNode = textureNode;
  24566. this.updateType = NodeUpdateType.FRAME;
  24567. }
  24568. get textureNode() {
  24569. return this._textureNode;
  24570. }
  24571. get texture() {
  24572. return this._textureNode.value;
  24573. }
  24574. update() {
  24575. const texture = this.texture;
  24576. const images = texture.images;
  24577. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24578. if ( image && image.width !== undefined ) {
  24579. const { width, height } = image;
  24580. this.value = Math.log2( Math.max( width, height ) );
  24581. }
  24582. }
  24583. }
  24584. const maxMipLevel = nodeProxy( MaxMipLevelNode );
  24585. addNodeClass( 'MaxMipLevelNode', MaxMipLevelNode );
  24586. class TextureNode extends UniformNode {
  24587. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24588. super( value );
  24589. this.isTextureNode = true;
  24590. this.uvNode = uvNode;
  24591. this.levelNode = levelNode;
  24592. this.biasNode = biasNode;
  24593. this.compareNode = null;
  24594. this.depthNode = null;
  24595. this.gradNode = null;
  24596. this.sampler = true;
  24597. this.updateMatrix = false;
  24598. this.updateType = NodeUpdateType.NONE;
  24599. this.referenceNode = null;
  24600. this._value = value;
  24601. this._matrixUniform = null;
  24602. this.setUpdateMatrix( uvNode === null );
  24603. }
  24604. set value( value ) {
  24605. if ( this.referenceNode ) {
  24606. this.referenceNode.value = value;
  24607. } else {
  24608. this._value = value;
  24609. }
  24610. }
  24611. get value() {
  24612. return this.referenceNode ? this.referenceNode.value : this._value;
  24613. }
  24614. getUniformHash( /*builder*/ ) {
  24615. return this.value.uuid;
  24616. }
  24617. getNodeType( /*builder*/ ) {
  24618. if ( this.value.isDepthTexture === true ) return 'float';
  24619. if ( this.value.type === UnsignedIntType ) {
  24620. return 'uvec4';
  24621. } else if ( this.value.type === IntType ) {
  24622. return 'ivec4';
  24623. }
  24624. return 'vec4';
  24625. }
  24626. getInputType( /*builder*/ ) {
  24627. return 'texture';
  24628. }
  24629. getDefaultUV() {
  24630. return uv( this.value.channel );
  24631. }
  24632. updateReference( /*state*/ ) {
  24633. return this.value;
  24634. }
  24635. getTransformedUV( uvNode ) {
  24636. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24637. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24638. }
  24639. setUpdateMatrix( value ) {
  24640. this.updateMatrix = value;
  24641. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24642. return this;
  24643. }
  24644. setupUV( builder, uvNode ) {
  24645. const texture = this.value;
  24646. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24647. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  24648. }
  24649. return uvNode;
  24650. }
  24651. setup( builder ) {
  24652. const properties = builder.getNodeProperties( this );
  24653. properties.referenceNode = this.referenceNode;
  24654. //
  24655. let uvNode = this.uvNode;
  24656. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24657. uvNode = builder.context.getUV( this );
  24658. }
  24659. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24660. if ( this.updateMatrix === true ) {
  24661. uvNode = this.getTransformedUV( uvNode );
  24662. }
  24663. uvNode = this.setupUV( builder, uvNode );
  24664. //
  24665. let levelNode = this.levelNode;
  24666. if ( levelNode === null && builder.context.getTextureLevel ) {
  24667. levelNode = builder.context.getTextureLevel( this );
  24668. }
  24669. //
  24670. properties.uvNode = uvNode;
  24671. properties.levelNode = levelNode;
  24672. properties.biasNode = this.biasNode;
  24673. properties.compareNode = this.compareNode;
  24674. properties.gradNode = this.gradNode;
  24675. properties.depthNode = this.depthNode;
  24676. }
  24677. generateUV( builder, uvNode ) {
  24678. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24679. }
  24680. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24681. const texture = this.value;
  24682. let snippet;
  24683. if ( levelSnippet ) {
  24684. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24685. } else if ( biasSnippet ) {
  24686. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24687. } else if ( gradSnippet ) {
  24688. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24689. } else if ( compareSnippet ) {
  24690. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24691. } else if ( this.sampler === false ) {
  24692. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24693. } else {
  24694. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24695. }
  24696. return snippet;
  24697. }
  24698. generate( builder, output ) {
  24699. const properties = builder.getNodeProperties( this );
  24700. const texture = this.value;
  24701. if ( ! texture || texture.isTexture !== true ) {
  24702. throw new Error( 'TextureNode: Need a three.js texture.' );
  24703. }
  24704. const textureProperty = super.generate( builder, 'property' );
  24705. if ( output === 'sampler' ) {
  24706. return textureProperty + '_sampler';
  24707. } else if ( builder.isReference( output ) ) {
  24708. return textureProperty;
  24709. } else {
  24710. const nodeData = builder.getDataFromNode( this );
  24711. let propertyName = nodeData.propertyName;
  24712. if ( propertyName === undefined ) {
  24713. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24714. const uvSnippet = this.generateUV( builder, uvNode );
  24715. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24716. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24717. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24718. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24719. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24720. const nodeVar = builder.getVarFromNode( this );
  24721. propertyName = builder.getPropertyName( nodeVar );
  24722. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24723. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24724. nodeData.snippet = snippet;
  24725. nodeData.propertyName = propertyName;
  24726. }
  24727. let snippet = propertyName;
  24728. const nodeType = this.getNodeType( builder );
  24729. if ( builder.needsColorSpaceToLinear( texture ) ) {
  24730. snippet = colorSpaceToLinear( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24731. }
  24732. return builder.format( snippet, nodeType, output );
  24733. }
  24734. }
  24735. setSampler( value ) {
  24736. this.sampler = value;
  24737. return this;
  24738. }
  24739. getSampler() {
  24740. return this.sampler;
  24741. }
  24742. // @TODO: Move to TSL
  24743. uv( uvNode ) {
  24744. const textureNode = this.clone();
  24745. textureNode.uvNode = nodeObject( uvNode );
  24746. textureNode.referenceNode = this;
  24747. return nodeObject( textureNode );
  24748. }
  24749. blur( amountNode ) {
  24750. const textureNode = this.clone();
  24751. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24752. textureNode.referenceNode = this;
  24753. return nodeObject( textureNode );
  24754. }
  24755. level( levelNode ) {
  24756. const textureNode = this.clone();
  24757. textureNode.levelNode = nodeObject( levelNode );
  24758. textureNode.referenceNode = this;
  24759. return nodeObject( textureNode );
  24760. }
  24761. size( levelNode ) {
  24762. return textureSize( this, levelNode );
  24763. }
  24764. bias( biasNode ) {
  24765. const textureNode = this.clone();
  24766. textureNode.biasNode = nodeObject( biasNode );
  24767. textureNode.referenceNode = this;
  24768. return nodeObject( textureNode );
  24769. }
  24770. compare( compareNode ) {
  24771. const textureNode = this.clone();
  24772. textureNode.compareNode = nodeObject( compareNode );
  24773. textureNode.referenceNode = this;
  24774. return nodeObject( textureNode );
  24775. }
  24776. grad( gradNodeX, gradNodeY ) {
  24777. const textureNode = this.clone();
  24778. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24779. textureNode.referenceNode = this;
  24780. return nodeObject( textureNode );
  24781. }
  24782. depth( depthNode ) {
  24783. const textureNode = this.clone();
  24784. textureNode.depthNode = nodeObject( depthNode );
  24785. textureNode.referenceNode = this;
  24786. return nodeObject( textureNode );
  24787. }
  24788. // --
  24789. serialize( data ) {
  24790. super.serialize( data );
  24791. data.value = this.value.toJSON( data.meta ).uuid;
  24792. }
  24793. deserialize( data ) {
  24794. super.deserialize( data );
  24795. this.value = data.meta.textures[ data.value ];
  24796. }
  24797. update() {
  24798. const texture = this.value;
  24799. const matrixUniform = this._matrixUniform;
  24800. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24801. if ( texture.matrixAutoUpdate === true ) {
  24802. texture.updateMatrix();
  24803. }
  24804. }
  24805. clone() {
  24806. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24807. newNode.sampler = this.sampler;
  24808. return newNode;
  24809. }
  24810. }
  24811. const texture = nodeProxy( TextureNode );
  24812. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24813. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24814. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24815. addNodeElement( 'texture', texture );
  24816. //addNodeElement( 'textureLevel', textureLevel );
  24817. addNodeClass( 'TextureNode', TextureNode );
  24818. class BufferNode extends UniformNode {
  24819. constructor( value, bufferType, bufferCount = 0 ) {
  24820. super( value, bufferType );
  24821. this.isBufferNode = true;
  24822. this.bufferType = bufferType;
  24823. this.bufferCount = bufferCount;
  24824. }
  24825. getElementType( builder ) {
  24826. return this.getNodeType( builder );
  24827. }
  24828. getInputType( /*builder*/ ) {
  24829. return 'buffer';
  24830. }
  24831. }
  24832. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24833. addNodeClass( 'BufferNode', BufferNode );
  24834. class UniformsElementNode extends ArrayElementNode {
  24835. constructor( arrayBuffer, indexNode ) {
  24836. super( arrayBuffer, indexNode );
  24837. this.isArrayBufferElementNode = true;
  24838. }
  24839. getNodeType( builder ) {
  24840. return this.node.getElementType( builder );
  24841. }
  24842. generate( builder ) {
  24843. const snippet = super.generate( builder );
  24844. const type = this.getNodeType();
  24845. return builder.format( snippet, 'vec4', type );
  24846. }
  24847. }
  24848. class UniformsNode extends BufferNode {
  24849. constructor( value, elementType = null ) {
  24850. super( null, 'vec4' );
  24851. this.array = value;
  24852. this.elementType = elementType;
  24853. this._elementType = null;
  24854. this._elementLength = 0;
  24855. this.updateType = NodeUpdateType.RENDER;
  24856. this.isArrayBufferNode = true;
  24857. }
  24858. getElementType() {
  24859. return this.elementType || this._elementType;
  24860. }
  24861. getElementLength() {
  24862. return this._elementLength;
  24863. }
  24864. update( /*frame*/ ) {
  24865. const { array, value } = this;
  24866. const elementLength = this.getElementLength();
  24867. const elementType = this.getElementType();
  24868. if ( elementLength === 1 ) {
  24869. for ( let i = 0; i < array.length; i ++ ) {
  24870. const index = i * 4;
  24871. value[ index ] = array[ i ];
  24872. }
  24873. } else if ( elementType === 'color' ) {
  24874. for ( let i = 0; i < array.length; i ++ ) {
  24875. const index = i * 4;
  24876. const vector = array[ i ];
  24877. value[ index ] = vector.r;
  24878. value[ index + 1 ] = vector.g;
  24879. value[ index + 2 ] = vector.b || 0;
  24880. //value[ index + 3 ] = vector.a || 0;
  24881. }
  24882. } else {
  24883. for ( let i = 0; i < array.length; i ++ ) {
  24884. const index = i * 4;
  24885. const vector = array[ i ];
  24886. value[ index ] = vector.x;
  24887. value[ index + 1 ] = vector.y;
  24888. value[ index + 2 ] = vector.z || 0;
  24889. value[ index + 3 ] = vector.w || 0;
  24890. }
  24891. }
  24892. }
  24893. setup( builder ) {
  24894. const length = this.array.length;
  24895. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24896. this._elementLength = builder.getTypeLength( this._elementType );
  24897. let arrayType = Float32Array;
  24898. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24899. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24900. this.value = new arrayType( length * 4 );
  24901. this.bufferCount = length;
  24902. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24903. return super.setup( builder );
  24904. }
  24905. element( indexNode ) {
  24906. return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) );
  24907. }
  24908. }
  24909. const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) );
  24910. addNodeClass( 'UniformsNode', UniformsNode );
  24911. class ReferenceElementNode extends ArrayElementNode {
  24912. constructor( referenceNode, indexNode ) {
  24913. super( referenceNode, indexNode );
  24914. this.referenceNode = referenceNode;
  24915. this.isReferenceElementNode = true;
  24916. }
  24917. getNodeType() {
  24918. return this.referenceNode.uniformType;
  24919. }
  24920. generate( builder ) {
  24921. const snippet = super.generate( builder );
  24922. const arrayType = this.referenceNode.getNodeType();
  24923. const elementType = this.getNodeType();
  24924. return builder.format( snippet, arrayType, elementType );
  24925. }
  24926. }
  24927. class ReferenceNode extends Node {
  24928. constructor( property, uniformType, object = null, count = null ) {
  24929. super();
  24930. this.property = property;
  24931. this.uniformType = uniformType;
  24932. this.object = object;
  24933. this.count = count;
  24934. this.properties = property.split( '.' );
  24935. this.reference = null;
  24936. this.node = null;
  24937. this.updateType = NodeUpdateType.OBJECT;
  24938. }
  24939. element( indexNode ) {
  24940. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24941. }
  24942. setNodeType( uniformType ) {
  24943. let node = null;
  24944. if ( this.count !== null ) {
  24945. node = buffer( null, uniformType, this.count );
  24946. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24947. node = uniforms( null, uniformType );
  24948. } else if ( uniformType === 'texture' ) {
  24949. node = texture( null );
  24950. } else {
  24951. node = uniform( null, uniformType );
  24952. }
  24953. this.node = node;
  24954. }
  24955. getNodeType( builder ) {
  24956. if ( this.node === null ) {
  24957. this.updateValue();
  24958. }
  24959. return this.node.getNodeType( builder );
  24960. }
  24961. getValueFromReference( object = this.reference ) {
  24962. const { properties } = this;
  24963. let value = object[ properties[ 0 ] ];
  24964. for ( let i = 1; i < properties.length; i ++ ) {
  24965. value = value[ properties[ i ] ];
  24966. }
  24967. return value;
  24968. }
  24969. updateReference( state ) {
  24970. this.reference = this.object !== null ? this.object : state.object;
  24971. return this.reference;
  24972. }
  24973. setup() {
  24974. this.updateValue();
  24975. return this.node;
  24976. }
  24977. update( /*frame*/ ) {
  24978. this.updateValue();
  24979. }
  24980. updateValue() {
  24981. if ( this.node === null ) this.setNodeType( this.uniformType );
  24982. const value = this.getValueFromReference();
  24983. if ( Array.isArray( value ) ) {
  24984. this.node.array = value;
  24985. } else {
  24986. this.node.value = value;
  24987. }
  24988. }
  24989. }
  24990. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24991. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24992. addNodeClass( 'ReferenceNode', ReferenceNode );
  24993. class MaterialReferenceNode extends ReferenceNode {
  24994. constructor( property, inputType, material = null ) {
  24995. super( property, inputType, material );
  24996. this.material = material;
  24997. //this.updateType = NodeUpdateType.RENDER;
  24998. }
  24999. /*setNodeType( node ) {
  25000. super.setNodeType( node );
  25001. this.node.groupNode = renderGroup;
  25002. }*/
  25003. updateReference( state ) {
  25004. this.reference = this.material !== null ? this.material : state.material;
  25005. return this.reference;
  25006. }
  25007. }
  25008. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  25009. addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode );
  25010. const cameraGroup = /*#__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  25011. cameraGroup.needsUpdate = true;
  25012. } );
  25013. const cameraNear = /*#__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  25014. const cameraFar = /*#__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  25015. const cameraLogDepth = /*#__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  25016. const cameraProjectionMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  25017. const cameraProjectionMatrixInverse = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  25018. const cameraViewMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  25019. const cameraWorldMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  25020. const cameraNormalMatrix = /*#__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  25021. const cameraPosition = /*#__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  25022. class Object3DNode extends Node {
  25023. constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) {
  25024. super();
  25025. this.scope = scope;
  25026. this.object3d = object3d;
  25027. this.updateType = NodeUpdateType.OBJECT;
  25028. this._uniformNode = new UniformNode( null );
  25029. }
  25030. getNodeType() {
  25031. const scope = this.scope;
  25032. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25033. return 'mat4';
  25034. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25035. return 'mat3';
  25036. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25037. return 'vec3';
  25038. }
  25039. }
  25040. update( frame ) {
  25041. const object = this.object3d;
  25042. const uniformNode = this._uniformNode;
  25043. const scope = this.scope;
  25044. if ( scope === Object3DNode.VIEW_MATRIX ) {
  25045. uniformNode.value = object.modelViewMatrix;
  25046. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25047. uniformNode.value = object.normalMatrix;
  25048. } else if ( scope === Object3DNode.WORLD_MATRIX ) {
  25049. uniformNode.value = object.matrixWorld;
  25050. } else if ( scope === Object3DNode.POSITION ) {
  25051. uniformNode.value = uniformNode.value || new Vector3();
  25052. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25053. } else if ( scope === Object3DNode.SCALE ) {
  25054. uniformNode.value = uniformNode.value || new Vector3();
  25055. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  25056. } else if ( scope === Object3DNode.DIRECTION ) {
  25057. uniformNode.value = uniformNode.value || new Vector3();
  25058. object.getWorldDirection( uniformNode.value );
  25059. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  25060. const camera = frame.camera;
  25061. uniformNode.value = uniformNode.value || new Vector3();
  25062. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25063. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  25064. }
  25065. }
  25066. generate( builder ) {
  25067. const scope = this.scope;
  25068. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25069. this._uniformNode.nodeType = 'mat4';
  25070. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25071. this._uniformNode.nodeType = 'mat3';
  25072. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25073. this._uniformNode.nodeType = 'vec3';
  25074. }
  25075. return this._uniformNode.build( builder );
  25076. }
  25077. serialize( data ) {
  25078. super.serialize( data );
  25079. data.scope = this.scope;
  25080. }
  25081. deserialize( data ) {
  25082. super.deserialize( data );
  25083. this.scope = data.scope;
  25084. }
  25085. }
  25086. Object3DNode.VIEW_MATRIX = 'viewMatrix';
  25087. Object3DNode.NORMAL_MATRIX = 'normalMatrix';
  25088. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  25089. Object3DNode.POSITION = 'position';
  25090. Object3DNode.SCALE = 'scale';
  25091. Object3DNode.VIEW_POSITION = 'viewPosition';
  25092. Object3DNode.DIRECTION = 'direction';
  25093. const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  25094. const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX );
  25095. const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX );
  25096. const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  25097. const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION );
  25098. const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE );
  25099. const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  25100. addNodeClass( 'Object3DNode', Object3DNode );
  25101. class ModelNode extends Object3DNode {
  25102. constructor( scope = ModelNode.VIEW_MATRIX ) {
  25103. super( scope );
  25104. }
  25105. update( frame ) {
  25106. this.object3d = frame.object;
  25107. super.update( frame );
  25108. }
  25109. }
  25110. const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION );
  25111. const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' );
  25112. const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
  25113. const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  25114. const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
  25115. const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE );
  25116. const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  25117. const modelWorldMatrixInverse = uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  25118. addNodeClass( 'ModelNode', ModelNode );
  25119. const normalGeometry = /*#__PURE__*/ attribute( 'normal', 'vec3', vec3( 0, 1, 0 ) );
  25120. const normalLocal = /*#__PURE__*/ normalGeometry.toVar( 'normalLocal' );
  25121. const normalView = /*#__PURE__*/ varying( modelNormalMatrix.mul( normalLocal ), 'v_normalView' ).normalize().toVar( 'normalView' );
  25122. const normalWorld = /*#__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  25123. const transformedNormalView = /*#__PURE__*/ property( 'vec3', 'transformedNormalView' );
  25124. const transformedNormalWorld = /*#__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedNormalWorld' );
  25125. const transformedClearcoatNormalView = /*#__PURE__*/ property( 'vec3', 'transformedClearcoatNormalView' );
  25126. const _propertyCache = new Map();
  25127. class MaterialNode extends Node {
  25128. constructor( scope ) {
  25129. super();
  25130. this.scope = scope;
  25131. }
  25132. getCache( property, type ) {
  25133. let node = _propertyCache.get( property );
  25134. if ( node === undefined ) {
  25135. node = materialReference( property, type );
  25136. _propertyCache.set( property, node );
  25137. }
  25138. return node;
  25139. }
  25140. getFloat( property ) {
  25141. return this.getCache( property, 'float' );
  25142. }
  25143. getColor( property ) {
  25144. return this.getCache( property, 'color' );
  25145. }
  25146. getTexture( property ) {
  25147. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25148. }
  25149. setup( builder ) {
  25150. const material = builder.context.material;
  25151. const scope = this.scope;
  25152. let node = null;
  25153. if ( scope === MaterialNode.COLOR ) {
  25154. const colorNode = this.getColor( scope );
  25155. if ( material.map && material.map.isTexture === true ) {
  25156. node = colorNode.mul( this.getTexture( 'map' ) );
  25157. } else {
  25158. node = colorNode;
  25159. }
  25160. } else if ( scope === MaterialNode.OPACITY ) {
  25161. const opacityNode = this.getFloat( scope );
  25162. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25163. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25164. } else {
  25165. node = opacityNode;
  25166. }
  25167. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25168. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25169. node = this.getTexture( 'specular' ).r;
  25170. } else {
  25171. node = float( 1 );
  25172. }
  25173. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25174. const specularIntensity = this.getFloat( scope );
  25175. if ( material.specularMap ) {
  25176. node = specularIntensity.mul( this.getTexture( scope ).a );
  25177. } else {
  25178. node = specularIntensity;
  25179. }
  25180. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25181. const specularColorNode = this.getColor( scope );
  25182. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25183. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25184. } else {
  25185. node = specularColorNode;
  25186. }
  25187. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25188. const roughnessNode = this.getFloat( scope );
  25189. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25190. node = roughnessNode.mul( this.getTexture( scope ).g );
  25191. } else {
  25192. node = roughnessNode;
  25193. }
  25194. } else if ( scope === MaterialNode.METALNESS ) {
  25195. const metalnessNode = this.getFloat( scope );
  25196. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25197. node = metalnessNode.mul( this.getTexture( scope ).b );
  25198. } else {
  25199. node = metalnessNode;
  25200. }
  25201. } else if ( scope === MaterialNode.EMISSIVE ) {
  25202. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25203. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25204. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25205. node = emissiveNode.mul( this.getTexture( scope ) );
  25206. } else {
  25207. node = emissiveNode;
  25208. }
  25209. } else if ( scope === MaterialNode.NORMAL ) {
  25210. if ( material.normalMap ) {
  25211. node = this.getTexture( 'normal' ).normalMap( this.getCache( 'normalScale', 'vec2' ) );
  25212. } else if ( material.bumpMap ) {
  25213. node = this.getTexture( 'bump' ).r.bumpMap( this.getFloat( 'bumpScale' ) );
  25214. } else {
  25215. node = normalView;
  25216. }
  25217. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25218. const clearcoatNode = this.getFloat( scope );
  25219. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25220. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25221. } else {
  25222. node = clearcoatNode;
  25223. }
  25224. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25225. const clearcoatRoughnessNode = this.getFloat( scope );
  25226. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25227. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25228. } else {
  25229. node = clearcoatRoughnessNode;
  25230. }
  25231. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25232. if ( material.clearcoatNormalMap ) {
  25233. node = this.getTexture( scope ).normalMap( this.getCache( scope + 'Scale', 'vec2' ) );
  25234. } else {
  25235. node = normalView;
  25236. }
  25237. } else if ( scope === MaterialNode.SHEEN ) {
  25238. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25239. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25240. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25241. } else {
  25242. node = sheenNode;
  25243. }
  25244. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25245. const sheenRoughnessNode = this.getFloat( scope );
  25246. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25247. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25248. } else {
  25249. node = sheenRoughnessNode;
  25250. }
  25251. node = node.clamp( 0.07, 1.0 );
  25252. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25253. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25254. const anisotropyPolar = this.getTexture( scope );
  25255. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25256. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25257. } else {
  25258. node = materialAnisotropyVector;
  25259. }
  25260. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25261. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25262. if ( material.iridescenceThicknessMap ) {
  25263. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25264. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25265. } else {
  25266. node = iridescenceThicknessMaximum;
  25267. }
  25268. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25269. const transmissionNode = this.getFloat( scope );
  25270. if ( material.transmissionMap ) {
  25271. node = transmissionNode.mul( this.getTexture( scope ).r );
  25272. } else {
  25273. node = transmissionNode;
  25274. }
  25275. } else if ( scope === MaterialNode.THICKNESS ) {
  25276. const thicknessNode = this.getFloat( scope );
  25277. if ( material.thicknessMap ) {
  25278. node = thicknessNode.mul( this.getTexture( scope ).g );
  25279. } else {
  25280. node = thicknessNode;
  25281. }
  25282. } else if ( scope === MaterialNode.IOR ) {
  25283. node = this.getFloat( scope );
  25284. } else if ( scope === MaterialNode.REFRACTION_RATIO ) {
  25285. node = this.getFloat( scope );
  25286. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25287. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25288. } else if ( scope === MaterialNode.AO_MAP ) {
  25289. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25290. } else {
  25291. const outputType = this.getNodeType( builder );
  25292. node = this.getCache( scope, outputType );
  25293. }
  25294. return node;
  25295. }
  25296. }
  25297. MaterialNode.ALPHA_TEST = 'alphaTest';
  25298. MaterialNode.COLOR = 'color';
  25299. MaterialNode.OPACITY = 'opacity';
  25300. MaterialNode.SHININESS = 'shininess';
  25301. MaterialNode.SPECULAR = 'specular';
  25302. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25303. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25304. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25305. MaterialNode.REFLECTIVITY = 'reflectivity';
  25306. MaterialNode.ROUGHNESS = 'roughness';
  25307. MaterialNode.METALNESS = 'metalness';
  25308. MaterialNode.NORMAL = 'normal';
  25309. MaterialNode.CLEARCOAT = 'clearcoat';
  25310. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25311. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25312. MaterialNode.EMISSIVE = 'emissive';
  25313. MaterialNode.ROTATION = 'rotation';
  25314. MaterialNode.SHEEN = 'sheen';
  25315. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25316. MaterialNode.ANISOTROPY = 'anisotropy';
  25317. MaterialNode.IRIDESCENCE = 'iridescence';
  25318. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25319. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25320. MaterialNode.IOR = 'ior';
  25321. MaterialNode.TRANSMISSION = 'transmission';
  25322. MaterialNode.THICKNESS = 'thickness';
  25323. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25324. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25325. MaterialNode.LINE_SCALE = 'scale';
  25326. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25327. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25328. MaterialNode.LINE_WIDTH = 'linewidth';
  25329. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25330. MaterialNode.POINT_WIDTH = 'pointWidth';
  25331. MaterialNode.DISPERSION = 'dispersion';
  25332. MaterialNode.LIGHT_MAP = 'light';
  25333. MaterialNode.AO_MAP = 'ao';
  25334. MaterialNode.REFRACTION_RATIO = 'refractionRatio';
  25335. const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25336. const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25337. const materialShininess = nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25338. const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25339. const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25340. const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25341. const materialSpecularIntensity = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25342. const materialSpecularColor = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25343. const materialSpecularStrength = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25344. const materialReflectivity = nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25345. const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25346. const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25347. const materialNormal = nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  25348. const materialClearcoat = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25349. const materialClearcoatRoughness = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25350. const materialClearcoatNormal = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  25351. const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25352. const materialSheen = nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25353. const materialSheenRoughness = nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25354. const materialAnisotropy = nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25355. const materialIridescence = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25356. const materialIridescenceIOR = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25357. const materialIridescenceThickness = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25358. const materialTransmission = nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25359. const materialThickness = nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25360. const materialIOR = nodeImmutable( MaterialNode, MaterialNode.IOR );
  25361. const materialAttenuationDistance = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25362. const materialAttenuationColor = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25363. const materialLineScale = nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25364. const materialLineDashSize = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25365. const materialLineGapSize = nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25366. const materialLineWidth = nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25367. const materialLineDashOffset = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25368. const materialPointWidth = nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25369. const materialDispersion = nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25370. const materialLightMap = nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25371. const materialAOMap = nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25372. const materialRefractionRatio = nodeImmutable( MaterialNode, MaterialNode.REFRACTION_RATIO );
  25373. const materialAnisotropyVector = uniform( new Vector2() ).onReference( function ( frame ) {
  25374. return frame.material;
  25375. } ).onRenderUpdate( function ( { material } ) {
  25376. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25377. } );
  25378. addNodeClass( 'MaterialNode', MaterialNode );
  25379. const positionGeometry = /*#__PURE__*/ attribute( 'position', 'vec3' );
  25380. const positionLocal = /*#__PURE__*/ positionGeometry.toVar( 'positionLocal' );
  25381. const positionWorld = /*#__PURE__*/ varying( modelWorldMatrix.mul( positionLocal ).xyz, 'v_positionWorld' );
  25382. const positionWorldDirection = /*#__PURE__*/ varying( positionLocal.transformDirection( modelWorldMatrix ), 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  25383. const positionView = /*#__PURE__*/ varying( modelViewMatrix.mul( positionLocal ).xyz, 'v_positionView' );
  25384. const positionViewDirection = /*#__PURE__*/ varying( positionView.negate(), 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  25385. class ModelViewProjectionNode extends TempNode {
  25386. constructor( positionNode = null ) {
  25387. super( 'vec4' );
  25388. this.positionNode = positionNode;
  25389. }
  25390. setup( builder ) {
  25391. if ( builder.shaderStage === 'fragment' ) {
  25392. return varying( builder.context.mvp );
  25393. }
  25394. const position = this.positionNode || positionLocal;
  25395. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( position );
  25396. }
  25397. }
  25398. const modelViewProjection = nodeProxy( ModelViewProjectionNode );
  25399. addNodeClass( 'ModelViewProjectionNode', ModelViewProjectionNode );
  25400. class BufferAttributeNode extends InputNode {
  25401. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  25402. super( value, bufferType );
  25403. this.isBufferNode = true;
  25404. this.bufferType = bufferType;
  25405. this.bufferStride = bufferStride;
  25406. this.bufferOffset = bufferOffset;
  25407. this.usage = StaticDrawUsage;
  25408. this.instanced = false;
  25409. this.attribute = null;
  25410. this.global = true;
  25411. if ( value && value.isBufferAttribute === true ) {
  25412. this.attribute = value;
  25413. this.usage = value.usage;
  25414. this.instanced = value.isInstancedBufferAttribute;
  25415. }
  25416. }
  25417. getHash( builder ) {
  25418. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  25419. let bufferData = builder.globalCache.getData( this.value );
  25420. if ( bufferData === undefined ) {
  25421. bufferData = {
  25422. node: this
  25423. };
  25424. builder.globalCache.setData( this.value, bufferData );
  25425. }
  25426. return bufferData.node.uuid;
  25427. }
  25428. return this.uuid;
  25429. }
  25430. getNodeType( builder ) {
  25431. if ( this.bufferType === null ) {
  25432. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  25433. }
  25434. return this.bufferType;
  25435. }
  25436. setup( builder ) {
  25437. if ( this.attribute !== null ) return;
  25438. const type = this.getNodeType( builder );
  25439. const array = this.value;
  25440. const itemSize = builder.getTypeLength( type );
  25441. const stride = this.bufferStride || itemSize;
  25442. const offset = this.bufferOffset;
  25443. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  25444. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  25445. buffer.setUsage( this.usage );
  25446. this.attribute = bufferAttribute;
  25447. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  25448. }
  25449. generate( builder ) {
  25450. const nodeType = this.getNodeType( builder );
  25451. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  25452. const propertyName = builder.getPropertyName( nodeAttribute );
  25453. let output = null;
  25454. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25455. this.name = propertyName;
  25456. output = propertyName;
  25457. } else {
  25458. const nodeVarying = varying( this );
  25459. output = nodeVarying.build( builder, nodeType );
  25460. }
  25461. return output;
  25462. }
  25463. getInputType( /*builder*/ ) {
  25464. return 'bufferAttribute';
  25465. }
  25466. setUsage( value ) {
  25467. this.usage = value;
  25468. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  25469. this.attribute.usage = value;
  25470. }
  25471. return this;
  25472. }
  25473. setInstanced( value ) {
  25474. this.instanced = value;
  25475. return this;
  25476. }
  25477. }
  25478. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  25479. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  25480. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  25481. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  25482. addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  25483. addNodeClass( 'BufferAttributeNode', BufferAttributeNode );
  25484. class InstanceNode extends Node {
  25485. constructor( instanceMesh ) {
  25486. super( 'void' );
  25487. this.instanceMesh = instanceMesh;
  25488. this.instanceMatrixNode = null;
  25489. this.instanceColorNode = null;
  25490. this.updateType = NodeUpdateType.FRAME;
  25491. this.buffer = null;
  25492. this.bufferColor = null;
  25493. }
  25494. setup( /*builder*/ ) {
  25495. let instanceMatrixNode = this.instanceMatrixNode;
  25496. let instanceColorNode = this.instanceColorNode;
  25497. const instanceMesh = this.instanceMesh;
  25498. if ( instanceMatrixNode === null ) {
  25499. const instanceAttribute = instanceMesh.instanceMatrix;
  25500. // 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.
  25501. if ( instanceMesh.count <= 1000 ) {
  25502. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', instanceMesh.count ).element( instanceIndex );
  25503. } else {
  25504. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25505. this.buffer = buffer;
  25506. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25507. const instanceBuffers = [
  25508. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25509. bufferFn( buffer, 'vec4', 16, 0 ),
  25510. bufferFn( buffer, 'vec4', 16, 4 ),
  25511. bufferFn( buffer, 'vec4', 16, 8 ),
  25512. bufferFn( buffer, 'vec4', 16, 12 )
  25513. ];
  25514. instanceMatrixNode = mat4( ...instanceBuffers );
  25515. }
  25516. this.instanceMatrixNode = instanceMatrixNode;
  25517. }
  25518. const instanceColorAttribute = instanceMesh.instanceColor;
  25519. if ( instanceColorAttribute && instanceColorNode === null ) {
  25520. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25521. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25522. this.bufferColor = buffer;
  25523. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25524. this.instanceColorNode = instanceColorNode;
  25525. }
  25526. // POSITION
  25527. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25528. // NORMAL
  25529. const m = mat3( instanceMatrixNode );
  25530. const transformedNormal = normalLocal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  25531. const instanceNormal = m.mul( transformedNormal ).xyz;
  25532. // ASSIGNS
  25533. positionLocal.assign( instancePosition );
  25534. normalLocal.assign( instanceNormal );
  25535. // COLOR
  25536. if ( this.instanceColorNode !== null ) {
  25537. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25538. }
  25539. }
  25540. update( /*frame*/ ) {
  25541. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25542. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25543. }
  25544. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25545. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25546. }
  25547. }
  25548. }
  25549. const instance = nodeProxy( InstanceNode );
  25550. addNodeClass( 'InstanceNode', InstanceNode );
  25551. const tangentGeometry = /*#__PURE__*/ tslFn( ( stack, builder ) => {
  25552. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25553. builder.geometry.computeTangents();
  25554. }
  25555. return attribute( 'tangent', 'vec4' );
  25556. } )();
  25557. const tangentLocal = /*#__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25558. const tangentView = /*#__PURE__*/ varying( modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz, 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25559. const tangentWorld = /*#__PURE__*/ varying( tangentView.transformDirection( cameraViewMatrix ), 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25560. const transformedTangentView = /*#__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25561. const transformedTangentWorld = /*#__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25562. class BatchNode extends Node {
  25563. constructor( batchMesh ) {
  25564. super( 'void' );
  25565. this.batchMesh = batchMesh;
  25566. this.instanceColorNode = null;
  25567. this.batchingIdNode = null;
  25568. }
  25569. setup( builder ) {
  25570. // POSITION
  25571. if ( this.batchingIdNode === null ) {
  25572. if ( builder.getDrawIndex() === null ) {
  25573. this.batchingIdNode = instanceIndex;
  25574. } else {
  25575. this.batchingIdNode = drawIndex;
  25576. }
  25577. }
  25578. const getIndirectIndex = tslFn( ( [ id ] ) => {
  25579. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25580. const x = int( id ).remainder( int( size ) );
  25581. const y = int( id ).div( int( size ) );
  25582. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25583. } ).setLayout( {
  25584. name: 'getIndirectIndex',
  25585. type: 'uint',
  25586. inputs: [
  25587. { name: 'id', type: 'int' }
  25588. ]
  25589. } );
  25590. const matriceTexture = this.batchMesh._matricesTexture;
  25591. const size = textureSize( textureLoad( matriceTexture ), 0 );
  25592. const j = float( getIndirectIndex( int( this.batchingIdNode ) ) ).mul( 4 ).toVar();
  25593. const x = int( j.mod( size ) );
  25594. const y = int( j ).div( int( size ) );
  25595. const batchingMatrix = mat4(
  25596. textureLoad( matriceTexture, ivec2( x, y ) ),
  25597. textureLoad( matriceTexture, ivec2( x.add( 1 ), y ) ),
  25598. textureLoad( matriceTexture, ivec2( x.add( 2 ), y ) ),
  25599. textureLoad( matriceTexture, ivec2( x.add( 3 ), y ) )
  25600. );
  25601. const bm = mat3( batchingMatrix );
  25602. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25603. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25604. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25605. normalLocal.assign( batchingNormal );
  25606. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25607. tangentLocal.mulAssign( bm );
  25608. }
  25609. }
  25610. }
  25611. const batch = nodeProxy( BatchNode );
  25612. addNodeClass( 'batch', BatchNode );
  25613. class SkinningNode extends Node {
  25614. constructor( skinnedMesh, useReference = false ) {
  25615. super( 'void' );
  25616. this.skinnedMesh = skinnedMesh;
  25617. this.useReference = useReference;
  25618. this.updateType = NodeUpdateType.OBJECT;
  25619. //
  25620. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25621. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25622. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25623. if ( useReference ) {
  25624. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25625. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25626. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25627. } else {
  25628. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25629. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25630. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25631. }
  25632. this.bindMatrixNode = bindMatrixNode;
  25633. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25634. this.boneMatricesNode = boneMatricesNode;
  25635. }
  25636. setup( builder ) {
  25637. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode, boneMatricesNode } = this;
  25638. const boneMatX = boneMatricesNode.element( skinIndexNode.x );
  25639. const boneMatY = boneMatricesNode.element( skinIndexNode.y );
  25640. const boneMatZ = boneMatricesNode.element( skinIndexNode.z );
  25641. const boneMatW = boneMatricesNode.element( skinIndexNode.w );
  25642. // POSITION
  25643. const skinVertex = bindMatrixNode.mul( positionLocal );
  25644. const skinned = add(
  25645. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25646. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25647. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25648. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25649. );
  25650. const skinPosition = bindMatrixInverseNode.mul( skinned ).xyz;
  25651. // NORMAL
  25652. let skinMatrix = add(
  25653. skinWeightNode.x.mul( boneMatX ),
  25654. skinWeightNode.y.mul( boneMatY ),
  25655. skinWeightNode.z.mul( boneMatZ ),
  25656. skinWeightNode.w.mul( boneMatW )
  25657. );
  25658. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25659. const skinNormal = skinMatrix.transformDirection( normalLocal ).xyz;
  25660. // ASSIGNS
  25661. positionLocal.assign( skinPosition );
  25662. normalLocal.assign( skinNormal );
  25663. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25664. tangentLocal.assign( skinNormal );
  25665. }
  25666. }
  25667. generate( builder, output ) {
  25668. if ( output !== 'void' ) {
  25669. return positionLocal.build( builder, output );
  25670. }
  25671. }
  25672. update( frame ) {
  25673. const object = this.useReference ? frame.object : this.skinnedMesh;
  25674. object.skeleton.update();
  25675. }
  25676. }
  25677. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25678. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25679. addNodeClass( 'SkinningNode', SkinningNode );
  25680. class LoopNode extends Node {
  25681. constructor( params = [] ) {
  25682. super();
  25683. this.params = params;
  25684. }
  25685. getVarName( index ) {
  25686. return String.fromCharCode( 'i'.charCodeAt() + index );
  25687. }
  25688. getProperties( builder ) {
  25689. const properties = builder.getNodeProperties( this );
  25690. if ( properties.stackNode !== undefined ) return properties;
  25691. //
  25692. const inputs = {};
  25693. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25694. const param = this.params[ i ];
  25695. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25696. const type = ( param.isNode !== true && param.type ) || 'int';
  25697. inputs[ name ] = expression( name, type );
  25698. }
  25699. const stack = builder.addStack(); // TODO: cache() it
  25700. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25701. properties.stackNode = stack;
  25702. builder.removeStack();
  25703. return properties;
  25704. }
  25705. getNodeType( builder ) {
  25706. const { returnsNode } = this.getProperties( builder );
  25707. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25708. }
  25709. setup( builder ) {
  25710. // setup properties
  25711. this.getProperties( builder );
  25712. }
  25713. generate( builder ) {
  25714. const properties = this.getProperties( builder );
  25715. const params = this.params;
  25716. const stackNode = properties.stackNode;
  25717. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25718. const param = params[ i ];
  25719. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25720. if ( param.isNode ) {
  25721. type = 'int';
  25722. name = this.getVarName( i );
  25723. start = '0';
  25724. end = param.build( builder, type );
  25725. condition = '<';
  25726. } else {
  25727. type = param.type || 'int';
  25728. name = param.name || this.getVarName( i );
  25729. start = param.start;
  25730. end = param.end;
  25731. condition = param.condition;
  25732. update = param.update;
  25733. if ( typeof start === 'number' ) start = start.toString();
  25734. else if ( start && start.isNode ) start = start.build( builder, type );
  25735. if ( typeof end === 'number' ) end = end.toString();
  25736. else if ( end && end.isNode ) end = end.build( builder, type );
  25737. if ( start !== undefined && end === undefined ) {
  25738. start = start + ' - 1';
  25739. end = '0';
  25740. condition = '>=';
  25741. } else if ( end !== undefined && start === undefined ) {
  25742. start = '0';
  25743. condition = '<';
  25744. }
  25745. if ( condition === undefined ) {
  25746. if ( Number( start ) > Number( end ) ) {
  25747. condition = '>=';
  25748. } else {
  25749. condition = '<';
  25750. }
  25751. }
  25752. }
  25753. const internalParam = { start, end, condition };
  25754. //
  25755. const startSnippet = internalParam.start;
  25756. const endSnippet = internalParam.end;
  25757. let declarationSnippet = '';
  25758. let conditionalSnippet = '';
  25759. let updateSnippet = '';
  25760. if ( ! update ) {
  25761. if ( type === 'int' || type === 'uint' ) {
  25762. if ( condition.includes( '<' ) ) update = '++';
  25763. else update = '--';
  25764. } else {
  25765. if ( condition.includes( '<' ) ) update = '+= 1.';
  25766. else update = '-= 1.';
  25767. }
  25768. }
  25769. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25770. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25771. updateSnippet += name + ' ' + update;
  25772. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25773. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25774. }
  25775. const stackSnippet = stackNode.build( builder, 'void' );
  25776. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25777. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25778. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25779. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25780. }
  25781. builder.addFlowTab();
  25782. return returnsSnippet;
  25783. }
  25784. }
  25785. const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25786. const Continue = () => expression( 'continue' ).append();
  25787. const Break = () => expression( 'break' ).append();
  25788. addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) );
  25789. addNodeClass( 'LoopNode', LoopNode );
  25790. const _morphTextures = new WeakMap();
  25791. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25792. const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25793. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25794. const y = texelIndex.div( width );
  25795. const x = texelIndex.sub( y.mul( width ) );
  25796. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25797. return bufferAttrib.mul( influence );
  25798. } );
  25799. function getEntry( geometry ) {
  25800. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25801. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25802. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25803. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25804. // into an array of data textures. Each layer represents a single morph target.
  25805. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25806. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25807. let entry = _morphTextures.get( geometry );
  25808. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25809. if ( entry !== undefined ) entry.texture.dispose();
  25810. const morphTargets = geometry.morphAttributes.position || [];
  25811. const morphNormals = geometry.morphAttributes.normal || [];
  25812. const morphColors = geometry.morphAttributes.color || [];
  25813. let vertexDataCount = 0;
  25814. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25815. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25816. if ( hasMorphColors === true ) vertexDataCount = 3;
  25817. let width = geometry.attributes.position.count * vertexDataCount;
  25818. let height = 1;
  25819. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25820. if ( width > maxTextureSize ) {
  25821. height = Math.ceil( width / maxTextureSize );
  25822. width = maxTextureSize;
  25823. }
  25824. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25825. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25826. bufferTexture.type = FloatType;
  25827. bufferTexture.needsUpdate = true;
  25828. // fill buffer
  25829. const vertexDataStride = vertexDataCount * 4;
  25830. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25831. const morphTarget = morphTargets[ i ];
  25832. const morphNormal = morphNormals[ i ];
  25833. const morphColor = morphColors[ i ];
  25834. const offset = width * height * 4 * i;
  25835. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25836. const stride = j * vertexDataStride;
  25837. if ( hasMorphPosition === true ) {
  25838. _morphVec4.fromBufferAttribute( morphTarget, j );
  25839. buffer[ offset + stride + 0 ] = _morphVec4.x;
  25840. buffer[ offset + stride + 1 ] = _morphVec4.y;
  25841. buffer[ offset + stride + 2 ] = _morphVec4.z;
  25842. buffer[ offset + stride + 3 ] = 0;
  25843. }
  25844. if ( hasMorphNormals === true ) {
  25845. _morphVec4.fromBufferAttribute( morphNormal, j );
  25846. buffer[ offset + stride + 4 ] = _morphVec4.x;
  25847. buffer[ offset + stride + 5 ] = _morphVec4.y;
  25848. buffer[ offset + stride + 6 ] = _morphVec4.z;
  25849. buffer[ offset + stride + 7 ] = 0;
  25850. }
  25851. if ( hasMorphColors === true ) {
  25852. _morphVec4.fromBufferAttribute( morphColor, j );
  25853. buffer[ offset + stride + 8 ] = _morphVec4.x;
  25854. buffer[ offset + stride + 9 ] = _morphVec4.y;
  25855. buffer[ offset + stride + 10 ] = _morphVec4.z;
  25856. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  25857. }
  25858. }
  25859. }
  25860. entry = {
  25861. count: morphTargetsCount,
  25862. texture: bufferTexture,
  25863. stride: vertexDataCount,
  25864. size: new Vector2( width, height )
  25865. };
  25866. _morphTextures.set( geometry, entry );
  25867. function disposeTexture() {
  25868. bufferTexture.dispose();
  25869. _morphTextures.delete( geometry );
  25870. geometry.removeEventListener( 'dispose', disposeTexture );
  25871. }
  25872. geometry.addEventListener( 'dispose', disposeTexture );
  25873. }
  25874. return entry;
  25875. }
  25876. class MorphNode extends Node {
  25877. constructor( mesh ) {
  25878. super( 'void' );
  25879. this.mesh = mesh;
  25880. this.morphBaseInfluence = uniform( 1 );
  25881. this.updateType = NodeUpdateType.OBJECT;
  25882. }
  25883. setup( builder ) {
  25884. const { geometry } = builder;
  25885. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25886. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25887. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25888. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25889. // nodes
  25890. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25891. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25892. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25893. const width = int( size.width );
  25894. loop( morphTargetsCount, ( { i } ) => {
  25895. const influence = float( 0 ).toVar();
  25896. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25897. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25898. } else {
  25899. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25900. }
  25901. if ( hasMorphPosition === true ) {
  25902. positionLocal.addAssign( getMorph( {
  25903. bufferMap,
  25904. influence,
  25905. stride,
  25906. width,
  25907. depth: i,
  25908. offset: int( 0 )
  25909. } ) );
  25910. }
  25911. if ( hasMorphNormals === true ) {
  25912. normalLocal.addAssign( getMorph( {
  25913. bufferMap,
  25914. influence,
  25915. stride,
  25916. width,
  25917. depth: i,
  25918. offset: int( 1 )
  25919. } ) );
  25920. }
  25921. } );
  25922. }
  25923. update() {
  25924. const morphBaseInfluence = this.morphBaseInfluence;
  25925. if ( this.mesh.geometry.morphTargetsRelative ) {
  25926. morphBaseInfluence.value = 1;
  25927. } else {
  25928. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25929. }
  25930. }
  25931. }
  25932. const morphReference = nodeProxy( MorphNode );
  25933. addNodeClass( 'MorphNode', MorphNode );
  25934. const reflectView = /*#__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  25935. const refractView = /*#__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  25936. const reflectVector = /*#__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25937. const refractVector = /*#__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25938. class CubeTextureNode extends TextureNode {
  25939. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  25940. super( value, uvNode, levelNode, biasNode );
  25941. this.isCubeTextureNode = true;
  25942. }
  25943. getInputType( /*builder*/ ) {
  25944. return 'cubeTexture';
  25945. }
  25946. getDefaultUV() {
  25947. const texture = this.value;
  25948. if ( texture.mapping === CubeReflectionMapping ) {
  25949. return reflectVector;
  25950. } else if ( texture.mapping === CubeRefractionMapping ) {
  25951. return refractVector;
  25952. } else {
  25953. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  25954. return vec3( 0, 0, 0 );
  25955. }
  25956. }
  25957. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  25958. setupUV( builder, uvNode ) {
  25959. const texture = this.value;
  25960. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  25961. return vec3( uvNode.x.negate(), uvNode.yz );
  25962. } else {
  25963. return uvNode;
  25964. }
  25965. }
  25966. generateUV( builder, cubeUV ) {
  25967. return cubeUV.build( builder, 'vec3' );
  25968. }
  25969. }
  25970. const cubeTexture = nodeProxy( CubeTextureNode );
  25971. addNodeElement( 'cubeTexture', cubeTexture );
  25972. addNodeClass( 'CubeTextureNode', CubeTextureNode );
  25973. class LightingNode extends Node {
  25974. constructor() {
  25975. super( 'vec3' );
  25976. this.isLightingNode = true;
  25977. }
  25978. generate( /*builder*/ ) {
  25979. console.warn( 'Abstract function.' );
  25980. }
  25981. }
  25982. addNodeClass( 'LightingNode', LightingNode );
  25983. let overrideMaterial = null;
  25984. class AnalyticLightNode extends LightingNode {
  25985. constructor( light = null ) {
  25986. super();
  25987. this.updateType = NodeUpdateType.FRAME;
  25988. this.light = light;
  25989. this.rtt = null;
  25990. this.shadowNode = null;
  25991. this.shadowMaskNode = null;
  25992. this.color = new Color();
  25993. this._defaultColorNode = uniform( this.color );
  25994. this._shadowColorNode = null;
  25995. this.colorNode = this._defaultColorNode;
  25996. this.isAnalyticLightNode = true;
  25997. }
  25998. getCacheKey() {
  25999. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  26000. }
  26001. getHash() {
  26002. return this.light.uuid;
  26003. }
  26004. setupShadow( builder ) {
  26005. const { object } = builder;
  26006. if ( object.receiveShadow === false ) {
  26007. this.colorNode = this._defaultColorNode;
  26008. return;
  26009. }
  26010. let shadowNode = this.shadowNode;
  26011. if ( shadowNode === null ) {
  26012. if ( overrideMaterial === null ) {
  26013. overrideMaterial = builder.createNodeMaterial();
  26014. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  26015. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  26016. }
  26017. const shadow = this.light.shadow;
  26018. const rtt = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  26019. const depthTexture = new DepthTexture();
  26020. depthTexture.minFilter = NearestFilter;
  26021. depthTexture.magFilter = NearestFilter;
  26022. depthTexture.image.width = shadow.mapSize.width;
  26023. depthTexture.image.height = shadow.mapSize.height;
  26024. depthTexture.compareFunction = LessCompare;
  26025. rtt.depthTexture = depthTexture;
  26026. shadow.camera.updateProjectionMatrix();
  26027. //
  26028. const shadowIntensity = reference( 'intensity', 'float', shadow );
  26029. const bias = reference( 'bias', 'float', shadow );
  26030. const normalBias = reference( 'normalBias', 'float', shadow );
  26031. const position = object.material.shadowPositionNode || positionWorld;
  26032. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  26033. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  26034. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  26035. .and( shadowCoord.x.lessThanEqual( 1 ) )
  26036. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  26037. .and( shadowCoord.y.lessThanEqual( 1 ) )
  26038. .and( shadowCoord.z.lessThanEqual( 1 ) );
  26039. let coordZ = shadowCoord.z.add( bias );
  26040. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26041. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  26042. }
  26043. shadowCoord = vec3(
  26044. shadowCoord.x,
  26045. shadowCoord.y.oneMinus(), // follow webgpu standards
  26046. coordZ
  26047. );
  26048. const textureCompare = ( depthTexture, shadowCoord, compare ) => texture( depthTexture, shadowCoord ).compare( compare );
  26049. //const textureCompare = ( depthTexture, shadowCoord, compare ) => compare.step( texture( depthTexture, shadowCoord ) );
  26050. // BasicShadowMap
  26051. shadowNode = textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z );
  26052. // PCFShadowMap
  26053. /*
  26054. const mapSize = reference( 'mapSize', 'vec2', shadow );
  26055. const radius = reference( 'radius', 'float', shadow );
  26056. const texelSize = vec2( 1 ).div( mapSize );
  26057. const dx0 = texelSize.x.negate().mul( radius );
  26058. const dy0 = texelSize.y.negate().mul( radius );
  26059. const dx1 = texelSize.x.mul( radius );
  26060. const dy1 = texelSize.y.mul( radius );
  26061. const dx2 = dx0.mul( 2 );
  26062. const dy2 = dy0.mul( 2 );
  26063. const dx3 = dx1.mul( 2 );
  26064. const dy3 = dy1.mul( 2 );
  26065. shadowNode = add(
  26066. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  26067. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  26068. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  26069. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  26070. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  26071. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  26072. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  26073. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  26074. textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z ),
  26075. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  26076. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  26077. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  26078. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  26079. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  26080. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  26081. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  26082. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  26083. ).mul( 1 / 17 );
  26084. */
  26085. //
  26086. const shadowColor = texture( rtt.texture, shadowCoord );
  26087. const shadowMaskNode = frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) );
  26088. this.rtt = rtt;
  26089. this.colorNode = this.colorNode.mul( mix( 1, shadowMaskNode, shadowIntensity ) );
  26090. this._shadowColorNode = this.colorNode;
  26091. this.shadowNode = shadowNode;
  26092. this.shadowMaskNode = shadowMaskNode;
  26093. //
  26094. this.updateBeforeType = NodeUpdateType.RENDER;
  26095. } else {
  26096. this.colorNode = this._shadowColorNode;
  26097. }
  26098. }
  26099. setup( builder ) {
  26100. if ( this.light.castShadow ) this.setupShadow( builder );
  26101. else if ( this.shadowNode !== null ) this.disposeShadow();
  26102. }
  26103. updateShadow( frame ) {
  26104. const { rtt, light } = this;
  26105. const { renderer, scene, camera } = frame;
  26106. const currentOverrideMaterial = scene.overrideMaterial;
  26107. scene.overrideMaterial = overrideMaterial;
  26108. rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  26109. light.shadow.updateMatrices( light );
  26110. light.shadow.camera.layers.mask = camera.layers.mask;
  26111. const currentToneMapping = renderer.toneMapping;
  26112. const currentRenderTarget = renderer.getRenderTarget();
  26113. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26114. renderer.setRenderObjectFunction( ( object, ...params ) => {
  26115. if ( object.castShadow === true ) {
  26116. renderer.renderObject( object, ...params );
  26117. }
  26118. } );
  26119. renderer.setRenderTarget( rtt );
  26120. renderer.toneMapping = NoToneMapping;
  26121. renderer.render( scene, light.shadow.camera );
  26122. renderer.setRenderTarget( currentRenderTarget );
  26123. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26124. renderer.toneMapping = currentToneMapping;
  26125. scene.overrideMaterial = currentOverrideMaterial;
  26126. }
  26127. disposeShadow() {
  26128. this.rtt.dispose();
  26129. this.shadowNode = null;
  26130. this.shadowMaskNode = null;
  26131. this._shadowColorNode = null;
  26132. this.rtt = null;
  26133. this.colorNode = this._defaultColorNode;
  26134. }
  26135. updateBefore( frame ) {
  26136. const { light } = this;
  26137. if ( light.castShadow ) this.updateShadow( frame );
  26138. }
  26139. update( /*frame*/ ) {
  26140. const { light } = this;
  26141. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26142. }
  26143. }
  26144. addNodeClass( 'AnalyticLightNode', AnalyticLightNode );
  26145. const LightNodes = new WeakMap();
  26146. const sortLights = ( lights ) => {
  26147. return lights.sort( ( a, b ) => a.id - b.id );
  26148. };
  26149. class LightsNode extends Node {
  26150. constructor( lightNodes = [] ) {
  26151. super( 'vec3' );
  26152. this.totalDiffuseNode = vec3().temp( 'totalDiffuse' );
  26153. this.totalSpecularNode = vec3().temp( 'totalSpecular' );
  26154. this.outgoingLightNode = vec3().temp( 'outgoingLight' );
  26155. this.lightNodes = lightNodes;
  26156. this._hash = null;
  26157. }
  26158. get hasLight() {
  26159. return this.lightNodes.length > 0;
  26160. }
  26161. getHash() {
  26162. if ( this._hash === null ) {
  26163. const hash = [];
  26164. for ( const lightNode of this.lightNodes ) {
  26165. hash.push( lightNode.getHash() );
  26166. }
  26167. this._hash = 'lights-' + hash.join( ',' );
  26168. }
  26169. return this._hash;
  26170. }
  26171. analyze( builder ) {
  26172. const properties = builder.getDataFromNode( this );
  26173. for ( const node of properties.nodes ) {
  26174. node.build( builder );
  26175. }
  26176. }
  26177. setup( builder ) {
  26178. const context = builder.context;
  26179. const lightingModel = context.lightingModel;
  26180. let outgoingLightNode = this.outgoingLightNode;
  26181. if ( lightingModel ) {
  26182. const { lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26183. context.outgoingLight = outgoingLightNode;
  26184. const stack = builder.addStack();
  26185. //
  26186. const properties = builder.getDataFromNode( this );
  26187. properties.nodes = stack.nodes;
  26188. //
  26189. lightingModel.start( context, stack, builder );
  26190. // lights
  26191. for ( const lightNode of lightNodes ) {
  26192. lightNode.build( builder );
  26193. }
  26194. //
  26195. lightingModel.indirect( context, stack, builder );
  26196. //
  26197. const { backdrop, backdropAlpha } = context;
  26198. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26199. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26200. if ( backdrop !== null ) {
  26201. if ( backdropAlpha !== null ) {
  26202. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26203. } else {
  26204. totalDiffuse = vec3( backdrop );
  26205. }
  26206. context.material.transparent = true;
  26207. }
  26208. totalDiffuseNode.assign( totalDiffuse );
  26209. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26210. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26211. //
  26212. lightingModel.finish( context, stack, builder );
  26213. //
  26214. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26215. }
  26216. return outgoingLightNode;
  26217. }
  26218. _getLightNodeById( id ) {
  26219. for ( const lightNode of this.lightNodes ) {
  26220. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26221. return lightNode;
  26222. }
  26223. }
  26224. return null;
  26225. }
  26226. fromLights( lights = [] ) {
  26227. const lightNodes = [];
  26228. lights = sortLights( lights );
  26229. for ( const light of lights ) {
  26230. let lightNode = this._getLightNodeById( light.id );
  26231. if ( lightNode === null ) {
  26232. const lightClass = light.constructor;
  26233. const lightNodeClass = LightNodes.has( lightClass ) ? LightNodes.get( lightClass ) : AnalyticLightNode;
  26234. lightNode = nodeObject( new lightNodeClass( light ) );
  26235. }
  26236. lightNodes.push( lightNode );
  26237. }
  26238. this.lightNodes = lightNodes;
  26239. this._hash = null;
  26240. return this;
  26241. }
  26242. }
  26243. const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) );
  26244. const lightsNode = nodeProxy( LightsNode );
  26245. function addLightNode( lightClass, lightNodeClass ) {
  26246. if ( LightNodes.has( lightClass ) ) {
  26247. console.warn( `Redefinition of light node ${ lightNodeClass.type }` );
  26248. return;
  26249. }
  26250. if ( typeof lightClass !== 'function' ) throw new Error( `Light ${ lightClass.name } is not a class` );
  26251. if ( typeof lightNodeClass !== 'function' || ! lightNodeClass.type ) throw new Error( `Light node ${ lightNodeClass.type } is not a class` );
  26252. LightNodes.set( lightClass, lightNodeClass );
  26253. }
  26254. class AONode extends LightingNode {
  26255. constructor( aoNode = null ) {
  26256. super();
  26257. this.aoNode = aoNode;
  26258. }
  26259. setup( builder ) {
  26260. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26261. }
  26262. }
  26263. addNodeClass( 'AONode', AONode );
  26264. class LightingContextNode extends ContextNode {
  26265. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26266. super( node );
  26267. this.lightingModel = lightingModel;
  26268. this.backdropNode = backdropNode;
  26269. this.backdropAlphaNode = backdropAlphaNode;
  26270. this._context = null;
  26271. }
  26272. getContext() {
  26273. const { backdropNode, backdropAlphaNode } = this;
  26274. const directDiffuse = vec3().temp( 'directDiffuse' ),
  26275. directSpecular = vec3().temp( 'directSpecular' ),
  26276. indirectDiffuse = vec3().temp( 'indirectDiffuse' ),
  26277. indirectSpecular = vec3().temp( 'indirectSpecular' );
  26278. const reflectedLight = {
  26279. directDiffuse,
  26280. directSpecular,
  26281. indirectDiffuse,
  26282. indirectSpecular
  26283. };
  26284. const context = {
  26285. radiance: vec3().temp( 'radiance' ),
  26286. irradiance: vec3().temp( 'irradiance' ),
  26287. iblIrradiance: vec3().temp( 'iblIrradiance' ),
  26288. ambientOcclusion: float( 1 ).temp( 'ambientOcclusion' ),
  26289. reflectedLight,
  26290. backdrop: backdropNode,
  26291. backdropAlpha: backdropAlphaNode
  26292. };
  26293. return context;
  26294. }
  26295. setup( builder ) {
  26296. this.context = this._context || ( this._context = this.getContext() );
  26297. this.context.lightingModel = this.lightingModel || builder.context.lightingModel;
  26298. return super.setup( builder );
  26299. }
  26300. }
  26301. const lightingContext = nodeProxy( LightingContextNode );
  26302. addNodeElement( 'lightingContext', lightingContext );
  26303. addNodeClass( 'LightingContextNode', LightingContextNode );
  26304. class IrradianceNode extends LightingNode {
  26305. constructor( node ) {
  26306. super();
  26307. this.node = node;
  26308. }
  26309. setup( builder ) {
  26310. builder.context.irradiance.addAssign( this.node );
  26311. }
  26312. }
  26313. addNodeClass( 'IrradianceNode', IrradianceNode );
  26314. let resolution, viewportResult;
  26315. class ViewportNode extends Node {
  26316. constructor( scope ) {
  26317. super();
  26318. this.scope = scope;
  26319. this.isViewportNode = true;
  26320. }
  26321. getNodeType() {
  26322. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  26323. else if ( this.scope === ViewportNode.COORDINATE ) return 'vec3';
  26324. else return 'vec2';
  26325. }
  26326. getUpdateType() {
  26327. let updateType = NodeUpdateType.NONE;
  26328. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  26329. updateType = NodeUpdateType.RENDER;
  26330. }
  26331. this.updateType = updateType;
  26332. return updateType;
  26333. }
  26334. update( { renderer } ) {
  26335. if ( this.scope === ViewportNode.VIEWPORT ) {
  26336. renderer.getViewport( viewportResult );
  26337. } else {
  26338. renderer.getDrawingBufferSize( resolution );
  26339. }
  26340. }
  26341. setup( /*builder*/ ) {
  26342. const scope = this.scope;
  26343. let output = null;
  26344. if ( scope === ViewportNode.RESOLUTION ) {
  26345. output = uniform( resolution || ( resolution = new Vector2() ) );
  26346. } else if ( scope === ViewportNode.VIEWPORT ) {
  26347. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  26348. } else {
  26349. output = viewportCoordinate.div( viewportResolution );
  26350. let outX = output.x;
  26351. let outY = output.y;
  26352. if ( /bottom/i.test( scope ) ) outY = outY.oneMinus();
  26353. if ( /right/i.test( scope ) ) outX = outX.oneMinus();
  26354. output = vec2( outX, outY );
  26355. }
  26356. return output;
  26357. }
  26358. generate( builder ) {
  26359. if ( this.scope === ViewportNode.COORDINATE ) {
  26360. let coord = builder.getFragCoord();
  26361. if ( builder.isFlipY() ) {
  26362. // follow webgpu standards
  26363. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  26364. coord = `${ builder.getType( 'vec3' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y, ${ coord }.z )`;
  26365. }
  26366. return coord;
  26367. }
  26368. return super.generate( builder );
  26369. }
  26370. }
  26371. ViewportNode.COORDINATE = 'coordinate';
  26372. ViewportNode.RESOLUTION = 'resolution';
  26373. ViewportNode.VIEWPORT = 'viewport';
  26374. ViewportNode.TOP_LEFT = 'topLeft';
  26375. ViewportNode.BOTTOM_LEFT = 'bottomLeft';
  26376. ViewportNode.TOP_RIGHT = 'topRight';
  26377. ViewportNode.BOTTOM_RIGHT = 'bottomRight';
  26378. const viewportCoordinate = nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  26379. const viewportResolution = nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  26380. const viewport = nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  26381. const viewportTopLeft = nodeImmutable( ViewportNode, ViewportNode.TOP_LEFT );
  26382. const viewportBottomLeft = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_LEFT );
  26383. const viewportTopRight = nodeImmutable( ViewportNode, ViewportNode.TOP_RIGHT );
  26384. const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIGHT );
  26385. addNodeClass( 'ViewportNode', ViewportNode );
  26386. const _size$7 = /*@__PURE__*/ new Vector2();
  26387. class ViewportTextureNode extends TextureNode {
  26388. constructor( uvNode = viewportTopLeft, levelNode = null, framebufferTexture = null ) {
  26389. if ( framebufferTexture === null ) {
  26390. framebufferTexture = new FramebufferTexture();
  26391. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26392. }
  26393. super( framebufferTexture, uvNode, levelNode );
  26394. this.generateMipmaps = false;
  26395. this.isOutputTextureNode = true;
  26396. this.updateBeforeType = NodeUpdateType.FRAME;
  26397. }
  26398. updateBefore( frame ) {
  26399. const renderer = frame.renderer;
  26400. renderer.getDrawingBufferSize( _size$7 );
  26401. //
  26402. const framebufferTexture = this.value;
  26403. if ( framebufferTexture.image.width !== _size$7.width || framebufferTexture.image.height !== _size$7.height ) {
  26404. framebufferTexture.image.width = _size$7.width;
  26405. framebufferTexture.image.height = _size$7.height;
  26406. framebufferTexture.needsUpdate = true;
  26407. }
  26408. //
  26409. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26410. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26411. renderer.copyFramebufferToTexture( framebufferTexture );
  26412. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26413. }
  26414. clone() {
  26415. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26416. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26417. return viewportTextureNode;
  26418. }
  26419. }
  26420. const viewportTexture = nodeProxy( ViewportTextureNode );
  26421. const viewportMipTexture = nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26422. addNodeElement( 'viewportTexture', viewportTexture );
  26423. addNodeElement( 'viewportMipTexture', viewportMipTexture );
  26424. addNodeClass( 'ViewportTextureNode', ViewportTextureNode );
  26425. let sharedDepthbuffer = null;
  26426. class ViewportDepthTextureNode extends ViewportTextureNode {
  26427. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  26428. if ( sharedDepthbuffer === null ) {
  26429. sharedDepthbuffer = new DepthTexture();
  26430. }
  26431. super( uvNode, levelNode, sharedDepthbuffer );
  26432. }
  26433. }
  26434. const viewportDepthTexture = nodeProxy( ViewportDepthTextureNode );
  26435. addNodeElement( 'viewportDepthTexture', viewportDepthTexture );
  26436. addNodeClass( 'ViewportDepthTextureNode', ViewportDepthTextureNode );
  26437. class ViewportDepthNode extends Node {
  26438. constructor( scope, valueNode = null ) {
  26439. super( 'float' );
  26440. this.scope = scope;
  26441. this.valueNode = valueNode;
  26442. this.isViewportDepthNode = true;
  26443. }
  26444. generate( builder ) {
  26445. const { scope } = this;
  26446. if ( scope === ViewportDepthNode.DEPTH ) {
  26447. return builder.getFragDepth();
  26448. }
  26449. return super.generate( builder );
  26450. }
  26451. setup( { camera } ) {
  26452. const { scope } = this;
  26453. const texture = this.valueNode;
  26454. let node = null;
  26455. if ( scope === ViewportDepthNode.DEPTH ) {
  26456. if ( texture !== null ) {
  26457. node = depthBase().assign( texture );
  26458. } else {
  26459. if ( camera.isPerspectiveCamera ) {
  26460. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26461. } else {
  26462. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26463. }
  26464. }
  26465. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26466. if ( texture !== null ) {
  26467. if ( camera.isPerspectiveCamera ) {
  26468. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  26469. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26470. } else {
  26471. node = texture;
  26472. }
  26473. } else {
  26474. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26475. }
  26476. }
  26477. return node;
  26478. }
  26479. }
  26480. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26481. // -near maps to 0; -far maps to 1
  26482. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26483. // maps orthographic depth in [ 0, 1 ] to viewZ
  26484. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26485. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26486. // -near maps to 0; -far maps to 1
  26487. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26488. // maps perspective depth in [ 0, 1 ] to viewZ
  26489. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26490. ViewportDepthNode.DEPTH = 'depth';
  26491. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26492. const depthBase = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26493. const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26494. const linearDepth = nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26495. const viewportLinearDepth = linearDepth( viewportDepthTexture() );
  26496. depth.assign = ( value ) => depthBase( value );
  26497. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );
  26498. class ClippingNode extends Node {
  26499. constructor( scope = ClippingNode.DEFAULT ) {
  26500. super();
  26501. this.scope = scope;
  26502. }
  26503. setup( builder ) {
  26504. super.setup( builder );
  26505. const clippingContext = builder.clippingContext;
  26506. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26507. const numClippingPlanes = globalClippingCount + localClippingCount;
  26508. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26509. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26510. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26511. } else {
  26512. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26513. }
  26514. }
  26515. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26516. return tslFn( () => {
  26517. const clippingPlanes = uniforms( planes );
  26518. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26519. const distanceGradient = property( 'float', 'distanceToGradient' );
  26520. const clipOpacity = property( 'float', 'clipOpacity' );
  26521. clipOpacity.assign( 1 );
  26522. let plane;
  26523. loop( numUnionClippingPlanes, ( { i } ) => {
  26524. plane = clippingPlanes.element( i );
  26525. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26526. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26527. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26528. clipOpacity.equal( 0.0 ).discard();
  26529. } );
  26530. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26531. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26532. unionClipOpacity.assign( 1 );
  26533. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26534. plane = clippingPlanes.element( i );
  26535. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26536. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26537. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26538. } );
  26539. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26540. }
  26541. diffuseColor.a.mulAssign( clipOpacity );
  26542. diffuseColor.a.equal( 0.0 ).discard();
  26543. } )();
  26544. }
  26545. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26546. return tslFn( () => {
  26547. const clippingPlanes = uniforms( planes );
  26548. let plane;
  26549. loop( numUnionClippingPlanes, ( { i } ) => {
  26550. plane = clippingPlanes.element( i );
  26551. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26552. } );
  26553. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26554. const clipped = property( 'bool', 'clipped' );
  26555. clipped.assign( true );
  26556. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26557. plane = clippingPlanes.element( i );
  26558. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26559. } );
  26560. clipped.discard();
  26561. }
  26562. } )();
  26563. }
  26564. }
  26565. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26566. ClippingNode.DEFAULT = 'default';
  26567. const clipping = () => nodeObject( new ClippingNode() );
  26568. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26569. class FrontFacingNode extends Node {
  26570. constructor() {
  26571. super( 'bool' );
  26572. this.isFrontFacingNode = true;
  26573. }
  26574. generate( builder ) {
  26575. const { renderer, material } = builder;
  26576. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  26577. if ( material.side === BackSide ) {
  26578. return 'false';
  26579. }
  26580. }
  26581. return builder.getFrontFacing();
  26582. }
  26583. }
  26584. const frontFacing = nodeImmutable( FrontFacingNode );
  26585. const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  26586. addNodeClass( 'FrontFacingNode', FrontFacingNode );
  26587. const NodeMaterials = new Map();
  26588. class NodeMaterial extends Material {
  26589. constructor() {
  26590. super();
  26591. this.isNodeMaterial = true;
  26592. this.type = this.constructor.type;
  26593. this.forceSinglePass = false;
  26594. this.fog = true;
  26595. this.lights = true;
  26596. this.normals = true;
  26597. this.lightsNode = null;
  26598. this.envNode = null;
  26599. this.aoNode = null;
  26600. this.colorNode = null;
  26601. this.normalNode = null;
  26602. this.opacityNode = null;
  26603. this.backdropNode = null;
  26604. this.backdropAlphaNode = null;
  26605. this.alphaTestNode = null;
  26606. this.positionNode = null;
  26607. this.depthNode = null;
  26608. this.shadowNode = null;
  26609. this.shadowPositionNode = null;
  26610. this.outputNode = null;
  26611. this.mrtNode = null;
  26612. this.fragmentNode = null;
  26613. this.vertexNode = null;
  26614. }
  26615. customProgramCacheKey() {
  26616. return this.type + getCacheKey( this );
  26617. }
  26618. build( builder ) {
  26619. this.setup( builder );
  26620. }
  26621. setup( builder ) {
  26622. // < VERTEX STAGE >
  26623. builder.addStack();
  26624. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26625. builder.addFlow( 'vertex', builder.removeStack() );
  26626. // < FRAGMENT STAGE >
  26627. builder.addStack();
  26628. let resultNode;
  26629. const clippingNode = this.setupClipping( builder );
  26630. if ( this.depthWrite === true ) this.setupDepth( builder );
  26631. if ( this.fragmentNode === null ) {
  26632. if ( this.normals === true ) this.setupNormal( builder );
  26633. this.setupDiffuseColor( builder );
  26634. this.setupVariants( builder );
  26635. const outgoingLightNode = this.setupLighting( builder );
  26636. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26637. // force unsigned floats - useful for RenderTargets
  26638. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26639. resultNode = this.setupOutput( builder, basicOutput );
  26640. // OUTPUT NODE
  26641. output.assign( resultNode );
  26642. //
  26643. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26644. // MRT
  26645. const renderTarget = builder.renderer.getRenderTarget();
  26646. if ( renderTarget !== null ) {
  26647. const mrt = builder.renderer.getMRT();
  26648. const materialMRT = this.mrtNode;
  26649. if ( mrt !== null ) {
  26650. resultNode = mrt;
  26651. if ( materialMRT !== null ) {
  26652. resultNode = mrt.merge( materialMRT );
  26653. }
  26654. } else if ( materialMRT !== null ) {
  26655. resultNode = materialMRT;
  26656. }
  26657. }
  26658. } else {
  26659. let fragmentNode = this.fragmentNode;
  26660. if ( fragmentNode.isOutputStructNode !== true ) {
  26661. fragmentNode = vec4( fragmentNode );
  26662. }
  26663. resultNode = this.setupOutput( builder, fragmentNode );
  26664. }
  26665. builder.stack.outputNode = resultNode;
  26666. builder.addFlow( 'fragment', builder.removeStack() );
  26667. }
  26668. setupClipping( builder ) {
  26669. if ( builder.clippingContext === null ) return null;
  26670. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26671. let result = null;
  26672. if ( globalClippingCount || localClippingCount ) {
  26673. if ( this.alphaToCoverage ) {
  26674. // to be added to flow when the color/alpha value has been determined
  26675. result = clippingAlpha();
  26676. } else {
  26677. builder.stack.add( clipping() );
  26678. }
  26679. }
  26680. return result;
  26681. }
  26682. setupDepth( builder ) {
  26683. const { renderer } = builder;
  26684. // Depth
  26685. let depthNode = this.depthNode;
  26686. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  26687. const fragDepth = modelViewProjection().w.add( 1 );
  26688. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26689. }
  26690. if ( depthNode !== null ) {
  26691. depth.assign( depthNode ).append();
  26692. }
  26693. }
  26694. setupPosition( builder ) {
  26695. const { object } = builder;
  26696. const geometry = object.geometry;
  26697. builder.addStack();
  26698. // Vertex
  26699. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26700. morphReference( object ).append();
  26701. }
  26702. if ( object.isSkinnedMesh === true ) {
  26703. skinningReference( object ).append();
  26704. }
  26705. if ( this.displacementMap ) {
  26706. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26707. const displacementScale = materialReference( 'displacementScale', 'float' );
  26708. const displacementBias = materialReference( 'displacementBias', 'float' );
  26709. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26710. }
  26711. if ( object.isBatchedMesh ) {
  26712. batch( object ).append();
  26713. }
  26714. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26715. instance( object ).append();
  26716. }
  26717. if ( this.positionNode !== null ) {
  26718. positionLocal.assign( this.positionNode );
  26719. }
  26720. const mvp = modelViewProjection();
  26721. builder.context.vertex = builder.removeStack();
  26722. builder.context.mvp = mvp;
  26723. return mvp;
  26724. }
  26725. setupDiffuseColor( { object, geometry } ) {
  26726. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26727. // VERTEX COLORS
  26728. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26729. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26730. }
  26731. // Instanced colors
  26732. if ( object.instanceColor ) {
  26733. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26734. colorNode = instanceColor.mul( colorNode );
  26735. }
  26736. // COLOR
  26737. diffuseColor.assign( colorNode );
  26738. // OPACITY
  26739. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26740. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26741. // ALPHA TEST
  26742. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26743. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26744. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26745. }
  26746. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26747. diffuseColor.a.assign( 1.0 );
  26748. }
  26749. }
  26750. setupVariants( /*builder*/ ) {
  26751. // Interface function.
  26752. }
  26753. setupNormal() {
  26754. // NORMAL VIEW
  26755. if ( this.flatShading === true ) {
  26756. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  26757. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26758. } else {
  26759. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26760. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26761. }
  26762. }
  26763. setupEnvironment( builder ) {
  26764. let node = null;
  26765. if ( this.envNode ) {
  26766. node = this.envNode;
  26767. } else if ( this.envMap ) {
  26768. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  26769. } else if ( builder.environmentNode ) {
  26770. node = builder.environmentNode;
  26771. }
  26772. return node;
  26773. }
  26774. setupLightMap( builder ) {
  26775. let node = null;
  26776. if ( builder.material.lightMap ) {
  26777. node = new IrradianceNode( materialLightMap );
  26778. }
  26779. return node;
  26780. }
  26781. setupLights( builder ) {
  26782. const materialLightsNode = [];
  26783. //
  26784. const envNode = this.setupEnvironment( builder );
  26785. if ( envNode && envNode.isLightingNode ) {
  26786. materialLightsNode.push( envNode );
  26787. }
  26788. const lightMapNode = this.setupLightMap( builder );
  26789. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26790. materialLightsNode.push( lightMapNode );
  26791. }
  26792. if ( this.aoNode !== null || builder.material.aoMap ) {
  26793. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26794. materialLightsNode.push( new AONode( aoNode ) );
  26795. }
  26796. let lightsN = this.lightsNode || builder.lightsNode;
  26797. if ( materialLightsNode.length > 0 ) {
  26798. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  26799. }
  26800. return lightsN;
  26801. }
  26802. setupLightingModel( /*builder*/ ) {
  26803. // Interface function.
  26804. }
  26805. setupLighting( builder ) {
  26806. const { material } = builder;
  26807. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26808. // OUTGOING LIGHT
  26809. const lights = this.lights === true || this.lightsNode !== null;
  26810. const lightsNode = lights ? this.setupLights( builder ) : null;
  26811. let outgoingLightNode = diffuseColor.rgb;
  26812. if ( lightsNode && lightsNode.hasLight !== false ) {
  26813. const lightingModel = this.setupLightingModel( builder );
  26814. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26815. } else if ( backdropNode !== null ) {
  26816. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26817. }
  26818. // EMISSIVE
  26819. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26820. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26821. outgoingLightNode = outgoingLightNode.add( emissive );
  26822. }
  26823. return outgoingLightNode;
  26824. }
  26825. setupOutput( builder, outputNode ) {
  26826. // FOG
  26827. if ( this.fog === true ) {
  26828. const fogNode = builder.fogNode;
  26829. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26830. }
  26831. return outputNode;
  26832. }
  26833. setDefaultValues( material ) {
  26834. // This approach is to reuse the native refreshUniforms*
  26835. // and turn available the use of features like transmission and environment in core
  26836. for ( const property in material ) {
  26837. const value = material[ property ];
  26838. if ( this[ property ] === undefined ) {
  26839. this[ property ] = value;
  26840. if ( value && value.clone ) this[ property ] = value.clone();
  26841. }
  26842. }
  26843. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26844. for ( const key in descriptors ) {
  26845. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26846. descriptors[ key ].get !== undefined ) {
  26847. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26848. }
  26849. }
  26850. }
  26851. toJSON( meta ) {
  26852. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26853. if ( isRoot ) {
  26854. meta = {
  26855. textures: {},
  26856. images: {},
  26857. nodes: {}
  26858. };
  26859. }
  26860. const data = Material.prototype.toJSON.call( this, meta );
  26861. const nodeChildren = getNodeChildren( this );
  26862. data.inputNodes = {};
  26863. for ( const { property, childNode } of nodeChildren ) {
  26864. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26865. }
  26866. // TODO: Copied from Object3D.toJSON
  26867. function extractFromCache( cache ) {
  26868. const values = [];
  26869. for ( const key in cache ) {
  26870. const data = cache[ key ];
  26871. delete data.metadata;
  26872. values.push( data );
  26873. }
  26874. return values;
  26875. }
  26876. if ( isRoot ) {
  26877. const textures = extractFromCache( meta.textures );
  26878. const images = extractFromCache( meta.images );
  26879. const nodes = extractFromCache( meta.nodes );
  26880. if ( textures.length > 0 ) data.textures = textures;
  26881. if ( images.length > 0 ) data.images = images;
  26882. if ( nodes.length > 0 ) data.nodes = nodes;
  26883. }
  26884. return data;
  26885. }
  26886. copy( source ) {
  26887. this.lightsNode = source.lightsNode;
  26888. this.envNode = source.envNode;
  26889. this.colorNode = source.colorNode;
  26890. this.normalNode = source.normalNode;
  26891. this.opacityNode = source.opacityNode;
  26892. this.backdropNode = source.backdropNode;
  26893. this.backdropAlphaNode = source.backdropAlphaNode;
  26894. this.alphaTestNode = source.alphaTestNode;
  26895. this.positionNode = source.positionNode;
  26896. this.depthNode = source.depthNode;
  26897. this.shadowNode = source.shadowNode;
  26898. this.shadowPositionNode = source.shadowPositionNode;
  26899. this.outputNode = source.outputNode;
  26900. this.mrtNode = source.mrtNode;
  26901. this.fragmentNode = source.fragmentNode;
  26902. this.vertexNode = source.vertexNode;
  26903. return super.copy( source );
  26904. }
  26905. static fromMaterial( material ) {
  26906. if ( material.isNodeMaterial === true ) { // is already a node material
  26907. return material;
  26908. }
  26909. const type = material.type.replace( 'Material', 'NodeMaterial' );
  26910. const nodeMaterial = createNodeMaterialFromType( type );
  26911. if ( nodeMaterial === undefined ) {
  26912. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  26913. }
  26914. for ( const key in material ) {
  26915. nodeMaterial[ key ] = material[ key ];
  26916. }
  26917. return nodeMaterial;
  26918. }
  26919. }
  26920. function addNodeMaterial( type, nodeMaterial ) {
  26921. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  26922. if ( NodeMaterials.has( type ) ) {
  26923. console.warn( `Redefinition of node material ${ type }` );
  26924. return;
  26925. }
  26926. NodeMaterials.set( type, nodeMaterial );
  26927. nodeMaterial.type = type;
  26928. }
  26929. function createNodeMaterialFromType( type ) {
  26930. const Material = NodeMaterials.get( type );
  26931. if ( Material !== undefined ) {
  26932. return new Material();
  26933. }
  26934. }
  26935. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  26936. class Uniform {
  26937. constructor( name, value ) {
  26938. this.name = name;
  26939. this.value = value;
  26940. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  26941. this.itemSize = 0;
  26942. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  26943. }
  26944. setValue( value ) {
  26945. this.value = value;
  26946. }
  26947. getValue() {
  26948. return this.value;
  26949. }
  26950. }
  26951. class NumberUniform extends Uniform {
  26952. constructor( name, value = 0 ) {
  26953. super( name, value );
  26954. this.isNumberUniform = true;
  26955. this.boundary = 4;
  26956. this.itemSize = 1;
  26957. }
  26958. }
  26959. class Vector2Uniform extends Uniform {
  26960. constructor( name, value = new Vector2() ) {
  26961. super( name, value );
  26962. this.isVector2Uniform = true;
  26963. this.boundary = 8;
  26964. this.itemSize = 2;
  26965. }
  26966. }
  26967. class Vector3Uniform extends Uniform {
  26968. constructor( name, value = new Vector3() ) {
  26969. super( name, value );
  26970. this.isVector3Uniform = true;
  26971. this.boundary = 16;
  26972. this.itemSize = 3;
  26973. }
  26974. }
  26975. class Vector4Uniform extends Uniform {
  26976. constructor( name, value = new Vector4() ) {
  26977. super( name, value );
  26978. this.isVector4Uniform = true;
  26979. this.boundary = 16;
  26980. this.itemSize = 4;
  26981. }
  26982. }
  26983. class ColorUniform extends Uniform {
  26984. constructor( name, value = new Color() ) {
  26985. super( name, value );
  26986. this.isColorUniform = true;
  26987. this.boundary = 16;
  26988. this.itemSize = 3;
  26989. }
  26990. }
  26991. class Matrix3Uniform extends Uniform {
  26992. constructor( name, value = new Matrix3() ) {
  26993. super( name, value );
  26994. this.isMatrix3Uniform = true;
  26995. this.boundary = 48;
  26996. this.itemSize = 12;
  26997. }
  26998. }
  26999. class Matrix4Uniform extends Uniform {
  27000. constructor( name, value = new Matrix4() ) {
  27001. super( name, value );
  27002. this.isMatrix4Uniform = true;
  27003. this.boundary = 64;
  27004. this.itemSize = 16;
  27005. }
  27006. }
  27007. class NumberNodeUniform extends NumberUniform {
  27008. constructor( nodeUniform ) {
  27009. super( nodeUniform.name, nodeUniform.value );
  27010. this.nodeUniform = nodeUniform;
  27011. }
  27012. getValue() {
  27013. return this.nodeUniform.value;
  27014. }
  27015. }
  27016. class Vector2NodeUniform extends Vector2Uniform {
  27017. constructor( nodeUniform ) {
  27018. super( nodeUniform.name, nodeUniform.value );
  27019. this.nodeUniform = nodeUniform;
  27020. }
  27021. getValue() {
  27022. return this.nodeUniform.value;
  27023. }
  27024. }
  27025. class Vector3NodeUniform extends Vector3Uniform {
  27026. constructor( nodeUniform ) {
  27027. super( nodeUniform.name, nodeUniform.value );
  27028. this.nodeUniform = nodeUniform;
  27029. }
  27030. getValue() {
  27031. return this.nodeUniform.value;
  27032. }
  27033. }
  27034. class Vector4NodeUniform extends Vector4Uniform {
  27035. constructor( nodeUniform ) {
  27036. super( nodeUniform.name, nodeUniform.value );
  27037. this.nodeUniform = nodeUniform;
  27038. }
  27039. getValue() {
  27040. return this.nodeUniform.value;
  27041. }
  27042. }
  27043. class ColorNodeUniform extends ColorUniform {
  27044. constructor( nodeUniform ) {
  27045. super( nodeUniform.name, nodeUniform.value );
  27046. this.nodeUniform = nodeUniform;
  27047. }
  27048. getValue() {
  27049. return this.nodeUniform.value;
  27050. }
  27051. }
  27052. class Matrix3NodeUniform extends Matrix3Uniform {
  27053. constructor( nodeUniform ) {
  27054. super( nodeUniform.name, nodeUniform.value );
  27055. this.nodeUniform = nodeUniform;
  27056. }
  27057. getValue() {
  27058. return this.nodeUniform.value;
  27059. }
  27060. }
  27061. class Matrix4NodeUniform extends Matrix4Uniform {
  27062. constructor( nodeUniform ) {
  27063. super( nodeUniform.name, nodeUniform.value );
  27064. this.nodeUniform = nodeUniform;
  27065. }
  27066. getValue() {
  27067. return this.nodeUniform.value;
  27068. }
  27069. }
  27070. class CondNode extends Node {
  27071. constructor( condNode, ifNode, elseNode = null ) {
  27072. super();
  27073. this.condNode = condNode;
  27074. this.ifNode = ifNode;
  27075. this.elseNode = elseNode;
  27076. }
  27077. getNodeType( builder ) {
  27078. const ifType = this.ifNode.getNodeType( builder );
  27079. if ( this.elseNode !== null ) {
  27080. const elseType = this.elseNode.getNodeType( builder );
  27081. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  27082. return elseType;
  27083. }
  27084. }
  27085. return ifType;
  27086. }
  27087. setup( builder ) {
  27088. const properties = builder.getNodeProperties( this );
  27089. properties.condNode = this.condNode.cache();
  27090. properties.ifNode = this.ifNode.cache();
  27091. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  27092. }
  27093. generate( builder, output ) {
  27094. const type = this.getNodeType( builder );
  27095. const nodeData = builder.getDataFromNode( this );
  27096. if ( nodeData.nodeProperty !== undefined ) {
  27097. return nodeData.nodeProperty;
  27098. }
  27099. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  27100. const needsOutput = output !== 'void';
  27101. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  27102. nodeData.nodeProperty = nodeProperty;
  27103. const nodeSnippet = condNode.build( builder, 'bool' );
  27104. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  27105. let ifSnippet = ifNode.build( builder, type );
  27106. if ( ifSnippet ) {
  27107. if ( needsOutput ) {
  27108. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  27109. } else {
  27110. ifSnippet = 'return ' + ifSnippet + ';';
  27111. }
  27112. }
  27113. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  27114. if ( elseNode !== null ) {
  27115. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  27116. let elseSnippet = elseNode.build( builder, type );
  27117. if ( elseSnippet ) {
  27118. if ( needsOutput ) {
  27119. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  27120. } else {
  27121. elseSnippet = 'return ' + elseSnippet + ';';
  27122. }
  27123. }
  27124. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  27125. } else {
  27126. builder.addFlowCode( '\n\n' );
  27127. }
  27128. return builder.format( nodeProperty, type, output );
  27129. }
  27130. }
  27131. const cond = nodeProxy( CondNode );
  27132. addNodeElement( 'cond', cond );
  27133. addNodeClass( 'CondNode', CondNode );
  27134. class StackNode extends Node {
  27135. constructor( parent = null ) {
  27136. super();
  27137. this.nodes = [];
  27138. this.outputNode = null;
  27139. this.parent = parent;
  27140. this._currentCond = null;
  27141. this.isStackNode = true;
  27142. }
  27143. getNodeType( builder ) {
  27144. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27145. }
  27146. add( node ) {
  27147. this.nodes.push( node );
  27148. return this;
  27149. }
  27150. if( boolNode, method ) {
  27151. const methodNode = new ShaderNode( method );
  27152. this._currentCond = cond( boolNode, methodNode );
  27153. return this.add( this._currentCond );
  27154. }
  27155. elseif( boolNode, method ) {
  27156. const methodNode = new ShaderNode( method );
  27157. const ifNode = cond( boolNode, methodNode );
  27158. this._currentCond.elseNode = ifNode;
  27159. this._currentCond = ifNode;
  27160. return this;
  27161. }
  27162. else( method ) {
  27163. this._currentCond.elseNode = new ShaderNode( method );
  27164. return this;
  27165. }
  27166. build( builder, ...params ) {
  27167. const previousStack = getCurrentStack();
  27168. setCurrentStack( this );
  27169. for ( const node of this.nodes ) {
  27170. node.build( builder, 'void' );
  27171. }
  27172. setCurrentStack( previousStack );
  27173. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27174. }
  27175. }
  27176. const stack = nodeProxy( StackNode );
  27177. addNodeClass( 'StackNode', StackNode );
  27178. class EquirectUVNode extends TempNode {
  27179. constructor( dirNode = positionWorldDirection ) {
  27180. super( 'vec2' );
  27181. this.dirNode = dirNode;
  27182. }
  27183. setup() {
  27184. const dir = this.dirNode;
  27185. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27186. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27187. return vec2( u, v );
  27188. }
  27189. }
  27190. const equirectUV = nodeProxy( EquirectUVNode );
  27191. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27192. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27193. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27194. constructor( size = 1, options = {} ) {
  27195. super( size, options );
  27196. this.isCubeRenderTarget = true;
  27197. }
  27198. fromEquirectangularTexture( renderer, texture$1 ) {
  27199. const currentMinFilter = texture$1.minFilter;
  27200. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27201. texture$1.generateMipmaps = true;
  27202. this.texture.type = texture$1.type;
  27203. this.texture.colorSpace = texture$1.colorSpace;
  27204. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27205. this.texture.minFilter = texture$1.minFilter;
  27206. this.texture.magFilter = texture$1.magFilter;
  27207. const geometry = new BoxGeometry( 5, 5, 5 );
  27208. const uvNode = equirectUV( positionWorldDirection );
  27209. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27210. material.colorNode = texture( texture$1, uvNode, 0 );
  27211. material.side = BackSide;
  27212. material.blending = NoBlending;
  27213. const mesh = new Mesh( geometry, material );
  27214. const scene = new Scene();
  27215. scene.add( mesh );
  27216. // Avoid blurred poles
  27217. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27218. const camera = new CubeCamera( 1, 10, this );
  27219. camera.update( renderer, scene );
  27220. texture$1.minFilter = currentMinFilter;
  27221. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27222. mesh.geometry.dispose();
  27223. mesh.material.dispose();
  27224. return this;
  27225. }
  27226. }
  27227. // These defines must match with PMREMGenerator
  27228. const cubeUV_r0 = float( 1.0 );
  27229. const cubeUV_m0 = float( - 2.0 );
  27230. const cubeUV_r1 = float( 0.8 );
  27231. const cubeUV_m1 = float( - 1.0 );
  27232. const cubeUV_r4 = float( 0.4 );
  27233. const cubeUV_m4 = float( 2.0 );
  27234. const cubeUV_r5 = float( 0.305 );
  27235. const cubeUV_m5 = float( 3.0 );
  27236. const cubeUV_r6 = float( 0.21 );
  27237. const cubeUV_m6 = float( 4.0 );
  27238. const cubeUV_minMipLevel = float( 4.0 );
  27239. const cubeUV_minTileSize = float( 16.0 );
  27240. // These shader functions convert between the UV coordinates of a single face of
  27241. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  27242. // sampling a textureCube (not generally normalized ).
  27243. const getFace = tslFn( ( [ direction ] ) => {
  27244. const absDirection = vec3( abs( direction ) ).toVar();
  27245. const face = float( - 1.0 ).toVar();
  27246. If( absDirection.x.greaterThan( absDirection.z ), () => {
  27247. If( absDirection.x.greaterThan( absDirection.y ), () => {
  27248. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  27249. } ).else( () => {
  27250. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27251. } );
  27252. } ).else( () => {
  27253. If( absDirection.z.greaterThan( absDirection.y ), () => {
  27254. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  27255. } ).else( () => {
  27256. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27257. } );
  27258. } );
  27259. return face;
  27260. } ).setLayout( {
  27261. name: 'getFace',
  27262. type: 'float',
  27263. inputs: [
  27264. { name: 'direction', type: 'vec3' }
  27265. ]
  27266. } );
  27267. // RH coordinate system; PMREM face-indexing convention
  27268. const getUV = tslFn( ( [ direction, face ] ) => {
  27269. const uv = vec2().toVar();
  27270. If( face.equal( 0.0 ), () => {
  27271. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  27272. } ).elseif( face.equal( 1.0 ), () => {
  27273. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  27274. } ).elseif( face.equal( 2.0 ), () => {
  27275. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  27276. } ).elseif( face.equal( 3.0 ), () => {
  27277. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  27278. } ).elseif( face.equal( 4.0 ), () => {
  27279. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  27280. } ).else( () => {
  27281. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  27282. } );
  27283. return mul( 0.5, uv.add( 1.0 ) );
  27284. } ).setLayout( {
  27285. name: 'getUV',
  27286. type: 'vec2',
  27287. inputs: [
  27288. { name: 'direction', type: 'vec3' },
  27289. { name: 'face', type: 'float' }
  27290. ]
  27291. } );
  27292. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  27293. const mip = float( 0.0 ).toVar();
  27294. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  27295. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  27296. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  27297. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  27298. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  27299. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  27300. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  27301. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  27302. } ).else( () => {
  27303. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  27304. } );
  27305. return mip;
  27306. } ).setLayout( {
  27307. name: 'roughnessToMip',
  27308. type: 'float',
  27309. inputs: [
  27310. { name: 'roughness', type: 'float' }
  27311. ]
  27312. } );
  27313. // RH coordinate system; PMREM face-indexing convention
  27314. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  27315. const uv = uv_immutable.toVar();
  27316. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  27317. const direction = vec3( uv, 1.0 ).toVar();
  27318. If( face.equal( 0.0 ), () => {
  27319. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  27320. } ).elseif( face.equal( 1.0 ), () => {
  27321. direction.assign( direction.xzy );
  27322. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  27323. } ).elseif( face.equal( 2.0 ), () => {
  27324. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  27325. } ).elseif( face.equal( 3.0 ), () => {
  27326. direction.assign( direction.zyx );
  27327. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  27328. } ).elseif( face.equal( 4.0 ), () => {
  27329. direction.assign( direction.xzy );
  27330. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  27331. } ).elseif( face.equal( 5.0 ), () => {
  27332. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  27333. } );
  27334. return direction;
  27335. } ).setLayout( {
  27336. name: 'getDirection',
  27337. type: 'vec3',
  27338. inputs: [
  27339. { name: 'uv', type: 'vec2' },
  27340. { name: 'face', type: 'float' }
  27341. ]
  27342. } );
  27343. //
  27344. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27345. const roughness = float( roughness_immutable );
  27346. const sampleDir = vec3( sampleDir_immutable );
  27347. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  27348. const mipF = fract( mip );
  27349. const mipInt = floor( mip );
  27350. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27351. If( mipF.notEqual( 0.0 ), () => {
  27352. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27353. color0.assign( mix( color0, color1, mipF ) );
  27354. } );
  27355. return color0;
  27356. } );
  27357. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27358. const mipInt = float( mipInt_immutable ).toVar();
  27359. const direction = vec3( direction_immutable );
  27360. const face = float( getFace( direction ) ).toVar();
  27361. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  27362. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  27363. const faceSize = float( exp2( mipInt ) ).toVar();
  27364. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  27365. If( face.greaterThan( 2.0 ), () => {
  27366. uv.y.addAssign( faceSize );
  27367. face.subAssign( 3.0 );
  27368. } );
  27369. uv.x.addAssign( face.mul( faceSize ) );
  27370. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  27371. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  27372. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  27373. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  27374. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  27375. } );
  27376. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27377. const cosTheta = cos( theta );
  27378. // Rodrigues' axis-angle rotation
  27379. const sampleDirection = outputDirection.mul( cosTheta )
  27380. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  27381. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  27382. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  27383. } );
  27384. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27385. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  27386. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  27387. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  27388. } );
  27389. axis.assign( normalize( axis ) );
  27390. const gl_FragColor = vec3().toVar();
  27391. 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 } ) ) );
  27392. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  27393. If( i.greaterThanEqual( samples ), () => {
  27394. Break();
  27395. } );
  27396. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  27397. 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 } ) ) );
  27398. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27399. } );
  27400. return vec4( gl_FragColor, 1 );
  27401. } );
  27402. const LOD_MIN = 4;
  27403. // The standard deviations (radians) associated with the extra mips. These are
  27404. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27405. // geometric shadowing function. These sigma values squared must match the
  27406. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27407. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27408. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27409. // samples and exit early, but not recompile the shader.
  27410. const MAX_SAMPLES = 20;
  27411. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27412. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27413. const _clearColor$2 = /*@__PURE__*/ new Color();
  27414. let _oldTarget = null;
  27415. let _oldActiveCubeFace = 0;
  27416. let _oldActiveMipmapLevel = 0;
  27417. // Golden Ratio
  27418. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27419. const INV_PHI = 1 / PHI;
  27420. // Vertices of a dodecahedron (except the opposites, which represent the
  27421. // same axis), used as axis directions evenly spread on a sphere.
  27422. const _axisDirections = [
  27423. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27424. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27425. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27426. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27427. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27428. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27429. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27430. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27431. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27432. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27433. ];
  27434. //
  27435. // WebGPU Face indices
  27436. const _faceLib = [
  27437. 3, 1, 5,
  27438. 0, 4, 2
  27439. ];
  27440. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27441. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27442. /**
  27443. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27444. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27445. * blur to be quickly accessed based on material roughness. It is packed into a
  27446. * special CubeUV format that allows us to perform custom interpolation so that
  27447. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27448. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27449. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27450. * higher roughness levels. In this way we maintain resolution to smoothly
  27451. * interpolate diffuse lighting while limiting sampling computation.
  27452. *
  27453. * Paper: Fast, Accurate Image-Based Lighting
  27454. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27455. */
  27456. class PMREMGenerator {
  27457. constructor( renderer ) {
  27458. this._renderer = renderer;
  27459. this._pingPongRenderTarget = null;
  27460. this._lodMax = 0;
  27461. this._cubeSize = 0;
  27462. this._lodPlanes = [];
  27463. this._sizeLods = [];
  27464. this._sigmas = [];
  27465. this._lodMeshes = [];
  27466. this._blurMaterial = null;
  27467. this._cubemapMaterial = null;
  27468. this._equirectMaterial = null;
  27469. this._backgroundBox = null;
  27470. }
  27471. /**
  27472. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27473. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27474. * in radians to be applied to the scene before PMREM generation. Optional near
  27475. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27476. * is placed at the origin).
  27477. */
  27478. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27479. _oldTarget = this._renderer.getRenderTarget();
  27480. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27481. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27482. this._setSize( 256 );
  27483. const cubeUVRenderTarget = this._allocateTargets();
  27484. cubeUVRenderTarget.depthBuffer = true;
  27485. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27486. if ( sigma > 0 ) {
  27487. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27488. }
  27489. this._applyPMREM( cubeUVRenderTarget );
  27490. this._cleanup( cubeUVRenderTarget );
  27491. return cubeUVRenderTarget;
  27492. }
  27493. /**
  27494. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27495. * or HDR. The ideal input image size is 1k (1024 x 512),
  27496. * as this matches best with the 256 x 256 cubemap output.
  27497. */
  27498. fromEquirectangular( equirectangular, renderTarget = null ) {
  27499. return this._fromTexture( equirectangular, renderTarget );
  27500. }
  27501. /**
  27502. * Generates a PMREM from an cubemap texture, which can be either LDR
  27503. * or HDR. The ideal input cube size is 256 x 256,
  27504. * as this matches best with the 256 x 256 cubemap output.
  27505. */
  27506. fromCubemap( cubemap, renderTarget = null ) {
  27507. return this._fromTexture( cubemap, renderTarget );
  27508. }
  27509. /**
  27510. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27511. * your texture's network fetch for increased concurrency.
  27512. */
  27513. compileCubemapShader() {
  27514. if ( this._cubemapMaterial === null ) {
  27515. this._cubemapMaterial = _getCubemapMaterial();
  27516. this._compileMaterial( this._cubemapMaterial );
  27517. }
  27518. }
  27519. /**
  27520. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27521. * your texture's network fetch for increased concurrency.
  27522. */
  27523. compileEquirectangularShader() {
  27524. if ( this._equirectMaterial === null ) {
  27525. this._equirectMaterial = _getEquirectMaterial();
  27526. this._compileMaterial( this._equirectMaterial );
  27527. }
  27528. }
  27529. /**
  27530. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27531. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27532. * one of them will cause any others to also become unusable.
  27533. */
  27534. dispose() {
  27535. this._dispose();
  27536. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27537. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27538. if ( this._backgroundBox !== null ) {
  27539. this._backgroundBox.geometry.dispose();
  27540. this._backgroundBox.material.dispose();
  27541. }
  27542. }
  27543. // private interface
  27544. _setSize( cubeSize ) {
  27545. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27546. this._cubeSize = Math.pow( 2, this._lodMax );
  27547. }
  27548. _dispose() {
  27549. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27550. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27551. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27552. this._lodPlanes[ i ].dispose();
  27553. }
  27554. }
  27555. _cleanup( outputTarget ) {
  27556. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27557. outputTarget.scissorTest = false;
  27558. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27559. }
  27560. _fromTexture( texture, renderTarget ) {
  27561. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27562. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27563. } else { // Equirectangular
  27564. this._setSize( texture.image.width / 4 );
  27565. }
  27566. _oldTarget = this._renderer.getRenderTarget();
  27567. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27568. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27569. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27570. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27571. this._applyPMREM( cubeUVRenderTarget );
  27572. this._cleanup( cubeUVRenderTarget );
  27573. return cubeUVRenderTarget;
  27574. }
  27575. _allocateTargets() {
  27576. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27577. const height = 4 * this._cubeSize;
  27578. const params = {
  27579. magFilter: LinearFilter,
  27580. minFilter: LinearFilter,
  27581. generateMipmaps: false,
  27582. type: HalfFloatType,
  27583. format: RGBAFormat,
  27584. colorSpace: LinearSRGBColorSpace,
  27585. //depthBuffer: false
  27586. };
  27587. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27588. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27589. if ( this._pingPongRenderTarget !== null ) {
  27590. this._dispose();
  27591. }
  27592. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27593. const { _lodMax } = this;
  27594. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27595. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27596. }
  27597. return cubeUVRenderTarget;
  27598. }
  27599. _compileMaterial( material ) {
  27600. const tmpMesh = this._lodMeshes[ 0 ];
  27601. tmpMesh.material = material;
  27602. this._renderer.compile( tmpMesh, _flatCamera );
  27603. }
  27604. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27605. const cubeCamera = _cubeCamera;
  27606. cubeCamera.near = near;
  27607. cubeCamera.far = far;
  27608. // px, py, pz, nx, ny, nz
  27609. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27610. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27611. const renderer = this._renderer;
  27612. const originalAutoClear = renderer.autoClear;
  27613. renderer.getClearColor( _clearColor$2 );
  27614. renderer.autoClear = false;
  27615. let backgroundBox = this._backgroundBox;
  27616. if ( backgroundBox === null ) {
  27617. const backgroundMaterial = new MeshBasicMaterial( {
  27618. name: 'PMREM.Background',
  27619. side: BackSide,
  27620. depthWrite: false,
  27621. depthTest: false
  27622. } );
  27623. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27624. }
  27625. let useSolidColor = false;
  27626. const background = scene.background;
  27627. if ( background ) {
  27628. if ( background.isColor ) {
  27629. backgroundBox.material.color.copy( background );
  27630. scene.background = null;
  27631. useSolidColor = true;
  27632. }
  27633. } else {
  27634. backgroundBox.material.color.copy( _clearColor$2 );
  27635. useSolidColor = true;
  27636. }
  27637. renderer.setRenderTarget( cubeUVRenderTarget );
  27638. renderer.clear();
  27639. if ( useSolidColor ) {
  27640. renderer.render( backgroundBox, cubeCamera );
  27641. }
  27642. for ( let i = 0; i < 6; i ++ ) {
  27643. const col = i % 3;
  27644. if ( col === 0 ) {
  27645. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27646. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27647. } else if ( col === 1 ) {
  27648. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27649. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27650. } else {
  27651. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27652. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27653. }
  27654. const size = this._cubeSize;
  27655. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27656. renderer.render( scene, cubeCamera );
  27657. }
  27658. renderer.autoClear = originalAutoClear;
  27659. scene.background = background;
  27660. }
  27661. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27662. const renderer = this._renderer;
  27663. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27664. if ( isCubeTexture ) {
  27665. if ( this._cubemapMaterial === null ) {
  27666. this._cubemapMaterial = _getCubemapMaterial( texture );
  27667. }
  27668. } else {
  27669. if ( this._equirectMaterial === null ) {
  27670. this._equirectMaterial = _getEquirectMaterial( texture );
  27671. }
  27672. }
  27673. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27674. material.fragmentNode.value = texture;
  27675. const mesh = this._lodMeshes[ 0 ];
  27676. mesh.material = material;
  27677. const size = this._cubeSize;
  27678. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27679. renderer.setRenderTarget( cubeUVRenderTarget );
  27680. renderer.render( mesh, _flatCamera );
  27681. }
  27682. _applyPMREM( cubeUVRenderTarget ) {
  27683. const renderer = this._renderer;
  27684. const autoClear = renderer.autoClear;
  27685. renderer.autoClear = false;
  27686. const n = this._lodPlanes.length;
  27687. for ( let i = 1; i < n; i ++ ) {
  27688. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27689. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27690. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27691. }
  27692. renderer.autoClear = autoClear;
  27693. }
  27694. /**
  27695. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27696. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27697. * the blur latitudinally (around the poles), and then longitudinally (towards
  27698. * the poles) to approximate the orthogonally-separable blur. It is least
  27699. * accurate at the poles, but still does a decent job.
  27700. */
  27701. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27702. const pingPongRenderTarget = this._pingPongRenderTarget;
  27703. this._halfBlur(
  27704. cubeUVRenderTarget,
  27705. pingPongRenderTarget,
  27706. lodIn,
  27707. lodOut,
  27708. sigma,
  27709. 'latitudinal',
  27710. poleAxis );
  27711. this._halfBlur(
  27712. pingPongRenderTarget,
  27713. cubeUVRenderTarget,
  27714. lodOut,
  27715. lodOut,
  27716. sigma,
  27717. 'longitudinal',
  27718. poleAxis );
  27719. }
  27720. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27721. const renderer = this._renderer;
  27722. const blurMaterial = this._blurMaterial;
  27723. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27724. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27725. }
  27726. // Number of standard deviations at which to cut off the discrete approximation.
  27727. const STANDARD_DEVIATIONS = 3;
  27728. const blurMesh = this._lodMeshes[ lodOut ];
  27729. blurMesh.material = blurMaterial;
  27730. const blurUniforms = blurMaterial.uniforms;
  27731. const pixels = this._sizeLods[ lodIn ] - 1;
  27732. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27733. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27734. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27735. if ( samples > MAX_SAMPLES ) {
  27736. console.warn( `sigmaRadians, ${
  27737. sigmaRadians}, is too large and will clip, as it requested ${
  27738. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27739. }
  27740. const weights = [];
  27741. let sum = 0;
  27742. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27743. const x = i / sigmaPixels;
  27744. const weight = Math.exp( - x * x / 2 );
  27745. weights.push( weight );
  27746. if ( i === 0 ) {
  27747. sum += weight;
  27748. } else if ( i < samples ) {
  27749. sum += 2 * weight;
  27750. }
  27751. }
  27752. for ( let i = 0; i < weights.length; i ++ ) {
  27753. weights[ i ] = weights[ i ] / sum;
  27754. }
  27755. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27756. blurUniforms.envMap.value = targetIn.texture;
  27757. blurUniforms.samples.value = samples;
  27758. blurUniforms.weights.array = weights;
  27759. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27760. if ( poleAxis ) {
  27761. blurUniforms.poleAxis.value = poleAxis;
  27762. }
  27763. const { _lodMax } = this;
  27764. blurUniforms.dTheta.value = radiansPerPixel;
  27765. blurUniforms.mipInt.value = _lodMax - lodIn;
  27766. const outputSize = this._sizeLods[ lodOut ];
  27767. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27768. const y = 4 * ( this._cubeSize - outputSize );
  27769. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27770. renderer.setRenderTarget( targetOut );
  27771. renderer.render( blurMesh, _flatCamera );
  27772. }
  27773. }
  27774. function _createPlanes( lodMax ) {
  27775. const lodPlanes = [];
  27776. const sizeLods = [];
  27777. const sigmas = [];
  27778. const lodMeshes = [];
  27779. let lod = lodMax;
  27780. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27781. for ( let i = 0; i < totalLods; i ++ ) {
  27782. const sizeLod = Math.pow( 2, lod );
  27783. sizeLods.push( sizeLod );
  27784. let sigma = 1.0 / sizeLod;
  27785. if ( i > lodMax - LOD_MIN ) {
  27786. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27787. } else if ( i === 0 ) {
  27788. sigma = 0;
  27789. }
  27790. sigmas.push( sigma );
  27791. const texelSize = 1.0 / ( sizeLod - 2 );
  27792. const min = - texelSize;
  27793. const max = 1 + texelSize;
  27794. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27795. const cubeFaces = 6;
  27796. const vertices = 6;
  27797. const positionSize = 3;
  27798. const uvSize = 2;
  27799. const faceIndexSize = 1;
  27800. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27801. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27802. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27803. for ( let face = 0; face < cubeFaces; face ++ ) {
  27804. const x = ( face % 3 ) * 2 / 3 - 1;
  27805. const y = face > 2 ? 0 : - 1;
  27806. const coordinates = [
  27807. x, y, 0,
  27808. x + 2 / 3, y, 0,
  27809. x + 2 / 3, y + 1, 0,
  27810. x, y, 0,
  27811. x + 2 / 3, y + 1, 0,
  27812. x, y + 1, 0
  27813. ];
  27814. const faceIdx = _faceLib[ face ];
  27815. position.set( coordinates, positionSize * vertices * faceIdx );
  27816. uv.set( uv1, uvSize * vertices * faceIdx );
  27817. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27818. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27819. }
  27820. const planes = new BufferGeometry();
  27821. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27822. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27823. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27824. lodPlanes.push( planes );
  27825. lodMeshes.push( new Mesh( planes, null ) );
  27826. if ( lod > LOD_MIN ) {
  27827. lod --;
  27828. }
  27829. }
  27830. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27831. }
  27832. function _createRenderTarget( width, height, params ) {
  27833. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27834. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27835. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27836. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27837. cubeUVRenderTarget.scissorTest = true;
  27838. return cubeUVRenderTarget;
  27839. }
  27840. function _setViewport( target, x, y, width, height ) {
  27841. const viewY = target.height - height - y;
  27842. target.viewport.set( x, viewY, width, height );
  27843. target.scissor.set( x, viewY, width, height );
  27844. }
  27845. function _getMaterial() {
  27846. const material = new NodeMaterial();
  27847. material.depthTest = false;
  27848. material.depthWrite = false;
  27849. material.blending = NoBlending;
  27850. return material;
  27851. }
  27852. function _getBlurShader( lodMax, width, height ) {
  27853. const weights = uniforms( new Array( MAX_SAMPLES ).fill( 0 ) );
  27854. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27855. const dTheta = uniform( 0 );
  27856. const n = float( MAX_SAMPLES );
  27857. const latitudinal = uniform( 0 ); // false, bool
  27858. const samples = uniform( 1 ); // int
  27859. const envMap = texture( null );
  27860. const mipInt = uniform( 0 ); // int
  27861. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27862. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27863. const CUBEUV_MAX_MIP = float( lodMax );
  27864. const materialUniforms = {
  27865. n,
  27866. latitudinal,
  27867. weights,
  27868. poleAxis,
  27869. outputDirection,
  27870. dTheta,
  27871. samples,
  27872. envMap,
  27873. mipInt,
  27874. CUBEUV_TEXEL_WIDTH,
  27875. CUBEUV_TEXEL_HEIGHT,
  27876. CUBEUV_MAX_MIP
  27877. };
  27878. const material = _getMaterial();
  27879. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27880. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27881. return material;
  27882. }
  27883. function _getCubemapMaterial( envTexture ) {
  27884. const material = _getMaterial();
  27885. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27886. return material;
  27887. }
  27888. function _getEquirectMaterial( envTexture ) {
  27889. const material = _getMaterial();
  27890. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27891. return material;
  27892. }
  27893. let _id$5 = 0;
  27894. class BindGroup {
  27895. constructor( name = '', bindings = [] ) {
  27896. this.name = name;
  27897. this.bindings = bindings;
  27898. this.id = _id$5 ++;
  27899. }
  27900. }
  27901. const rendererCache = new WeakMap();
  27902. const typeFromLength = new Map( [
  27903. [ 2, 'vec2' ],
  27904. [ 3, 'vec3' ],
  27905. [ 4, 'vec4' ],
  27906. [ 9, 'mat3' ],
  27907. [ 16, 'mat4' ]
  27908. ] );
  27909. const typeFromArray = new Map( [
  27910. [ Int8Array, 'int' ],
  27911. [ Int16Array, 'int' ],
  27912. [ Int32Array, 'int' ],
  27913. [ Uint8Array, 'uint' ],
  27914. [ Uint16Array, 'uint' ],
  27915. [ Uint32Array, 'uint' ],
  27916. [ Float32Array, 'float' ]
  27917. ] );
  27918. const toFloat = ( value ) => {
  27919. value = Number( value );
  27920. return value + ( value % 1 ? '' : '.0' );
  27921. };
  27922. class NodeBuilder {
  27923. constructor( object, renderer, parser ) {
  27924. this.object = object;
  27925. this.material = ( object && object.material ) || null;
  27926. this.geometry = ( object && object.geometry ) || null;
  27927. this.renderer = renderer;
  27928. this.parser = parser;
  27929. this.scene = null;
  27930. this.camera = null;
  27931. this.nodes = [];
  27932. this.updateNodes = [];
  27933. this.updateBeforeNodes = [];
  27934. this.updateAfterNodes = [];
  27935. this.hashNodes = {};
  27936. this.lightsNode = null;
  27937. this.environmentNode = null;
  27938. this.fogNode = null;
  27939. this.clippingContext = null;
  27940. this.vertexShader = null;
  27941. this.fragmentShader = null;
  27942. this.computeShader = null;
  27943. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  27944. this.flowCode = { vertex: '', fragment: '', compute: '' };
  27945. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  27946. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  27947. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  27948. this.bindingsIndexes = {};
  27949. this.bindGroups = null;
  27950. this.attributes = [];
  27951. this.bufferAttributes = [];
  27952. this.varyings = [];
  27953. this.codes = {};
  27954. this.vars = {};
  27955. this.flow = { code: '' };
  27956. this.chaining = [];
  27957. this.stack = stack();
  27958. this.stacks = [];
  27959. this.tab = '\t';
  27960. this.instanceBindGroups = true;
  27961. this.currentFunctionNode = null;
  27962. this.context = {
  27963. keywords: new NodeKeywords(),
  27964. material: this.material
  27965. };
  27966. this.cache = new NodeCache();
  27967. this.globalCache = this.cache;
  27968. this.flowsData = new WeakMap();
  27969. this.shaderStage = null;
  27970. this.buildStage = null;
  27971. }
  27972. getBingGroupsCache() {
  27973. let bindGroupsCache = rendererCache.get( this.renderer );
  27974. if ( bindGroupsCache === undefined ) {
  27975. bindGroupsCache = new ChainMap();
  27976. rendererCache.set( this.renderer, bindGroupsCache );
  27977. }
  27978. return bindGroupsCache;
  27979. }
  27980. createRenderTarget( width, height, options ) {
  27981. return new RenderTarget( width, height, options );
  27982. }
  27983. createCubeRenderTarget( size, options ) {
  27984. return new CubeRenderTarget( size, options );
  27985. }
  27986. createPMREMGenerator() {
  27987. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  27988. return new PMREMGenerator( this.renderer );
  27989. }
  27990. includes( node ) {
  27991. return this.nodes.includes( node );
  27992. }
  27993. _getBindGroup( groupName, bindings ) {
  27994. const bindGroupsCache = this.getBingGroupsCache();
  27995. //
  27996. const bindingsArray = [];
  27997. let sharedGroup = true;
  27998. for ( const binding of bindings ) {
  27999. bindingsArray.push( binding );
  28000. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  28001. }
  28002. //
  28003. let bindGroup;
  28004. if ( sharedGroup ) {
  28005. bindGroup = bindGroupsCache.get( bindingsArray );
  28006. if ( bindGroup === undefined ) {
  28007. bindGroup = new BindGroup( groupName, bindingsArray );
  28008. bindGroupsCache.set( bindingsArray, bindGroup );
  28009. }
  28010. } else {
  28011. bindGroup = new BindGroup( groupName, bindingsArray );
  28012. }
  28013. return bindGroup;
  28014. }
  28015. getBindGroupArray( groupName, shaderStage ) {
  28016. const bindings = this.bindings[ shaderStage ];
  28017. let bindGroup = bindings[ groupName ];
  28018. if ( bindGroup === undefined ) {
  28019. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  28020. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  28021. }
  28022. bindings[ groupName ] = bindGroup = [];
  28023. }
  28024. return bindGroup;
  28025. }
  28026. getBindings() {
  28027. let bindingsGroups = this.bindGroups;
  28028. if ( bindingsGroups === null ) {
  28029. const groups = {};
  28030. const bindings = this.bindings;
  28031. for ( const shaderStage of shaderStages ) {
  28032. for ( const groupName in bindings[ shaderStage ] ) {
  28033. const uniforms = bindings[ shaderStage ][ groupName ];
  28034. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  28035. groupUniforms.push( ...uniforms );
  28036. }
  28037. }
  28038. bindingsGroups = [];
  28039. for ( const groupName in groups ) {
  28040. const group = groups[ groupName ];
  28041. const bindingsGroup = this._getBindGroup( groupName, group );
  28042. bindingsGroups.push( bindingsGroup );
  28043. }
  28044. this.bindGroups = bindingsGroups;
  28045. }
  28046. return bindingsGroups;
  28047. }
  28048. setHashNode( node, hash ) {
  28049. this.hashNodes[ hash ] = node;
  28050. }
  28051. addNode( node ) {
  28052. if ( this.nodes.includes( node ) === false ) {
  28053. this.nodes.push( node );
  28054. this.setHashNode( node, node.getHash( this ) );
  28055. }
  28056. }
  28057. buildUpdateNodes() {
  28058. for ( const node of this.nodes ) {
  28059. const updateType = node.getUpdateType();
  28060. const updateBeforeType = node.getUpdateBeforeType();
  28061. const updateAfterType = node.getUpdateAfterType();
  28062. if ( updateType !== NodeUpdateType.NONE ) {
  28063. this.updateNodes.push( node.getSelf() );
  28064. }
  28065. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  28066. this.updateBeforeNodes.push( node );
  28067. }
  28068. if ( updateAfterType !== NodeUpdateType.NONE ) {
  28069. this.updateAfterNodes.push( node );
  28070. }
  28071. }
  28072. }
  28073. get currentNode() {
  28074. return this.chaining[ this.chaining.length - 1 ];
  28075. }
  28076. isFilteredTexture( texture ) {
  28077. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28078. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  28079. }
  28080. addChain( node ) {
  28081. /*
  28082. if ( this.chaining.indexOf( node ) !== - 1 ) {
  28083. console.warn( 'Recursive node: ', node );
  28084. }
  28085. */
  28086. this.chaining.push( node );
  28087. }
  28088. removeChain( node ) {
  28089. const lastChain = this.chaining.pop();
  28090. if ( lastChain !== node ) {
  28091. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  28092. }
  28093. }
  28094. getMethod( method ) {
  28095. return method;
  28096. }
  28097. getNodeFromHash( hash ) {
  28098. return this.hashNodes[ hash ];
  28099. }
  28100. addFlow( shaderStage, node ) {
  28101. this.flowNodes[ shaderStage ].push( node );
  28102. return node;
  28103. }
  28104. setContext( context ) {
  28105. this.context = context;
  28106. }
  28107. getContext() {
  28108. return this.context;
  28109. }
  28110. getSharedContext() {
  28111. ({ ...this.context });
  28112. return this.context;
  28113. }
  28114. setCache( cache ) {
  28115. this.cache = cache;
  28116. }
  28117. getCache() {
  28118. return this.cache;
  28119. }
  28120. getCacheFromNode( node, parent = true ) {
  28121. const data = this.getDataFromNode( node );
  28122. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28123. return data.cache;
  28124. }
  28125. isAvailable( /*name*/ ) {
  28126. return false;
  28127. }
  28128. getVertexIndex() {
  28129. console.warn( 'Abstract function.' );
  28130. }
  28131. getInstanceIndex() {
  28132. console.warn( 'Abstract function.' );
  28133. }
  28134. getDrawIndex() {
  28135. console.warn( 'Abstract function.' );
  28136. }
  28137. getFrontFacing() {
  28138. console.warn( 'Abstract function.' );
  28139. }
  28140. getFragCoord() {
  28141. console.warn( 'Abstract function.' );
  28142. }
  28143. isFlipY() {
  28144. return false;
  28145. }
  28146. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28147. console.warn( 'Abstract function.' );
  28148. }
  28149. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28150. console.warn( 'Abstract function.' );
  28151. }
  28152. generateConst( type, value = null ) {
  28153. if ( value === null ) {
  28154. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28155. else if ( type === 'bool' ) value = false;
  28156. else if ( type === 'color' ) value = new Color();
  28157. else if ( type === 'vec2' ) value = new Vector2();
  28158. else if ( type === 'vec3' ) value = new Vector3();
  28159. else if ( type === 'vec4' ) value = new Vector4();
  28160. }
  28161. if ( type === 'float' ) return toFloat( value );
  28162. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28163. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28164. if ( type === 'bool' ) return value ? 'true' : 'false';
  28165. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28166. const typeLength = this.getTypeLength( type );
  28167. const componentType = this.getComponentType( type );
  28168. const generateConst = value => this.generateConst( componentType, value );
  28169. if ( typeLength === 2 ) {
  28170. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28171. } else if ( typeLength === 3 ) {
  28172. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28173. } else if ( typeLength === 4 ) {
  28174. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28175. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28176. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28177. } else if ( typeLength > 4 ) {
  28178. return `${ this.getType( type ) }()`;
  28179. }
  28180. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28181. }
  28182. getType( type ) {
  28183. if ( type === 'color' ) return 'vec3';
  28184. return type;
  28185. }
  28186. hasGeometryAttribute( name ) {
  28187. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28188. }
  28189. getAttribute( name, type ) {
  28190. const attributes = this.attributes;
  28191. // find attribute
  28192. for ( const attribute of attributes ) {
  28193. if ( attribute.name === name ) {
  28194. return attribute;
  28195. }
  28196. }
  28197. // create a new if no exist
  28198. const attribute = new NodeAttribute( name, type );
  28199. attributes.push( attribute );
  28200. return attribute;
  28201. }
  28202. getPropertyName( node/*, shaderStage*/ ) {
  28203. return node.name;
  28204. }
  28205. isVector( type ) {
  28206. return /vec\d/.test( type );
  28207. }
  28208. isMatrix( type ) {
  28209. return /mat\d/.test( type );
  28210. }
  28211. isReference( type ) {
  28212. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28213. }
  28214. needsColorSpaceToLinear( /*texture*/ ) {
  28215. return false;
  28216. }
  28217. getComponentTypeFromTexture( texture ) {
  28218. const type = texture.type;
  28219. if ( texture.isDataTexture ) {
  28220. if ( type === IntType ) return 'int';
  28221. if ( type === UnsignedIntType ) return 'uint';
  28222. }
  28223. return 'float';
  28224. }
  28225. getElementType( type ) {
  28226. if ( type === 'mat2' ) return 'vec2';
  28227. if ( type === 'mat3' ) return 'vec3';
  28228. if ( type === 'mat4' ) return 'vec4';
  28229. return this.getComponentType( type );
  28230. }
  28231. getComponentType( type ) {
  28232. type = this.getVectorType( type );
  28233. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28234. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28235. if ( componentType === null ) return null;
  28236. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28237. if ( componentType[ 1 ] === 'i' ) return 'int';
  28238. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28239. return 'float';
  28240. }
  28241. getVectorType( type ) {
  28242. if ( type === 'color' ) return 'vec3';
  28243. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28244. return type;
  28245. }
  28246. getTypeFromLength( length, componentType = 'float' ) {
  28247. if ( length === 1 ) return componentType;
  28248. const baseType = typeFromLength.get( length );
  28249. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28250. return prefix + baseType;
  28251. }
  28252. getTypeFromArray( array ) {
  28253. return typeFromArray.get( array.constructor );
  28254. }
  28255. getTypeFromAttribute( attribute ) {
  28256. let dataAttribute = attribute;
  28257. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28258. const array = dataAttribute.array;
  28259. const itemSize = attribute.itemSize;
  28260. const normalized = attribute.normalized;
  28261. let arrayType;
  28262. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28263. arrayType = this.getTypeFromArray( array );
  28264. }
  28265. return this.getTypeFromLength( itemSize, arrayType );
  28266. }
  28267. getTypeLength( type ) {
  28268. const vecType = this.getVectorType( type );
  28269. const vecNum = /vec([2-4])/.exec( vecType );
  28270. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28271. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28272. if ( /mat2/.test( type ) === true ) return 4;
  28273. if ( /mat3/.test( type ) === true ) return 9;
  28274. if ( /mat4/.test( type ) === true ) return 16;
  28275. return 0;
  28276. }
  28277. getVectorFromMatrix( type ) {
  28278. return type.replace( 'mat', 'vec' );
  28279. }
  28280. changeComponentType( type, newComponentType ) {
  28281. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28282. }
  28283. getIntegerType( type ) {
  28284. const componentType = this.getComponentType( type );
  28285. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28286. return this.changeComponentType( type, 'int' );
  28287. }
  28288. addStack() {
  28289. this.stack = stack( this.stack );
  28290. this.stacks.push( getCurrentStack() || this.stack );
  28291. setCurrentStack( this.stack );
  28292. return this.stack;
  28293. }
  28294. removeStack() {
  28295. const lastStack = this.stack;
  28296. this.stack = lastStack.parent;
  28297. setCurrentStack( this.stacks.pop() );
  28298. return lastStack;
  28299. }
  28300. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28301. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28302. let nodeData = cache.getData( node );
  28303. if ( nodeData === undefined ) {
  28304. nodeData = {};
  28305. cache.setData( node, nodeData );
  28306. }
  28307. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28308. return nodeData[ shaderStage ];
  28309. }
  28310. getNodeProperties( node, shaderStage = 'any' ) {
  28311. const nodeData = this.getDataFromNode( node, shaderStage );
  28312. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28313. }
  28314. getBufferAttributeFromNode( node, type ) {
  28315. const nodeData = this.getDataFromNode( node );
  28316. let bufferAttribute = nodeData.bufferAttribute;
  28317. if ( bufferAttribute === undefined ) {
  28318. const index = this.uniforms.index ++;
  28319. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28320. this.bufferAttributes.push( bufferAttribute );
  28321. nodeData.bufferAttribute = bufferAttribute;
  28322. }
  28323. return bufferAttribute;
  28324. }
  28325. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28326. const nodeData = this.getDataFromNode( node, shaderStage );
  28327. if ( nodeData.structType === undefined ) {
  28328. const index = this.structs.index ++;
  28329. node.name = `StructType${ index }`;
  28330. this.structs[ shaderStage ].push( node );
  28331. nodeData.structType = node;
  28332. }
  28333. return node;
  28334. }
  28335. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28336. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28337. let nodeUniform = nodeData.uniform;
  28338. if ( nodeUniform === undefined ) {
  28339. const index = this.uniforms.index ++;
  28340. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28341. this.uniforms[ shaderStage ].push( nodeUniform );
  28342. nodeData.uniform = nodeUniform;
  28343. }
  28344. return nodeUniform;
  28345. }
  28346. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28347. const nodeData = this.getDataFromNode( node, shaderStage );
  28348. let nodeVar = nodeData.variable;
  28349. if ( nodeVar === undefined ) {
  28350. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28351. if ( name === null ) name = 'nodeVar' + vars.length;
  28352. nodeVar = new NodeVar( name, type );
  28353. vars.push( nodeVar );
  28354. nodeData.variable = nodeVar;
  28355. }
  28356. return nodeVar;
  28357. }
  28358. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28359. const nodeData = this.getDataFromNode( node, 'any' );
  28360. let nodeVarying = nodeData.varying;
  28361. if ( nodeVarying === undefined ) {
  28362. const varyings = this.varyings;
  28363. const index = varyings.length;
  28364. if ( name === null ) name = 'nodeVarying' + index;
  28365. nodeVarying = new NodeVarying( name, type );
  28366. varyings.push( nodeVarying );
  28367. nodeData.varying = nodeVarying;
  28368. }
  28369. return nodeVarying;
  28370. }
  28371. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28372. const nodeData = this.getDataFromNode( node );
  28373. let nodeCode = nodeData.code;
  28374. if ( nodeCode === undefined ) {
  28375. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28376. const index = codes.length;
  28377. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28378. codes.push( nodeCode );
  28379. nodeData.code = nodeCode;
  28380. }
  28381. return nodeCode;
  28382. }
  28383. addLineFlowCode( code ) {
  28384. if ( code === '' ) return this;
  28385. code = this.tab + code;
  28386. if ( ! /;\s*$/.test( code ) ) {
  28387. code = code + ';\n';
  28388. }
  28389. this.flow.code += code;
  28390. return this;
  28391. }
  28392. addFlowCode( code ) {
  28393. this.flow.code += code;
  28394. return this;
  28395. }
  28396. addFlowTab() {
  28397. this.tab += '\t';
  28398. return this;
  28399. }
  28400. removeFlowTab() {
  28401. this.tab = this.tab.slice( 0, - 1 );
  28402. return this;
  28403. }
  28404. getFlowData( node/*, shaderStage*/ ) {
  28405. return this.flowsData.get( node );
  28406. }
  28407. flowNode( node ) {
  28408. const output = node.getNodeType( this );
  28409. const flowData = this.flowChildNode( node, output );
  28410. this.flowsData.set( node, flowData );
  28411. return flowData;
  28412. }
  28413. buildFunctionNode( shaderNode ) {
  28414. const fn = new FunctionNode();
  28415. const previous = this.currentFunctionNode;
  28416. this.currentFunctionNode = fn;
  28417. fn.code = this.buildFunctionCode( shaderNode );
  28418. this.currentFunctionNode = previous;
  28419. return fn;
  28420. }
  28421. flowShaderNode( shaderNode ) {
  28422. const layout = shaderNode.layout;
  28423. let inputs;
  28424. if ( shaderNode.isArrayInput ) {
  28425. inputs = [];
  28426. for ( const input of layout.inputs ) {
  28427. inputs.push( new ParameterNode( input.type, input.name ) );
  28428. }
  28429. } else {
  28430. inputs = {};
  28431. for ( const input of layout.inputs ) {
  28432. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28433. }
  28434. }
  28435. //
  28436. shaderNode.layout = null;
  28437. const callNode = shaderNode.call( inputs );
  28438. const flowData = this.flowStagesNode( callNode, layout.type );
  28439. shaderNode.layout = layout;
  28440. return flowData;
  28441. }
  28442. flowStagesNode( node, output = null ) {
  28443. const previousFlow = this.flow;
  28444. const previousVars = this.vars;
  28445. const previousCache = this.cache;
  28446. const previousBuildStage = this.buildStage;
  28447. const previousStack = this.stack;
  28448. const flow = {
  28449. code: ''
  28450. };
  28451. this.flow = flow;
  28452. this.vars = {};
  28453. this.cache = new NodeCache();
  28454. this.stack = stack();
  28455. for ( const buildStage of defaultBuildStages ) {
  28456. this.setBuildStage( buildStage );
  28457. flow.result = node.build( this, output );
  28458. }
  28459. flow.vars = this.getVars( this.shaderStage );
  28460. this.flow = previousFlow;
  28461. this.vars = previousVars;
  28462. this.cache = previousCache;
  28463. this.stack = previousStack;
  28464. this.setBuildStage( previousBuildStage );
  28465. return flow;
  28466. }
  28467. getFunctionOperator() {
  28468. return null;
  28469. }
  28470. flowChildNode( node, output = null ) {
  28471. const previousFlow = this.flow;
  28472. const flow = {
  28473. code: ''
  28474. };
  28475. this.flow = flow;
  28476. flow.result = node.build( this, output );
  28477. this.flow = previousFlow;
  28478. return flow;
  28479. }
  28480. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28481. const previousShaderStage = this.shaderStage;
  28482. this.setShaderStage( shaderStage );
  28483. const flowData = this.flowChildNode( node, output );
  28484. if ( propertyName !== null ) {
  28485. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28486. }
  28487. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28488. this.setShaderStage( previousShaderStage );
  28489. return flowData;
  28490. }
  28491. getAttributesArray() {
  28492. return this.attributes.concat( this.bufferAttributes );
  28493. }
  28494. getAttributes( /*shaderStage*/ ) {
  28495. console.warn( 'Abstract function.' );
  28496. }
  28497. getVaryings( /*shaderStage*/ ) {
  28498. console.warn( 'Abstract function.' );
  28499. }
  28500. getVar( type, name ) {
  28501. return `${ this.getType( type ) } ${ name }`;
  28502. }
  28503. getVars( shaderStage ) {
  28504. let snippet = '';
  28505. const vars = this.vars[ shaderStage ];
  28506. if ( vars !== undefined ) {
  28507. for ( const variable of vars ) {
  28508. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28509. }
  28510. }
  28511. return snippet;
  28512. }
  28513. getUniforms( /*shaderStage*/ ) {
  28514. console.warn( 'Abstract function.' );
  28515. }
  28516. getCodes( shaderStage ) {
  28517. const codes = this.codes[ shaderStage ];
  28518. let code = '';
  28519. if ( codes !== undefined ) {
  28520. for ( const nodeCode of codes ) {
  28521. code += nodeCode.code + '\n';
  28522. }
  28523. }
  28524. return code;
  28525. }
  28526. getHash() {
  28527. return this.vertexShader + this.fragmentShader + this.computeShader;
  28528. }
  28529. setShaderStage( shaderStage ) {
  28530. this.shaderStage = shaderStage;
  28531. }
  28532. getShaderStage() {
  28533. return this.shaderStage;
  28534. }
  28535. setBuildStage( buildStage ) {
  28536. this.buildStage = buildStage;
  28537. }
  28538. getBuildStage() {
  28539. return this.buildStage;
  28540. }
  28541. buildCode() {
  28542. console.warn( 'Abstract function.' );
  28543. }
  28544. build() {
  28545. const { object, material } = this;
  28546. if ( material !== null ) {
  28547. NodeMaterial.fromMaterial( material ).build( this );
  28548. } else {
  28549. this.addFlow( 'compute', object );
  28550. }
  28551. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28552. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28553. // generate() -> stage 3: generate shader
  28554. for ( const buildStage of defaultBuildStages ) {
  28555. this.setBuildStage( buildStage );
  28556. if ( this.context.vertex && this.context.vertex.isNode ) {
  28557. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28558. }
  28559. for ( const shaderStage of shaderStages ) {
  28560. this.setShaderStage( shaderStage );
  28561. const flowNodes = this.flowNodes[ shaderStage ];
  28562. for ( const node of flowNodes ) {
  28563. if ( buildStage === 'generate' ) {
  28564. this.flowNode( node );
  28565. } else {
  28566. node.build( this );
  28567. }
  28568. }
  28569. }
  28570. }
  28571. this.setBuildStage( null );
  28572. this.setShaderStage( null );
  28573. // stage 4: build code for a specific output
  28574. this.buildCode();
  28575. this.buildUpdateNodes();
  28576. return this;
  28577. }
  28578. getNodeUniform( uniformNode, type ) {
  28579. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28580. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28581. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28582. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28583. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28584. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28585. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28586. throw new Error( `Uniform "${type}" not declared.` );
  28587. }
  28588. createNodeMaterial( type = 'NodeMaterial' ) {
  28589. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28590. return createNodeMaterialFromType( type );
  28591. }
  28592. format( snippet, fromType, toType ) {
  28593. fromType = this.getVectorType( fromType );
  28594. toType = this.getVectorType( toType );
  28595. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28596. return snippet;
  28597. }
  28598. const fromTypeLength = this.getTypeLength( fromType );
  28599. const toTypeLength = this.getTypeLength( toType );
  28600. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  28601. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  28602. }
  28603. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  28604. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  28605. }
  28606. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28607. // @TODO: ignore for now
  28608. return snippet;
  28609. }
  28610. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28611. // @TODO: ignore for now
  28612. return snippet;
  28613. }
  28614. if ( fromTypeLength === toTypeLength ) {
  28615. return `${ this.getType( toType ) }( ${ snippet } )`;
  28616. }
  28617. if ( fromTypeLength > toTypeLength ) {
  28618. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28619. }
  28620. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28621. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28622. }
  28623. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28624. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28625. }
  28626. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28627. // convert a number value to vector type, e.g:
  28628. // vec3( 1u ) -> vec3( float( 1u ) )
  28629. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28630. }
  28631. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28632. }
  28633. getSignature() {
  28634. return `// Three.js r${ REVISION } - Node System\n`;
  28635. }
  28636. }
  28637. class NodeFrame {
  28638. constructor() {
  28639. this.time = 0;
  28640. this.deltaTime = 0;
  28641. this.frameId = 0;
  28642. this.renderId = 0;
  28643. this.startTime = null;
  28644. this.updateMap = new WeakMap();
  28645. this.updateBeforeMap = new WeakMap();
  28646. this.updateAfterMap = new WeakMap();
  28647. this.renderer = null;
  28648. this.material = null;
  28649. this.camera = null;
  28650. this.object = null;
  28651. this.scene = null;
  28652. }
  28653. _getMaps( referenceMap, nodeRef ) {
  28654. let maps = referenceMap.get( nodeRef );
  28655. if ( maps === undefined ) {
  28656. maps = {
  28657. renderMap: new WeakMap(),
  28658. frameMap: new WeakMap()
  28659. };
  28660. referenceMap.set( nodeRef, maps );
  28661. }
  28662. return maps;
  28663. }
  28664. updateBeforeNode( node ) {
  28665. const updateType = node.getUpdateBeforeType();
  28666. const reference = node.updateReference( this );
  28667. if ( updateType === NodeUpdateType.FRAME ) {
  28668. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28669. if ( frameMap.get( reference ) !== this.frameId ) {
  28670. if ( node.updateBefore( this ) !== false ) {
  28671. frameMap.set( reference, this.frameId );
  28672. }
  28673. }
  28674. } else if ( updateType === NodeUpdateType.RENDER ) {
  28675. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28676. if ( renderMap.get( reference ) !== this.renderId ) {
  28677. if ( node.updateBefore( this ) !== false ) {
  28678. renderMap.set( reference, this.renderId );
  28679. }
  28680. }
  28681. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28682. node.updateBefore( this );
  28683. }
  28684. }
  28685. updateAfterNode( node ) {
  28686. const updateType = node.getUpdateAfterType();
  28687. const reference = node.updateReference( this );
  28688. if ( updateType === NodeUpdateType.FRAME ) {
  28689. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28690. if ( frameMap.get( reference ) !== this.frameId ) {
  28691. if ( node.updateAfter( this ) !== false ) {
  28692. frameMap.set( reference, this.frameId );
  28693. }
  28694. }
  28695. } else if ( updateType === NodeUpdateType.RENDER ) {
  28696. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28697. if ( renderMap.get( reference ) !== this.renderId ) {
  28698. if ( node.updateAfter( this ) !== false ) {
  28699. renderMap.set( reference, this.renderId );
  28700. }
  28701. }
  28702. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28703. node.updateAfter( this );
  28704. }
  28705. }
  28706. updateNode( node ) {
  28707. const updateType = node.getUpdateType();
  28708. const reference = node.updateReference( this );
  28709. if ( updateType === NodeUpdateType.FRAME ) {
  28710. const { frameMap } = this._getMaps( this.updateMap, reference );
  28711. if ( frameMap.get( reference ) !== this.frameId ) {
  28712. if ( node.update( this ) !== false ) {
  28713. frameMap.set( reference, this.frameId );
  28714. }
  28715. }
  28716. } else if ( updateType === NodeUpdateType.RENDER ) {
  28717. const { renderMap } = this._getMaps( this.updateMap, reference );
  28718. if ( renderMap.get( reference ) !== this.renderId ) {
  28719. if ( node.update( this ) !== false ) {
  28720. renderMap.set( reference, this.renderId );
  28721. }
  28722. }
  28723. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28724. node.update( this );
  28725. }
  28726. }
  28727. update() {
  28728. this.frameId ++;
  28729. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28730. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28731. this.lastTime = performance.now();
  28732. this.time += this.deltaTime;
  28733. }
  28734. }
  28735. class NodeFunctionInput {
  28736. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28737. this.type = type;
  28738. this.name = name;
  28739. this.count = count;
  28740. this.qualifier = qualifier;
  28741. this.isConst = isConst;
  28742. }
  28743. }
  28744. NodeFunctionInput.isNodeFunctionInput = true;
  28745. class StructTypeNode extends Node {
  28746. constructor( types ) {
  28747. super();
  28748. this.types = types;
  28749. this.isStructTypeNode = true;
  28750. }
  28751. getMemberTypes() {
  28752. return this.types;
  28753. }
  28754. }
  28755. addNodeClass( 'StructTypeNode', StructTypeNode );
  28756. class OutputStructNode extends Node {
  28757. constructor( ...members ) {
  28758. super();
  28759. this.members = members;
  28760. this.isOutputStructNode = true;
  28761. }
  28762. setup( builder ) {
  28763. super.setup( builder );
  28764. const members = this.members;
  28765. const types = [];
  28766. for ( let i = 0; i < members.length; i ++ ) {
  28767. types.push( members[ i ].getNodeType( builder ) );
  28768. }
  28769. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28770. }
  28771. generate( builder, output ) {
  28772. const propertyName = builder.getOutputStructName();
  28773. const members = this.members;
  28774. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28775. for ( let i = 0; i < members.length; i ++ ) {
  28776. const snippet = members[ i ].build( builder, output );
  28777. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28778. }
  28779. return propertyName;
  28780. }
  28781. }
  28782. const outputStruct = nodeProxy( OutputStructNode );
  28783. addNodeClass( 'OutputStructNode', OutputStructNode );
  28784. function getTextureIndex( textures, name ) {
  28785. for ( let i = 0; i < textures.length; i ++ ) {
  28786. if ( textures[ i ].name === name ) {
  28787. return i;
  28788. }
  28789. }
  28790. return - 1;
  28791. }
  28792. class MRTNode extends OutputStructNode {
  28793. constructor( outputNodes ) {
  28794. super();
  28795. this.outputNodes = outputNodes;
  28796. this.isMRTNode = true;
  28797. }
  28798. getNode( name ) {
  28799. return this.outputNodes[ name ];
  28800. }
  28801. merge( mrtNode ) {
  28802. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  28803. return mrt( outputs );
  28804. }
  28805. setup( builder ) {
  28806. const outputNodes = this.outputNodes;
  28807. const mrt = builder.renderer.getRenderTarget();
  28808. const members = [];
  28809. const textures = mrt.textures;
  28810. for ( const name in outputNodes ) {
  28811. const index = getTextureIndex( textures, name );
  28812. members[ index ] = vec4( outputNodes[ name ] );
  28813. }
  28814. this.members = members;
  28815. return super.setup( builder );
  28816. }
  28817. }
  28818. const mrt = nodeProxy( MRTNode );
  28819. addNodeClass( 'MRTNode', MRTNode );
  28820. class HashNode extends Node {
  28821. constructor( seedNode ) {
  28822. super();
  28823. this.seedNode = seedNode;
  28824. }
  28825. setup( /*builder*/ ) {
  28826. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28827. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28828. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28829. const result = word.shiftRight( 22 ).bitXor( word );
  28830. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28831. }
  28832. }
  28833. const hash = nodeProxy( HashNode );
  28834. addNodeElement( 'hash', hash );
  28835. addNodeClass( 'HashNode', HashNode );
  28836. // remapping functions https://iquilezles.org/articles/functions/
  28837. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28838. 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 ) );
  28839. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28840. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28841. addNodeElement( 'parabola', parabola );
  28842. addNodeElement( 'gain', gain );
  28843. addNodeElement( 'pcurve', pcurve );
  28844. addNodeElement( 'sinc', sinc );
  28845. // https://github.com/cabbibo/glsl-tri-noise-3d
  28846. const tri = tslFn( ( [ x ] ) => {
  28847. return x.fract().sub( .5 ).abs();
  28848. } );
  28849. const tri3 = tslFn( ( [ p ] ) => {
  28850. 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. ) ) ) ) );
  28851. } );
  28852. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28853. const p = vec3( p_immutable ).toVar();
  28854. const z = float( 1.4 ).toVar();
  28855. const rz = float( 0.0 ).toVar();
  28856. const bp = vec3( p ).toVar();
  28857. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28858. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28859. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28860. bp.mulAssign( 1.8 );
  28861. z.mulAssign( 1.5 );
  28862. p.mulAssign( 1.2 );
  28863. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28864. rz.addAssign( t.div( z ) );
  28865. bp.addAssign( 0.14 );
  28866. } );
  28867. return rz;
  28868. } );
  28869. // layouts
  28870. tri.setLayout( {
  28871. name: 'tri',
  28872. type: 'float',
  28873. inputs: [
  28874. { name: 'x', type: 'float' }
  28875. ]
  28876. } );
  28877. tri3.setLayout( {
  28878. name: 'tri3',
  28879. type: 'vec3',
  28880. inputs: [
  28881. { name: 'p', type: 'vec3' }
  28882. ]
  28883. } );
  28884. triNoise3D.setLayout( {
  28885. name: 'triNoise3D',
  28886. type: 'float',
  28887. inputs: [
  28888. { name: 'p', type: 'vec3' },
  28889. { name: 'spd', type: 'float' },
  28890. { name: 'time', type: 'float' }
  28891. ]
  28892. } );
  28893. let discardExpression;
  28894. class DiscardNode extends CondNode {
  28895. constructor( condNode ) {
  28896. discardExpression = discardExpression || expression( 'discard' );
  28897. super( condNode, discardExpression );
  28898. }
  28899. }
  28900. const inlineDiscard = nodeProxy( DiscardNode );
  28901. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28902. const Return = () => expression( 'return' ).append();
  28903. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28904. addNodeClass( 'DiscardNode', DiscardNode );
  28905. class FunctionOverloadingNode extends Node {
  28906. constructor( functionNodes = [], ...parametersNodes ) {
  28907. super();
  28908. this.functionNodes = functionNodes;
  28909. this.parametersNodes = parametersNodes;
  28910. this._candidateFnCall = null;
  28911. this.global = true;
  28912. }
  28913. getNodeType() {
  28914. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28915. }
  28916. setup( builder ) {
  28917. const params = this.parametersNodes;
  28918. let candidateFnCall = this._candidateFnCall;
  28919. if ( candidateFnCall === null ) {
  28920. let candidateFn = null;
  28921. let candidateScore = - 1;
  28922. for ( const functionNode of this.functionNodes ) {
  28923. const shaderNode = functionNode.shaderNode;
  28924. const layout = shaderNode.layout;
  28925. if ( layout === null ) {
  28926. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  28927. }
  28928. const inputs = layout.inputs;
  28929. if ( params.length === inputs.length ) {
  28930. let score = 0;
  28931. for ( let i = 0; i < params.length; i ++ ) {
  28932. const param = params[ i ];
  28933. const input = inputs[ i ];
  28934. if ( param.getNodeType( builder ) === input.type ) {
  28935. score ++;
  28936. } else {
  28937. score = 0;
  28938. }
  28939. }
  28940. if ( score > candidateScore ) {
  28941. candidateFn = functionNode;
  28942. candidateScore = score;
  28943. }
  28944. }
  28945. }
  28946. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  28947. }
  28948. return candidateFnCall;
  28949. }
  28950. }
  28951. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  28952. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  28953. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  28954. class MatcapUVNode extends TempNode {
  28955. constructor() {
  28956. super( 'vec2' );
  28957. }
  28958. setup() {
  28959. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28960. const y = positionViewDirection.cross( x );
  28961. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28962. }
  28963. }
  28964. const matcapUV = nodeImmutable( MatcapUVNode );
  28965. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  28966. class TimerNode extends UniformNode {
  28967. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  28968. super( value );
  28969. this.scope = scope;
  28970. this.scale = scale;
  28971. this.updateType = NodeUpdateType.FRAME;
  28972. }
  28973. /*
  28974. @TODO:
  28975. getNodeType( builder ) {
  28976. const scope = this.scope;
  28977. if ( scope === TimerNode.FRAME ) {
  28978. return 'uint';
  28979. }
  28980. return 'float';
  28981. }
  28982. */
  28983. update( frame ) {
  28984. const scope = this.scope;
  28985. const scale = this.scale;
  28986. if ( scope === TimerNode.LOCAL ) {
  28987. this.value += frame.deltaTime * scale;
  28988. } else if ( scope === TimerNode.DELTA ) {
  28989. this.value = frame.deltaTime * scale;
  28990. } else if ( scope === TimerNode.FRAME ) {
  28991. this.value = frame.frameId;
  28992. } else {
  28993. // global
  28994. this.value = frame.time * scale;
  28995. }
  28996. }
  28997. serialize( data ) {
  28998. super.serialize( data );
  28999. data.scope = this.scope;
  29000. data.scale = this.scale;
  29001. }
  29002. deserialize( data ) {
  29003. super.deserialize( data );
  29004. this.scope = data.scope;
  29005. this.scale = data.scale;
  29006. }
  29007. }
  29008. TimerNode.LOCAL = 'local';
  29009. TimerNode.GLOBAL = 'global';
  29010. TimerNode.DELTA = 'delta';
  29011. TimerNode.FRAME = 'frame';
  29012. // @TODO: add support to use node in timeScale
  29013. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  29014. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  29015. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  29016. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  29017. addNodeClass( 'TimerNode', TimerNode );
  29018. class OscNode extends Node {
  29019. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  29020. super();
  29021. this.method = method;
  29022. this.timeNode = timeNode;
  29023. }
  29024. getNodeType( builder ) {
  29025. return this.timeNode.getNodeType( builder );
  29026. }
  29027. setup() {
  29028. const method = this.method;
  29029. const timeNode = nodeObject( this.timeNode );
  29030. let outputNode = null;
  29031. if ( method === OscNode.SINE ) {
  29032. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  29033. } else if ( method === OscNode.SQUARE ) {
  29034. outputNode = timeNode.fract().round();
  29035. } else if ( method === OscNode.TRIANGLE ) {
  29036. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  29037. } else if ( method === OscNode.SAWTOOTH ) {
  29038. outputNode = timeNode.fract();
  29039. }
  29040. return outputNode;
  29041. }
  29042. serialize( data ) {
  29043. super.serialize( data );
  29044. data.method = this.method;
  29045. }
  29046. deserialize( data ) {
  29047. super.deserialize( data );
  29048. this.method = data.method;
  29049. }
  29050. }
  29051. OscNode.SINE = 'sine';
  29052. OscNode.SQUARE = 'square';
  29053. OscNode.TRIANGLE = 'triangle';
  29054. OscNode.SAWTOOTH = 'sawtooth';
  29055. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  29056. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  29057. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  29058. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  29059. addNodeClass( 'OscNode', OscNode );
  29060. class PackingNode extends TempNode {
  29061. constructor( scope, node ) {
  29062. super();
  29063. this.scope = scope;
  29064. this.node = node;
  29065. }
  29066. getNodeType( builder ) {
  29067. return this.node.getNodeType( builder );
  29068. }
  29069. setup() {
  29070. const { scope, node } = this;
  29071. let result = null;
  29072. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  29073. result = node.mul( 0.5 ).add( 0.5 );
  29074. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  29075. result = node.mul( 2.0 ).sub( 1 );
  29076. }
  29077. return result;
  29078. }
  29079. }
  29080. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  29081. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  29082. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  29083. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  29084. addNodeElement( 'directionToColor', directionToColor );
  29085. addNodeElement( 'colorToDirection', colorToDirection );
  29086. addNodeClass( 'PackingNode', PackingNode );
  29087. class RemapNode extends Node {
  29088. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  29089. super();
  29090. this.node = node;
  29091. this.inLowNode = inLowNode;
  29092. this.inHighNode = inHighNode;
  29093. this.outLowNode = outLowNode;
  29094. this.outHighNode = outHighNode;
  29095. this.doClamp = true;
  29096. }
  29097. setup() {
  29098. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  29099. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  29100. if ( doClamp === true ) t = t.clamp();
  29101. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  29102. }
  29103. }
  29104. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  29105. const remapClamp = nodeProxy( RemapNode );
  29106. addNodeElement( 'remap', remap );
  29107. addNodeElement( 'remapClamp', remapClamp );
  29108. addNodeClass( 'RemapNode', RemapNode );
  29109. class RotateUVNode extends TempNode {
  29110. constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) {
  29111. super( 'vec2' );
  29112. this.uvNode = uvNode;
  29113. this.rotationNode = rotationNode;
  29114. this.centerNode = centerNode;
  29115. }
  29116. setup() {
  29117. const { uvNode, rotationNode, centerNode } = this;
  29118. const vector = uvNode.sub( centerNode );
  29119. return vector.rotate( rotationNode ).add( centerNode );
  29120. }
  29121. }
  29122. const rotateUV = nodeProxy( RotateUVNode );
  29123. addNodeElement( 'rotateUV', rotateUV );
  29124. addNodeClass( 'RotateUVNode', RotateUVNode );
  29125. class RotateNode extends TempNode {
  29126. constructor( positionNode, rotationNode ) {
  29127. super();
  29128. this.positionNode = positionNode;
  29129. this.rotationNode = rotationNode;
  29130. }
  29131. getNodeType( builder ) {
  29132. return this.positionNode.getNodeType( builder );
  29133. }
  29134. setup( builder ) {
  29135. const { rotationNode, positionNode } = this;
  29136. const nodeType = this.getNodeType( builder );
  29137. if ( nodeType === 'vec2' ) {
  29138. const cosAngle = rotationNode.cos();
  29139. const sinAngle = rotationNode.sin();
  29140. const rotationMatrix = mat2(
  29141. cosAngle, sinAngle,
  29142. sinAngle.negate(), cosAngle
  29143. );
  29144. return rotationMatrix.mul( positionNode );
  29145. } else {
  29146. const rotation = rotationNode;
  29147. 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 ) );
  29148. 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 ) );
  29149. 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 ) );
  29150. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29151. }
  29152. }
  29153. }
  29154. const rotate = nodeProxy( RotateNode );
  29155. addNodeElement( 'rotate', rotate );
  29156. addNodeClass( 'RotateNode', RotateNode );
  29157. class SpriteSheetUVNode extends Node {
  29158. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29159. super( 'vec2' );
  29160. this.countNode = countNode;
  29161. this.uvNode = uvNode;
  29162. this.frameNode = frameNode;
  29163. }
  29164. setup() {
  29165. const { frameNode, uvNode, countNode } = this;
  29166. const { width, height } = countNode;
  29167. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29168. const column = frameNum.mod( width );
  29169. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29170. const scale = countNode.reciprocal();
  29171. const uvFrameOffset = vec2( column, row );
  29172. return uvNode.add( uvFrameOffset ).mul( scale );
  29173. }
  29174. }
  29175. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29176. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29177. class StorageArrayElementNode extends ArrayElementNode {
  29178. constructor( storageBufferNode, indexNode ) {
  29179. super( storageBufferNode, indexNode );
  29180. this.isStorageArrayElementNode = true;
  29181. }
  29182. set storageBufferNode( value ) {
  29183. this.node = value;
  29184. }
  29185. get storageBufferNode() {
  29186. return this.node;
  29187. }
  29188. setup( builder ) {
  29189. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29190. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29191. builder.setupPBO( this.node );
  29192. }
  29193. }
  29194. return super.setup( builder );
  29195. }
  29196. generate( builder, output ) {
  29197. let snippet;
  29198. const isAssignContext = builder.context.assign;
  29199. //
  29200. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29201. const { node } = this;
  29202. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29203. snippet = builder.generatePBO( this );
  29204. } else {
  29205. snippet = node.build( builder );
  29206. }
  29207. } else {
  29208. snippet = super.generate( builder );
  29209. }
  29210. if ( isAssignContext !== true ) {
  29211. const type = this.getNodeType( builder );
  29212. snippet = builder.format( snippet, type, output );
  29213. }
  29214. return snippet;
  29215. }
  29216. }
  29217. const storageElement = nodeProxy( StorageArrayElementNode );
  29218. addNodeElement( 'storageElement', storageElement );
  29219. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29220. class TriplanarTexturesNode extends Node {
  29221. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29222. super( 'vec4' );
  29223. this.textureXNode = textureXNode;
  29224. this.textureYNode = textureYNode;
  29225. this.textureZNode = textureZNode;
  29226. this.scaleNode = scaleNode;
  29227. this.positionNode = positionNode;
  29228. this.normalNode = normalNode;
  29229. }
  29230. setup() {
  29231. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29232. // Ref: https://github.com/keijiro/StandardTriplanar
  29233. // Blending factor of triplanar mapping
  29234. let bf = normalNode.abs().normalize();
  29235. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29236. // Triplanar mapping
  29237. const tx = positionNode.yz.mul( scaleNode );
  29238. const ty = positionNode.zx.mul( scaleNode );
  29239. const tz = positionNode.xy.mul( scaleNode );
  29240. // Base color
  29241. const textureX = textureXNode.value;
  29242. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29243. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29244. const cx = texture( textureX, tx ).mul( bf.x );
  29245. const cy = texture( textureY, ty ).mul( bf.y );
  29246. const cz = texture( textureZ, tz ).mul( bf.z );
  29247. return add( cx, cy, cz );
  29248. }
  29249. }
  29250. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29251. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29252. addNodeElement( 'triplanarTexture', triplanarTexture );
  29253. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29254. const _reflectorPlane = new Plane();
  29255. const _normal = new Vector3();
  29256. const _reflectorWorldPosition = new Vector3();
  29257. const _cameraWorldPosition = new Vector3();
  29258. const _rotationMatrix = new Matrix4();
  29259. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29260. const clipPlane = new Vector4();
  29261. const _view = new Vector3();
  29262. const _target = new Vector3();
  29263. const _q = new Vector4();
  29264. const _size$6 = new Vector2();
  29265. const _defaultRT = new RenderTarget();
  29266. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29267. let _inReflector = false;
  29268. class ReflectorNode extends TextureNode {
  29269. constructor( parameters = {} ) {
  29270. super( _defaultRT.texture, _defaultUV );
  29271. const {
  29272. target = new Object3D(),
  29273. resolution = 1,
  29274. generateMipmaps = false,
  29275. bounces = true
  29276. } = parameters;
  29277. //
  29278. this.target = target;
  29279. this.resolution = resolution;
  29280. this.generateMipmaps = generateMipmaps;
  29281. this.bounces = bounces;
  29282. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29283. this.virtualCameras = new WeakMap();
  29284. this.renderTargets = new WeakMap();
  29285. }
  29286. _updateResolution( renderTarget, renderer ) {
  29287. const resolution = this.resolution;
  29288. renderer.getDrawingBufferSize( _size$6 );
  29289. renderTarget.setSize( Math.round( _size$6.width * resolution ), Math.round( _size$6.height * resolution ) );
  29290. }
  29291. setup( builder ) {
  29292. this._updateResolution( _defaultRT, builder.renderer );
  29293. return super.setup( builder );
  29294. }
  29295. getTextureNode() {
  29296. return this.textureNode;
  29297. }
  29298. getVirtualCamera( camera ) {
  29299. let virtualCamera = this.virtualCameras.get( camera );
  29300. if ( virtualCamera === undefined ) {
  29301. virtualCamera = camera.clone();
  29302. this.virtualCameras.set( camera, virtualCamera );
  29303. }
  29304. return virtualCamera;
  29305. }
  29306. getRenderTarget( camera ) {
  29307. let renderTarget = this.renderTargets.get( camera );
  29308. if ( renderTarget === undefined ) {
  29309. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29310. if ( this.generateMipmaps === true ) {
  29311. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29312. renderTarget.texture.generateMipmaps = true;
  29313. }
  29314. this.renderTargets.set( camera, renderTarget );
  29315. }
  29316. return renderTarget;
  29317. }
  29318. updateBefore( frame ) {
  29319. if ( this.bounces === false && _inReflector ) return false;
  29320. _inReflector = true;
  29321. const { scene, camera, renderer, material } = frame;
  29322. const { target } = this;
  29323. const virtualCamera = this.getVirtualCamera( camera );
  29324. const renderTarget = this.getRenderTarget( virtualCamera );
  29325. renderer.getDrawingBufferSize( _size$6 );
  29326. this._updateResolution( renderTarget, renderer );
  29327. //
  29328. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29329. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29330. _rotationMatrix.extractRotation( target.matrixWorld );
  29331. _normal.set( 0, 0, 1 );
  29332. _normal.applyMatrix4( _rotationMatrix );
  29333. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29334. // Avoid rendering when reflector is facing away
  29335. if ( _view.dot( _normal ) > 0 ) return;
  29336. _view.reflect( _normal ).negate();
  29337. _view.add( _reflectorWorldPosition );
  29338. _rotationMatrix.extractRotation( camera.matrixWorld );
  29339. _lookAtPosition.set( 0, 0, - 1 );
  29340. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29341. _lookAtPosition.add( _cameraWorldPosition );
  29342. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29343. _target.reflect( _normal ).negate();
  29344. _target.add( _reflectorWorldPosition );
  29345. //
  29346. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29347. virtualCamera.position.copy( _view );
  29348. virtualCamera.up.set( 0, 1, 0 );
  29349. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29350. virtualCamera.up.reflect( _normal );
  29351. virtualCamera.lookAt( _target );
  29352. virtualCamera.near = camera.near;
  29353. virtualCamera.far = camera.far;
  29354. virtualCamera.updateMatrixWorld();
  29355. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29356. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29357. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29358. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29359. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29360. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29361. const projectionMatrix = virtualCamera.projectionMatrix;
  29362. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29363. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29364. _q.z = - 1.0;
  29365. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29366. // Calculate the scaled plane vector
  29367. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29368. const clipBias = 0;
  29369. // Replacing the third row of the projection matrix
  29370. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29371. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29372. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29373. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29374. //
  29375. this.value = renderTarget.texture;
  29376. material.visible = false;
  29377. const currentRenderTarget = renderer.getRenderTarget();
  29378. renderer.setRenderTarget( renderTarget );
  29379. renderer.render( scene, virtualCamera );
  29380. renderer.setRenderTarget( currentRenderTarget );
  29381. material.visible = true;
  29382. _inReflector = false;
  29383. }
  29384. }
  29385. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29386. // Helper for passes that need to fill the viewport with a single quad.
  29387. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29388. // https://github.com/mrdoob/three.js/pull/21358
  29389. class QuadGeometry extends BufferGeometry {
  29390. constructor( flipY = false ) {
  29391. super();
  29392. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  29393. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  29394. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  29395. }
  29396. }
  29397. const _geometry = /*@__PURE__*/ new QuadGeometry();
  29398. class QuadMesh extends Mesh {
  29399. constructor( material = null ) {
  29400. super( _geometry, material );
  29401. this.camera = _camera;
  29402. }
  29403. renderAsync( renderer ) {
  29404. return renderer.renderAsync( this, _camera );
  29405. }
  29406. render( renderer ) {
  29407. renderer.render( this, _camera );
  29408. }
  29409. }
  29410. const _size$5 = /*@__PURE__*/ new Vector2();
  29411. class RTTNode extends TextureNode {
  29412. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  29413. const renderTarget = new RenderTarget( width, height, options );
  29414. super( renderTarget.texture, uv() );
  29415. this.node = node;
  29416. this.width = width;
  29417. this.height = height;
  29418. this.renderTarget = renderTarget;
  29419. this.textureNeedsUpdate = true;
  29420. this.autoUpdate = true;
  29421. this.updateMap = new WeakMap();
  29422. this._rttNode = null;
  29423. this._quadMesh = new QuadMesh( new NodeMaterial() );
  29424. this.updateBeforeType = NodeUpdateType.RENDER;
  29425. }
  29426. get autoSize() {
  29427. return this.width === null;
  29428. }
  29429. setup( builder ) {
  29430. this._rttNode = this.node.context( builder.getSharedContext() );
  29431. this._quadMesh.material.needsUpdate = true;
  29432. return super.setup( builder );
  29433. }
  29434. setSize( width, height ) {
  29435. this.width = width;
  29436. this.height = height;
  29437. const effectiveWidth = width * this.pixelRatio;
  29438. const effectiveHeight = height * this.pixelRatio;
  29439. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  29440. this.textureNeedsUpdate = true;
  29441. }
  29442. setPixelRatio( pixelRatio ) {
  29443. this.pixelRatio = pixelRatio;
  29444. this.setSize( this.width, this.height );
  29445. }
  29446. updateBefore( { renderer } ) {
  29447. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  29448. this.textureNeedsUpdate = false;
  29449. //
  29450. if ( this.autoSize === true ) {
  29451. this.pixelRatio = renderer.getPixelRatio();
  29452. const size = renderer.getSize( _size$5 );
  29453. this.setSize( size.width, size.height );
  29454. }
  29455. //
  29456. this._quadMesh.material.fragmentNode = this._rttNode;
  29457. //
  29458. const currentRenderTarget = renderer.getRenderTarget();
  29459. renderer.setRenderTarget( this.renderTarget );
  29460. this._quadMesh.render( renderer );
  29461. renderer.setRenderTarget( currentRenderTarget );
  29462. }
  29463. clone() {
  29464. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  29465. newNode.sampler = this.sampler;
  29466. newNode.referenceNode = this;
  29467. return newNode;
  29468. }
  29469. }
  29470. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  29471. addNodeElement( 'toTexture', ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ) );
  29472. addNodeClass( 'RTTNode', RTTNode );
  29473. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  29474. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  29475. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  29476. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  29477. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  29478. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  29479. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  29480. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  29481. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  29482. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  29483. const transformedBentNormalView = ( () => {
  29484. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  29485. let bentNormal = anisotropyB.cross( positionViewDirection );
  29486. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  29487. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  29488. return bentNormal;
  29489. } )();
  29490. class VertexColorNode extends AttributeNode {
  29491. constructor( index = 0 ) {
  29492. super( null, 'vec4' );
  29493. this.isVertexColorNode = true;
  29494. this.index = index;
  29495. }
  29496. getAttributeName( /*builder*/ ) {
  29497. const index = this.index;
  29498. return 'color' + ( index > 0 ? index : '' );
  29499. }
  29500. generate( builder ) {
  29501. const attributeName = this.getAttributeName( builder );
  29502. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29503. let result;
  29504. if ( geometryAttribute === true ) {
  29505. result = super.generate( builder );
  29506. } else {
  29507. // Vertex color fallback should be white
  29508. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29509. }
  29510. return result;
  29511. }
  29512. serialize( data ) {
  29513. super.serialize( data );
  29514. data.index = this.index;
  29515. }
  29516. deserialize( data ) {
  29517. super.deserialize( data );
  29518. this.index = data.index;
  29519. }
  29520. }
  29521. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29522. addNodeClass( 'VertexColorNode', VertexColorNode );
  29523. class RendererReferenceNode extends ReferenceNode {
  29524. constructor( property, inputType, renderer = null ) {
  29525. super( property, inputType, renderer );
  29526. this.renderer = renderer;
  29527. }
  29528. updateReference( state ) {
  29529. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29530. return this.reference;
  29531. }
  29532. }
  29533. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29534. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29535. // Mipped Bicubic Texture Filtering by N8
  29536. // https://www.shadertoy.com/view/Dl2SDW
  29537. const bC = 1.0 / 6.0;
  29538. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29539. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29540. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29541. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29542. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29543. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29544. // h0 and h1 are the two offset functions
  29545. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29546. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29547. const bicubic = ( textureNode, texelSize, lod ) => {
  29548. const uv = textureNode.uvNode;
  29549. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29550. const iuv = floor( uvScaled );
  29551. const fuv = fract( uvScaled );
  29552. const g0x = g0( fuv.x );
  29553. const g1x = g1( fuv.x );
  29554. const h0x = h0( fuv.x );
  29555. const h1x = h1( fuv.x );
  29556. const h0y = h0( fuv.y );
  29557. const h1y = h1( fuv.y );
  29558. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29559. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29560. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29561. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29562. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29563. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29564. return a.add( b );
  29565. };
  29566. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29567. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29568. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29569. const fLodSizeInv = div( 1.0, fLodSize );
  29570. const cLodSizeInv = div( 1.0, cLodSize );
  29571. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29572. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29573. return fract( lodNode ).mix( fSample, cSample );
  29574. };
  29575. class TextureBicubicNode extends TempNode {
  29576. constructor( textureNode, blurNode = float( 3 ) ) {
  29577. super( 'vec4' );
  29578. this.textureNode = textureNode;
  29579. this.blurNode = blurNode;
  29580. }
  29581. setup() {
  29582. return textureBicubicMethod( this.textureNode, this.blurNode );
  29583. }
  29584. }
  29585. const textureBicubic = nodeProxy( TextureBicubicNode );
  29586. addNodeElement( 'bicubic', textureBicubic );
  29587. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29588. class PointUVNode extends Node {
  29589. constructor() {
  29590. super( 'vec2' );
  29591. this.isPointUVNode = true;
  29592. }
  29593. generate( /*builder*/ ) {
  29594. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29595. }
  29596. }
  29597. const pointUV = nodeImmutable( PointUVNode );
  29598. addNodeClass( 'PointUVNode', PointUVNode );
  29599. class SceneNode extends Node {
  29600. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29601. super();
  29602. this.scope = scope;
  29603. this.scene = scene;
  29604. }
  29605. setup( builder ) {
  29606. const scope = this.scope;
  29607. const scene = this.scene !== null ? this.scene : builder.scene;
  29608. let output;
  29609. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29610. output = reference( 'backgroundBlurriness', 'float', scene );
  29611. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29612. output = reference( 'backgroundIntensity', 'float', scene );
  29613. } else {
  29614. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29615. }
  29616. return output;
  29617. }
  29618. }
  29619. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29620. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29621. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29622. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29623. addNodeClass( 'SceneNode', SceneNode );
  29624. const GPUPrimitiveTopology = {
  29625. PointList: 'point-list',
  29626. LineList: 'line-list',
  29627. LineStrip: 'line-strip',
  29628. TriangleList: 'triangle-list',
  29629. TriangleStrip: 'triangle-strip',
  29630. };
  29631. const GPUCompareFunction = {
  29632. Never: 'never',
  29633. Less: 'less',
  29634. Equal: 'equal',
  29635. LessEqual: 'less-equal',
  29636. Greater: 'greater',
  29637. NotEqual: 'not-equal',
  29638. GreaterEqual: 'greater-equal',
  29639. Always: 'always'
  29640. };
  29641. const GPUStoreOp = {
  29642. Store: 'store',
  29643. Discard: 'discard'
  29644. };
  29645. const GPULoadOp = {
  29646. Load: 'load',
  29647. Clear: 'clear'
  29648. };
  29649. const GPUFrontFace = {
  29650. CCW: 'ccw',
  29651. CW: 'cw'
  29652. };
  29653. const GPUCullMode = {
  29654. None: 'none',
  29655. Front: 'front',
  29656. Back: 'back'
  29657. };
  29658. const GPUIndexFormat = {
  29659. Uint16: 'uint16',
  29660. Uint32: 'uint32'
  29661. };
  29662. const GPUTextureFormat = {
  29663. // 8-bit formats
  29664. R8Unorm: 'r8unorm',
  29665. R8Snorm: 'r8snorm',
  29666. R8Uint: 'r8uint',
  29667. R8Sint: 'r8sint',
  29668. // 16-bit formats
  29669. R16Uint: 'r16uint',
  29670. R16Sint: 'r16sint',
  29671. R16Float: 'r16float',
  29672. RG8Unorm: 'rg8unorm',
  29673. RG8Snorm: 'rg8snorm',
  29674. RG8Uint: 'rg8uint',
  29675. RG8Sint: 'rg8sint',
  29676. // 32-bit formats
  29677. R32Uint: 'r32uint',
  29678. R32Sint: 'r32sint',
  29679. R32Float: 'r32float',
  29680. RG16Uint: 'rg16uint',
  29681. RG16Sint: 'rg16sint',
  29682. RG16Float: 'rg16float',
  29683. RGBA8Unorm: 'rgba8unorm',
  29684. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29685. RGBA8Snorm: 'rgba8snorm',
  29686. RGBA8Uint: 'rgba8uint',
  29687. RGBA8Sint: 'rgba8sint',
  29688. BGRA8Unorm: 'bgra8unorm',
  29689. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29690. // Packed 32-bit formats
  29691. RGB9E5UFloat: 'rgb9e5ufloat',
  29692. RGB10A2Unorm: 'rgb10a2unorm',
  29693. RG11B10uFloat: 'rgb10a2unorm',
  29694. // 64-bit formats
  29695. RG32Uint: 'rg32uint',
  29696. RG32Sint: 'rg32sint',
  29697. RG32Float: 'rg32float',
  29698. RGBA16Uint: 'rgba16uint',
  29699. RGBA16Sint: 'rgba16sint',
  29700. RGBA16Float: 'rgba16float',
  29701. // 128-bit formats
  29702. RGBA32Uint: 'rgba32uint',
  29703. RGBA32Sint: 'rgba32sint',
  29704. RGBA32Float: 'rgba32float',
  29705. // Depth and stencil formats
  29706. Stencil8: 'stencil8',
  29707. Depth16Unorm: 'depth16unorm',
  29708. Depth24Plus: 'depth24plus',
  29709. Depth24PlusStencil8: 'depth24plus-stencil8',
  29710. Depth32Float: 'depth32float',
  29711. // 'depth32float-stencil8' extension
  29712. Depth32FloatStencil8: 'depth32float-stencil8',
  29713. // BC compressed formats usable if 'texture-compression-bc' is both
  29714. // supported by the device/user agent and enabled in requestDevice.
  29715. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29716. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29717. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29718. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29719. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29720. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29721. BC4RUnorm: 'bc4-r-unorm',
  29722. BC4RSnorm: 'bc4-r-snorm',
  29723. BC5RGUnorm: 'bc5-rg-unorm',
  29724. BC5RGSnorm: 'bc5-rg-snorm',
  29725. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29726. BC6HRGBFloat: 'bc6h-rgb-float',
  29727. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29728. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29729. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29730. // supported by the device/user agent and enabled in requestDevice.
  29731. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29732. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29733. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29734. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29735. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29736. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29737. EACR11Unorm: 'eac-r11unorm',
  29738. EACR11Snorm: 'eac-r11snorm',
  29739. EACRG11Unorm: 'eac-rg11unorm',
  29740. EACRG11Snorm: 'eac-rg11snorm',
  29741. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29742. // supported by the device/user agent and enabled in requestDevice.
  29743. ASTC4x4Unorm: 'astc-4x4-unorm',
  29744. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29745. ASTC5x4Unorm: 'astc-5x4-unorm',
  29746. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29747. ASTC5x5Unorm: 'astc-5x5-unorm',
  29748. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29749. ASTC6x5Unorm: 'astc-6x5-unorm',
  29750. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29751. ASTC6x6Unorm: 'astc-6x6-unorm',
  29752. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29753. ASTC8x5Unorm: 'astc-8x5-unorm',
  29754. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29755. ASTC8x6Unorm: 'astc-8x6-unorm',
  29756. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29757. ASTC8x8Unorm: 'astc-8x8-unorm',
  29758. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29759. ASTC10x5Unorm: 'astc-10x5-unorm',
  29760. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29761. ASTC10x6Unorm: 'astc-10x6-unorm',
  29762. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29763. ASTC10x8Unorm: 'astc-10x8-unorm',
  29764. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29765. ASTC10x10Unorm: 'astc-10x10-unorm',
  29766. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29767. ASTC12x10Unorm: 'astc-12x10-unorm',
  29768. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29769. ASTC12x12Unorm: 'astc-12x12-unorm',
  29770. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29771. };
  29772. const GPUAddressMode = {
  29773. ClampToEdge: 'clamp-to-edge',
  29774. Repeat: 'repeat',
  29775. MirrorRepeat: 'mirror-repeat'
  29776. };
  29777. const GPUFilterMode = {
  29778. Linear: 'linear',
  29779. Nearest: 'nearest'
  29780. };
  29781. const GPUBlendFactor = {
  29782. Zero: 'zero',
  29783. One: 'one',
  29784. Src: 'src',
  29785. OneMinusSrc: 'one-minus-src',
  29786. SrcAlpha: 'src-alpha',
  29787. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29788. Dst: 'dst',
  29789. OneMinusDstColor: 'one-minus-dst',
  29790. DstAlpha: 'dst-alpha',
  29791. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29792. SrcAlphaSaturated: 'src-alpha-saturated',
  29793. Constant: 'constant',
  29794. OneMinusConstant: 'one-minus-constant'
  29795. };
  29796. const GPUBlendOperation = {
  29797. Add: 'add',
  29798. Subtract: 'subtract',
  29799. ReverseSubtract: 'reverse-subtract',
  29800. Min: 'min',
  29801. Max: 'max'
  29802. };
  29803. const GPUColorWriteFlags = {
  29804. None: 0,
  29805. Red: 0x1,
  29806. Green: 0x2,
  29807. Blue: 0x4,
  29808. Alpha: 0x8,
  29809. All: 0xF
  29810. };
  29811. const GPUStencilOperation = {
  29812. Keep: 'keep',
  29813. Zero: 'zero',
  29814. Replace: 'replace',
  29815. Invert: 'invert',
  29816. IncrementClamp: 'increment-clamp',
  29817. DecrementClamp: 'decrement-clamp',
  29818. IncrementWrap: 'increment-wrap',
  29819. DecrementWrap: 'decrement-wrap'
  29820. };
  29821. const GPUBufferBindingType = {
  29822. Uniform: 'uniform',
  29823. Storage: 'storage',
  29824. ReadOnlyStorage: 'read-only-storage'
  29825. };
  29826. const GPUStorageTextureAccess = {
  29827. WriteOnly: 'write-only',
  29828. ReadOnly: 'read-only',
  29829. ReadWrite: 'read-write',
  29830. };
  29831. const GPUTextureSampleType = {
  29832. Float: 'float',
  29833. UnfilterableFloat: 'unfilterable-float',
  29834. Depth: 'depth',
  29835. SInt: 'sint',
  29836. UInt: 'uint'
  29837. };
  29838. const GPUTextureDimension = {
  29839. OneD: '1d',
  29840. TwoD: '2d',
  29841. ThreeD: '3d'
  29842. };
  29843. const GPUTextureViewDimension = {
  29844. OneD: '1d',
  29845. TwoD: '2d',
  29846. TwoDArray: '2d-array',
  29847. Cube: 'cube',
  29848. CubeArray: 'cube-array',
  29849. ThreeD: '3d'
  29850. };
  29851. const GPUTextureAspect = {
  29852. All: 'all',
  29853. StencilOnly: 'stencil-only',
  29854. DepthOnly: 'depth-only'
  29855. };
  29856. const GPUInputStepMode = {
  29857. Vertex: 'vertex',
  29858. Instance: 'instance'
  29859. };
  29860. const GPUFeatureName = {
  29861. DepthClipControl: 'depth-clip-control',
  29862. Depth32FloatStencil8: 'depth32float-stencil8',
  29863. TextureCompressionBC: 'texture-compression-bc',
  29864. TextureCompressionETC2: 'texture-compression-etc2',
  29865. TextureCompressionASTC: 'texture-compression-astc',
  29866. TimestampQuery: 'timestamp-query',
  29867. IndirectFirstInstance: 'indirect-first-instance',
  29868. ShaderF16: 'shader-f16',
  29869. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29870. BGRA8UNormStorage: 'bgra8unorm-storage',
  29871. Float32Filterable: 'float32-filterable',
  29872. ClipDistances: 'clip-distances',
  29873. DualSourceBlending: 'dual-source-blending'
  29874. };
  29875. class StorageBufferNode extends BufferNode {
  29876. constructor( value, bufferType, bufferCount = 0 ) {
  29877. super( value, bufferType, bufferCount );
  29878. this.isStorageBufferNode = true;
  29879. this.access = GPUBufferBindingType.Storage;
  29880. this.bufferObject = false;
  29881. this.bufferCount = bufferCount;
  29882. this._attribute = null;
  29883. this._varying = null;
  29884. this.global = true;
  29885. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29886. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29887. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29888. else value.isStorageBufferAttribute = true;
  29889. }
  29890. }
  29891. getHash( builder ) {
  29892. if ( this.bufferCount === 0 ) {
  29893. let bufferData = builder.globalCache.getData( this.value );
  29894. if ( bufferData === undefined ) {
  29895. bufferData = {
  29896. node: this
  29897. };
  29898. builder.globalCache.setData( this.value, bufferData );
  29899. }
  29900. return bufferData.node.uuid;
  29901. }
  29902. return this.uuid;
  29903. }
  29904. getInputType( /*builder*/ ) {
  29905. return 'storageBuffer';
  29906. }
  29907. element( indexNode ) {
  29908. return storageElement( this, indexNode );
  29909. }
  29910. setBufferObject( value ) {
  29911. this.bufferObject = value;
  29912. return this;
  29913. }
  29914. setAccess( value ) {
  29915. this.access = value;
  29916. return this;
  29917. }
  29918. toReadOnly() {
  29919. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  29920. }
  29921. generate( builder ) {
  29922. if ( builder.isAvailable( 'storageBuffer' ) ) {
  29923. return super.generate( builder );
  29924. }
  29925. const nodeType = this.getNodeType( builder );
  29926. if ( this._attribute === null ) {
  29927. this._attribute = bufferAttribute( this.value );
  29928. this._varying = varying( this._attribute );
  29929. }
  29930. const output = this._varying.build( builder, nodeType );
  29931. builder.registerTransform( output, this._attribute );
  29932. return output;
  29933. }
  29934. }
  29935. // Read-Write Storage
  29936. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  29937. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  29938. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  29939. class StorageTextureNode extends TextureNode {
  29940. constructor( value, uvNode, storeNode = null ) {
  29941. super( value, uvNode );
  29942. this.storeNode = storeNode;
  29943. this.isStorageTextureNode = true;
  29944. this.access = GPUStorageTextureAccess.WriteOnly;
  29945. }
  29946. getInputType( /*builder*/ ) {
  29947. return 'storageTexture';
  29948. }
  29949. setup( builder ) {
  29950. super.setup( builder );
  29951. const properties = builder.getNodeProperties( this );
  29952. properties.storeNode = this.storeNode;
  29953. }
  29954. setAccess( value ) {
  29955. this.access = value;
  29956. return this;
  29957. }
  29958. generate( builder, output ) {
  29959. let snippet;
  29960. if ( this.storeNode !== null ) {
  29961. snippet = this.generateStore( builder );
  29962. } else {
  29963. snippet = super.generate( builder, output );
  29964. }
  29965. return snippet;
  29966. }
  29967. toReadOnly() {
  29968. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  29969. }
  29970. toWriteOnly() {
  29971. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  29972. }
  29973. generateStore( builder ) {
  29974. const properties = builder.getNodeProperties( this );
  29975. const { uvNode, storeNode } = properties;
  29976. const textureProperty = super.generate( builder, 'property' );
  29977. const uvSnippet = uvNode.build( builder, 'uvec2' );
  29978. const storeSnippet = storeNode.build( builder, 'vec4' );
  29979. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  29980. builder.addLineFlowCode( snippet );
  29981. }
  29982. }
  29983. const storageTexture = nodeProxy( StorageTextureNode );
  29984. const textureStore = ( value, uvNode, storeNode ) => {
  29985. const node = storageTexture( value, uvNode, storeNode );
  29986. if ( storeNode !== null ) node.append();
  29987. return node;
  29988. };
  29989. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  29990. const normal = tslFn( ( { texture, uv } ) => {
  29991. const epsilon = 0.0001;
  29992. const ret = vec3().temp();
  29993. If( uv.x.lessThan( epsilon ), () => {
  29994. ret.assign( vec3( 1, 0, 0 ) );
  29995. } ).elseif( uv.y.lessThan( epsilon ), () => {
  29996. ret.assign( vec3( 0, 1, 0 ) );
  29997. } ).elseif( uv.z.lessThan( epsilon ), () => {
  29998. ret.assign( vec3( 0, 0, 1 ) );
  29999. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  30000. ret.assign( vec3( - 1, 0, 0 ) );
  30001. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  30002. ret.assign( vec3( 0, - 1, 0 ) );
  30003. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  30004. ret.assign( vec3( 0, 0, - 1 ) );
  30005. } ).else( () => {
  30006. const step = 0.01;
  30007. 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 );
  30008. 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 );
  30009. 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 );
  30010. ret.assign( vec3( x, y, z ) );
  30011. } );
  30012. return ret.normalize();
  30013. } );
  30014. class Texture3DNode extends TextureNode {
  30015. constructor( value, uvNode = null, levelNode = null ) {
  30016. super( value, uvNode, levelNode );
  30017. this.isTexture3DNode = true;
  30018. }
  30019. getInputType( /*builder*/ ) {
  30020. return 'texture3D';
  30021. }
  30022. getDefaultUV() {
  30023. return vec3( 0.5, 0.5, 0.5 );
  30024. }
  30025. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  30026. setupUV( builder, uvNode ) {
  30027. return uvNode;
  30028. }
  30029. generateUV( builder, uvNode ) {
  30030. return uvNode.build( builder, 'vec3' );
  30031. }
  30032. normal( uvNode ) {
  30033. return normal( { texture: this, uv: uvNode } );
  30034. }
  30035. }
  30036. const texture3D = nodeProxy( Texture3DNode );
  30037. addNodeClass( 'Texture3DNode', Texture3DNode );
  30038. class UserDataNode extends ReferenceNode {
  30039. constructor( property, inputType, userData = null ) {
  30040. super( property, inputType, userData );
  30041. this.userData = userData;
  30042. }
  30043. update( frame ) {
  30044. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  30045. super.update( frame );
  30046. }
  30047. }
  30048. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  30049. addNodeClass( 'UserDataNode', UserDataNode );
  30050. const BurnNode = tslFn( ( { base, blend } ) => {
  30051. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  30052. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30053. } ).setLayout( {
  30054. name: 'burnColor',
  30055. type: 'vec3',
  30056. inputs: [
  30057. { name: 'base', type: 'vec3' },
  30058. { name: 'blend', type: 'vec3' }
  30059. ]
  30060. } );
  30061. const DodgeNode = tslFn( ( { base, blend } ) => {
  30062. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  30063. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30064. } ).setLayout( {
  30065. name: 'dodgeColor',
  30066. type: 'vec3',
  30067. inputs: [
  30068. { name: 'base', type: 'vec3' },
  30069. { name: 'blend', type: 'vec3' }
  30070. ]
  30071. } );
  30072. const ScreenNode = tslFn( ( { base, blend } ) => {
  30073. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  30074. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30075. } ).setLayout( {
  30076. name: 'screenColor',
  30077. type: 'vec3',
  30078. inputs: [
  30079. { name: 'base', type: 'vec3' },
  30080. { name: 'blend', type: 'vec3' }
  30081. ]
  30082. } );
  30083. const OverlayNode = tslFn( ( { base, blend } ) => {
  30084. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  30085. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  30086. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30087. } ).setLayout( {
  30088. name: 'overlayColor',
  30089. type: 'vec3',
  30090. inputs: [
  30091. { name: 'base', type: 'vec3' },
  30092. { name: 'blend', type: 'vec3' }
  30093. ]
  30094. } );
  30095. class BlendModeNode extends TempNode {
  30096. constructor( blendMode, baseNode, blendNode ) {
  30097. super();
  30098. this.blendMode = blendMode;
  30099. this.baseNode = baseNode;
  30100. this.blendNode = blendNode;
  30101. }
  30102. setup() {
  30103. const { blendMode, baseNode, blendNode } = this;
  30104. const params = { base: baseNode, blend: blendNode };
  30105. let outputNode = null;
  30106. if ( blendMode === BlendModeNode.BURN ) {
  30107. outputNode = BurnNode( params );
  30108. } else if ( blendMode === BlendModeNode.DODGE ) {
  30109. outputNode = DodgeNode( params );
  30110. } else if ( blendMode === BlendModeNode.SCREEN ) {
  30111. outputNode = ScreenNode( params );
  30112. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  30113. outputNode = OverlayNode( params );
  30114. }
  30115. return outputNode;
  30116. }
  30117. }
  30118. BlendModeNode.BURN = 'burn';
  30119. BlendModeNode.DODGE = 'dodge';
  30120. BlendModeNode.SCREEN = 'screen';
  30121. BlendModeNode.OVERLAY = 'overlay';
  30122. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  30123. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  30124. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  30125. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  30126. addNodeElement( 'burn', burn );
  30127. addNodeElement( 'dodge', dodge );
  30128. addNodeElement( 'overlay', overlay );
  30129. addNodeElement( 'screen', screen );
  30130. addNodeClass( 'BlendModeNode', BlendModeNode );
  30131. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  30132. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  30133. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  30134. // It's used to preserve the same TextureNode instance
  30135. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  30136. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  30137. return vec2(
  30138. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  30139. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  30140. ).mul( bumpScale );
  30141. } );
  30142. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  30143. const perturbNormalArb = tslFn( ( inputs ) => {
  30144. const { surf_pos, surf_norm, dHdxy } = inputs;
  30145. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30146. const vSigmaX = surf_pos.dFdx().normalize();
  30147. const vSigmaY = surf_pos.dFdy().normalize();
  30148. const vN = surf_norm; // normalized
  30149. const R1 = vSigmaY.cross( vN );
  30150. const R2 = vN.cross( vSigmaX );
  30151. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30152. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30153. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30154. } );
  30155. class BumpMapNode extends TempNode {
  30156. constructor( textureNode, scaleNode = null ) {
  30157. super( 'vec3' );
  30158. this.textureNode = textureNode;
  30159. this.scaleNode = scaleNode;
  30160. }
  30161. setup() {
  30162. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30163. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30164. return perturbNormalArb( {
  30165. surf_pos: positionView,
  30166. surf_norm: normalView,
  30167. dHdxy
  30168. } );
  30169. }
  30170. }
  30171. const bumpMap = nodeProxy( BumpMapNode );
  30172. addNodeElement( 'bumpMap', bumpMap );
  30173. addNodeClass( 'BumpMapNode', BumpMapNode );
  30174. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30175. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30176. } );
  30177. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30178. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30179. const mx = color.r.max( color.g.max( color.b ) );
  30180. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30181. return mix( color.rgb, mx, amt );
  30182. } );
  30183. const hueNode = tslFn( ( { color, adjustment } ) => {
  30184. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30185. const cosAngle = adjustment.cos();
  30186. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30187. } );
  30188. class ColorAdjustmentNode extends TempNode {
  30189. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30190. super( 'vec3' );
  30191. this.method = method;
  30192. this.colorNode = colorNode;
  30193. this.adjustmentNode = adjustmentNode;
  30194. }
  30195. setup() {
  30196. const { method, colorNode, adjustmentNode } = this;
  30197. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30198. let outputNode = null;
  30199. if ( method === ColorAdjustmentNode.SATURATION ) {
  30200. outputNode = saturationNode( callParams );
  30201. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30202. outputNode = vibranceNode( callParams );
  30203. } else if ( method === ColorAdjustmentNode.HUE ) {
  30204. outputNode = hueNode( callParams );
  30205. } else {
  30206. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30207. }
  30208. return outputNode;
  30209. }
  30210. }
  30211. ColorAdjustmentNode.SATURATION = 'saturation';
  30212. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30213. ColorAdjustmentNode.HUE = 'hue';
  30214. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30215. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30216. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30217. const _luminanceCoefficients = /*#__PURE__*/ new Vector3();
  30218. const luminance = (
  30219. color,
  30220. luminanceCoefficients = vec3( ... ColorManagement.getLuminanceCoefficients( _luminanceCoefficients ) )
  30221. ) => dot( color, luminanceCoefficients );
  30222. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30223. addNodeElement( 'saturation', saturation );
  30224. addNodeElement( 'vibrance', vibrance );
  30225. addNodeElement( 'hue', hue );
  30226. addNodeElement( 'threshold', threshold );
  30227. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30228. // Normal Mapping Without Precomputed Tangents
  30229. // http://www.thetenthplanet.de/archives/1180
  30230. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30231. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30232. const q0 = eye_pos.dFdx();
  30233. const q1 = eye_pos.dFdy();
  30234. const st0 = uv.dFdx();
  30235. const st1 = uv.dFdy();
  30236. const N = surf_norm; // normalized
  30237. const q1perp = q1.cross( N );
  30238. const q0perp = N.cross( q0 );
  30239. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30240. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30241. const det = T.dot( T ).max( B.dot( B ) );
  30242. const scale = faceDirection.mul( det.inverseSqrt() );
  30243. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30244. } );
  30245. class NormalMapNode extends TempNode {
  30246. constructor( node, scaleNode = null ) {
  30247. super( 'vec3' );
  30248. this.node = node;
  30249. this.scaleNode = scaleNode;
  30250. this.normalMapType = TangentSpaceNormalMap;
  30251. }
  30252. setup( builder ) {
  30253. const { normalMapType, scaleNode } = this;
  30254. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30255. if ( scaleNode !== null ) {
  30256. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30257. }
  30258. let outputNode = null;
  30259. if ( normalMapType === ObjectSpaceNormalMap ) {
  30260. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30261. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30262. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30263. if ( tangent === true ) {
  30264. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30265. } else {
  30266. outputNode = perturbNormal2Arb( {
  30267. eye_pos: positionView,
  30268. surf_norm: normalView,
  30269. mapN: normalMap,
  30270. uv: uv()
  30271. } );
  30272. }
  30273. }
  30274. return outputNode;
  30275. }
  30276. }
  30277. const normalMap = nodeProxy( NormalMapNode );
  30278. addNodeElement( 'normalMap', normalMap );
  30279. addNodeClass( 'NormalMapNode', NormalMapNode );
  30280. class PosterizeNode extends TempNode {
  30281. constructor( sourceNode, stepsNode ) {
  30282. super();
  30283. this.sourceNode = sourceNode;
  30284. this.stepsNode = stepsNode;
  30285. }
  30286. setup() {
  30287. const { sourceNode, stepsNode } = this;
  30288. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30289. }
  30290. }
  30291. const posterize = nodeProxy( PosterizeNode );
  30292. addNodeElement( 'posterize', posterize );
  30293. addNodeClass( 'PosterizeNode', PosterizeNode );
  30294. // exposure only
  30295. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30296. return color.mul( exposure ).clamp();
  30297. } );
  30298. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30299. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30300. color = color.mul( exposure );
  30301. return color.div( color.add( 1.0 ) ).clamp();
  30302. } );
  30303. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30304. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30305. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30306. color = color.mul( exposure );
  30307. color = color.sub( 0.004 ).max( 0.0 );
  30308. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30309. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30310. return a.div( b ).pow( 2.2 );
  30311. } );
  30312. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30313. const RRTAndODTFit = tslFn( ( { color } ) => {
  30314. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30315. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30316. return a.div( b );
  30317. } );
  30318. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30319. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30320. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30321. const ACESInputMat = mat3(
  30322. 0.59719, 0.35458, 0.04823,
  30323. 0.07600, 0.90834, 0.01566,
  30324. 0.02840, 0.13383, 0.83777
  30325. );
  30326. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30327. const ACESOutputMat = mat3(
  30328. 1.60475, - 0.53108, - 0.07367,
  30329. - 0.10208, 1.10813, - 0.00605,
  30330. - 0.00327, - 0.07276, 1.07602
  30331. );
  30332. color = color.mul( exposure ).div( 0.6 );
  30333. color = ACESInputMat.mul( color );
  30334. // Apply RRT and ODT
  30335. color = RRTAndODTFit( { color } );
  30336. color = ACESOutputMat.mul( color );
  30337. // Clamp to [0, 1]
  30338. return color.clamp();
  30339. } );
  30340. const LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  30341. const LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  30342. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30343. const x = vec3( x_immutable ).toVar();
  30344. const x2 = vec3( x.mul( x ) ).toVar();
  30345. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30346. 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 ) ) ) );
  30347. } );
  30348. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30349. const colortone = vec3( color ).toVar();
  30350. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30351. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30352. const AgxMinEv = float( - 12.47393 );
  30353. const AgxMaxEv = float( 4.026069 );
  30354. colortone.mulAssign( exposure );
  30355. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30356. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30357. colortone.assign( max$1( colortone, 1e-10 ) );
  30358. colortone.assign( log2( colortone ) );
  30359. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30360. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30361. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30362. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30363. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30364. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30365. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30366. return colortone;
  30367. } );
  30368. // https://modelviewer.dev/examples/tone-mapping
  30369. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30370. const StartCompression = float( 0.8 - 0.04 );
  30371. const Desaturation = float( 0.15 );
  30372. color = color.mul( exposure );
  30373. const x = min$1( color.r, min$1( color.g, color.b ) );
  30374. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30375. color.subAssign( offset );
  30376. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30377. If( peak.lessThan( StartCompression ), () => {
  30378. return color;
  30379. } );
  30380. const d = sub( 1, StartCompression );
  30381. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30382. color.mulAssign( newPeak.div( peak ) );
  30383. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30384. return mix( color, vec3( newPeak ), g );
  30385. } ).setLayout( {
  30386. name: 'NeutralToneMapping',
  30387. type: 'vec3',
  30388. inputs: [
  30389. { name: 'color', type: 'vec3' },
  30390. { name: 'exposure', type: 'float' }
  30391. ]
  30392. } );
  30393. const toneMappingLib = {
  30394. [ LinearToneMapping ]: LinearToneMappingNode,
  30395. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30396. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30397. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30398. [ AgXToneMapping ]: AGXToneMappingNode,
  30399. [ NeutralToneMapping ]: NeutralToneMappingNode
  30400. };
  30401. class ToneMappingNode extends TempNode {
  30402. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30403. super( 'vec3' );
  30404. this.toneMapping = toneMapping;
  30405. this.exposureNode = exposureNode;
  30406. this.colorNode = colorNode;
  30407. }
  30408. getCacheKey() {
  30409. let cacheKey = super.getCacheKey();
  30410. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30411. return cacheKey;
  30412. }
  30413. setup( builder ) {
  30414. const colorNode = this.colorNode || builder.context.color;
  30415. const toneMapping = this.toneMapping;
  30416. if ( toneMapping === NoToneMapping ) return colorNode;
  30417. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30418. const toneMappingNode = toneMappingLib[ toneMapping ];
  30419. let outputNode = null;
  30420. if ( toneMappingNode ) {
  30421. outputNode = toneMappingNode( toneMappingParams );
  30422. } else {
  30423. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30424. outputNode = colorNode;
  30425. }
  30426. return outputNode;
  30427. }
  30428. }
  30429. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30430. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30431. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30432. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30433. let _sharedFramebuffer = null;
  30434. class ViewportSharedTextureNode extends ViewportTextureNode {
  30435. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30436. if ( _sharedFramebuffer === null ) {
  30437. _sharedFramebuffer = new FramebufferTexture();
  30438. }
  30439. super( uvNode, levelNode, _sharedFramebuffer );
  30440. }
  30441. updateReference() {
  30442. return this;
  30443. }
  30444. }
  30445. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30446. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30447. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30448. const _size$4 = /*@__PURE__*/ new Vector2();
  30449. class PassTextureNode extends TextureNode {
  30450. constructor( passNode, texture ) {
  30451. super( texture );
  30452. this.passNode = passNode;
  30453. this.setUpdateMatrix( false );
  30454. }
  30455. setup( builder ) {
  30456. this.passNode.build( builder );
  30457. return super.setup( builder );
  30458. }
  30459. clone() {
  30460. return new this.constructor( this.passNode, this.value );
  30461. }
  30462. }
  30463. class PassMultipleTextureNode extends PassTextureNode {
  30464. constructor( passNode, textureName ) {
  30465. super( passNode, null );
  30466. this.textureName = textureName;
  30467. }
  30468. setup( builder ) {
  30469. this.value = this.passNode.getTexture( this.textureName );
  30470. return super.setup( builder );
  30471. }
  30472. clone() {
  30473. return new this.constructor( this.passNode, this.textureName );
  30474. }
  30475. }
  30476. class PassNode extends TempNode {
  30477. constructor( scope, scene, camera, options = {} ) {
  30478. super( 'vec4' );
  30479. this.scope = scope;
  30480. this.scene = scene;
  30481. this.camera = camera;
  30482. this.options = options;
  30483. this._pixelRatio = 1;
  30484. this._width = 1;
  30485. this._height = 1;
  30486. const depthTexture = new DepthTexture();
  30487. depthTexture.isRenderTargetTexture = true;
  30488. //depthTexture.type = FloatType;
  30489. depthTexture.name = 'depth';
  30490. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  30491. renderTarget.texture.name = 'output';
  30492. renderTarget.depthTexture = depthTexture;
  30493. this.renderTarget = renderTarget;
  30494. this.updateBeforeType = NodeUpdateType.FRAME;
  30495. this._textures = {
  30496. output: renderTarget.texture,
  30497. depth: depthTexture
  30498. };
  30499. this._nodes = {};
  30500. this._linearDepthNode = null;
  30501. this._viewZNode = null;
  30502. this._cameraNear = uniform( 0 );
  30503. this._cameraFar = uniform( 0 );
  30504. this._mrt = null;
  30505. this.isPassNode = true;
  30506. }
  30507. setMRT( mrt ) {
  30508. this._mrt = mrt;
  30509. return this;
  30510. }
  30511. getMRT() {
  30512. return this._mrt;
  30513. }
  30514. isGlobal() {
  30515. return true;
  30516. }
  30517. getTexture( name ) {
  30518. let texture = this._textures[ name ];
  30519. if ( texture === undefined ) {
  30520. const refTexture = this.renderTarget.texture;
  30521. texture = refTexture.clone();
  30522. texture.isRenderTargetTexture = true;
  30523. texture.name = name;
  30524. this._textures[ name ] = texture;
  30525. this.renderTarget.textures.push( texture );
  30526. }
  30527. return texture;
  30528. }
  30529. getTextureNode( name = 'output' ) {
  30530. let textureNode = this._nodes[ name ];
  30531. if ( textureNode === undefined ) {
  30532. this._nodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  30533. }
  30534. return textureNode;
  30535. }
  30536. getViewZNode() {
  30537. if ( this._viewZNode === null ) {
  30538. const cameraNear = this._cameraNear;
  30539. const cameraFar = this._cameraFar;
  30540. this._viewZNode = perspectiveDepthToViewZ( this.getTextureNode( 'depth' ), cameraNear, cameraFar );
  30541. }
  30542. return this._viewZNode;
  30543. }
  30544. getLinearDepthNode() {
  30545. if ( this._linearDepthNode === null ) {
  30546. const cameraNear = this._cameraNear;
  30547. const cameraFar = this._cameraFar;
  30548. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30549. this._linearDepthNode = viewZToOrthographicDepth( this.getViewZNode(), cameraNear, cameraFar );
  30550. }
  30551. return this._linearDepthNode;
  30552. }
  30553. setup( { renderer } ) {
  30554. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  30555. // Disable MSAA for WebGL backend for now
  30556. if ( renderer.backend.isWebGLBackend === true ) {
  30557. this.renderTarget.samples = 0;
  30558. }
  30559. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  30560. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30561. }
  30562. updateBefore( frame ) {
  30563. const { renderer } = frame;
  30564. const { scene, camera } = this;
  30565. this._pixelRatio = renderer.getPixelRatio();
  30566. const size = renderer.getSize( _size$4 );
  30567. this.setSize( size.width, size.height );
  30568. const currentRenderTarget = renderer.getRenderTarget();
  30569. const currentMRT = renderer.getMRT();
  30570. this._cameraNear.value = camera.near;
  30571. this._cameraFar.value = camera.far;
  30572. renderer.setRenderTarget( this.renderTarget );
  30573. renderer.setMRT( this._mrt );
  30574. renderer.render( scene, camera );
  30575. renderer.setRenderTarget( currentRenderTarget );
  30576. renderer.setMRT( currentMRT );
  30577. }
  30578. setSize( width, height ) {
  30579. this._width = width;
  30580. this._height = height;
  30581. const effectiveWidth = this._width * this._pixelRatio;
  30582. const effectiveHeight = this._height * this._pixelRatio;
  30583. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30584. }
  30585. setPixelRatio( pixelRatio ) {
  30586. this._pixelRatio = pixelRatio;
  30587. this.setSize( this._width, this._height );
  30588. }
  30589. dispose() {
  30590. this.renderTarget.dispose();
  30591. }
  30592. }
  30593. PassNode.COLOR = 'color';
  30594. PassNode.DEPTH = 'depth';
  30595. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  30596. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30597. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30598. addNodeClass( 'PassNode', PassNode );
  30599. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30600. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30601. const _quadMesh1 = /*@__PURE__*/ new QuadMesh();
  30602. const _quadMesh2 = /*@__PURE__*/ new QuadMesh();
  30603. class GaussianBlurNode extends TempNode {
  30604. constructor( textureNode, directionNode = null, sigma = 2 ) {
  30605. super( 'vec4' );
  30606. this.textureNode = textureNode;
  30607. this.directionNode = directionNode;
  30608. this.sigma = sigma;
  30609. this._invSize = uniform( new Vector2() );
  30610. this._passDirection = uniform( new Vector2() );
  30611. this._horizontalRT = new RenderTarget();
  30612. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30613. this._verticalRT = new RenderTarget();
  30614. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30615. this._textureNode = passTexture( this, this._verticalRT.texture );
  30616. this.updateBeforeType = NodeUpdateType.RENDER;
  30617. this.resolution = new Vector2( 1, 1 );
  30618. }
  30619. setSize( width, height ) {
  30620. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30621. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30622. this._invSize.value.set( 1 / width, 1 / height );
  30623. this._horizontalRT.setSize( width, height );
  30624. this._verticalRT.setSize( width, height );
  30625. }
  30626. updateBefore( frame ) {
  30627. const { renderer } = frame;
  30628. const textureNode = this.textureNode;
  30629. const map = textureNode.value;
  30630. const currentRenderTarget = renderer.getRenderTarget();
  30631. const currentMRT = renderer.getMRT();
  30632. const currentTexture = textureNode.value;
  30633. _quadMesh1.material = this._material;
  30634. _quadMesh2.material = this._material;
  30635. this.setSize( map.image.width, map.image.height );
  30636. const textureType = map.type;
  30637. this._horizontalRT.texture.type = textureType;
  30638. this._verticalRT.texture.type = textureType;
  30639. // clear
  30640. renderer.setMRT( null );
  30641. // horizontal
  30642. renderer.setRenderTarget( this._horizontalRT );
  30643. this._passDirection.value.set( 1, 0 );
  30644. _quadMesh1.render( renderer );
  30645. // vertical
  30646. textureNode.value = this._horizontalRT.texture;
  30647. renderer.setRenderTarget( this._verticalRT );
  30648. this._passDirection.value.set( 0, 1 );
  30649. _quadMesh2.render( renderer );
  30650. // restore
  30651. renderer.setRenderTarget( currentRenderTarget );
  30652. renderer.setMRT( currentMRT );
  30653. textureNode.value = currentTexture;
  30654. }
  30655. getTextureNode() {
  30656. return this._textureNode;
  30657. }
  30658. setup( builder ) {
  30659. const textureNode = this.textureNode;
  30660. if ( textureNode.isTextureNode !== true ) {
  30661. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30662. return vec4();
  30663. }
  30664. //
  30665. const uvNode = textureNode.uvNode || uv();
  30666. const directionNode = vec2( this.directionNode || 1 );
  30667. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30668. const blur = tslFn( () => {
  30669. const kernelSize = 3 + ( 2 * this.sigma );
  30670. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30671. const invSize = this._invSize;
  30672. const direction = directionNode.mul( this._passDirection );
  30673. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30674. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30675. for ( let i = 1; i < kernelSize; i ++ ) {
  30676. const x = float( i );
  30677. const w = float( gaussianCoefficients[ i ] );
  30678. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30679. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30680. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30681. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30682. weightSum.addAssign( mul( 2.0, w ) );
  30683. }
  30684. return diffuseSum.div( weightSum );
  30685. } );
  30686. //
  30687. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30688. material.fragmentNode = blur().context( builder.getSharedContext() );
  30689. material.needsUpdate = true;
  30690. //
  30691. const properties = builder.getNodeProperties( this );
  30692. properties.textureNode = textureNode;
  30693. //
  30694. return this._textureNode;
  30695. }
  30696. dispose() {
  30697. this._horizontalRT.dispose();
  30698. this._verticalRT.dispose();
  30699. }
  30700. _getCoefficients( kernelRadius ) {
  30701. const coefficients = [];
  30702. for ( let i = 0; i < kernelRadius; i ++ ) {
  30703. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  30704. }
  30705. return coefficients;
  30706. }
  30707. }
  30708. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( nodeObject( node ).toTexture(), directionNode, sigma ) );
  30709. addNodeElement( 'gaussianBlur', gaussianBlur );
  30710. const _size$3 = /*@__PURE__*/ new Vector2();
  30711. const _quadMeshComp = /*@__PURE__*/ new QuadMesh();
  30712. class AfterImageNode extends TempNode {
  30713. constructor( textureNode, damp = 0.96 ) {
  30714. super( textureNode );
  30715. this.textureNode = textureNode;
  30716. this.textureNodeOld = texture();
  30717. this.damp = uniform( damp );
  30718. this._compRT = new RenderTarget();
  30719. this._compRT.texture.name = 'AfterImageNode.comp';
  30720. this._oldRT = new RenderTarget();
  30721. this._oldRT.texture.name = 'AfterImageNode.old';
  30722. this._textureNode = passTexture( this, this._compRT.texture );
  30723. this.updateBeforeType = NodeUpdateType.RENDER;
  30724. }
  30725. getTextureNode() {
  30726. return this._textureNode;
  30727. }
  30728. setSize( width, height ) {
  30729. this._compRT.setSize( width, height );
  30730. this._oldRT.setSize( width, height );
  30731. }
  30732. updateBefore( frame ) {
  30733. const { renderer } = frame;
  30734. const textureNode = this.textureNode;
  30735. const map = textureNode.value;
  30736. const textureType = map.type;
  30737. this._compRT.texture.type = textureType;
  30738. this._oldRT.texture.type = textureType;
  30739. renderer.getDrawingBufferSize( _size$3 );
  30740. this.setSize( _size$3.x, _size$3.y );
  30741. const currentRenderTarget = renderer.getRenderTarget();
  30742. const currentTexture = textureNode.value;
  30743. this.textureNodeOld.value = this._oldRT.texture;
  30744. // comp
  30745. renderer.setRenderTarget( this._compRT );
  30746. _quadMeshComp.render( renderer );
  30747. // Swap the textures
  30748. const temp = this._oldRT;
  30749. this._oldRT = this._compRT;
  30750. this._compRT = temp;
  30751. renderer.setRenderTarget( currentRenderTarget );
  30752. textureNode.value = currentTexture;
  30753. }
  30754. setup( builder ) {
  30755. const textureNode = this.textureNode;
  30756. const textureNodeOld = this.textureNodeOld;
  30757. //
  30758. const uvNode = textureNode.uvNode || uv();
  30759. textureNodeOld.uvNode = uvNode;
  30760. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30761. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30762. const y = float( y_immutable ).toVar();
  30763. const x = vec4( x_immutable ).toVar();
  30764. return max$1( sign( x.sub( y ) ), 0.0 );
  30765. } );
  30766. const afterImg = tslFn( () => {
  30767. const texelOld = vec4( textureNodeOld );
  30768. const texelNew = vec4( sampleTexture( uvNode ) );
  30769. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30770. return max$1( texelNew, texelOld );
  30771. } );
  30772. //
  30773. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30774. materialComposed.fragmentNode = afterImg();
  30775. _quadMeshComp.material = materialComposed;
  30776. //
  30777. const properties = builder.getNodeProperties( this );
  30778. properties.textureNode = textureNode;
  30779. //
  30780. return this._textureNode;
  30781. }
  30782. dispose() {
  30783. this._compRT.dispose();
  30784. this._oldRT.dispose();
  30785. }
  30786. }
  30787. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ).toTexture(), damp ) );
  30788. addNodeElement( 'afterImage', afterImage );
  30789. const _quadMesh$3 = /*@__PURE__*/ new QuadMesh();
  30790. class AnamorphicNode extends TempNode {
  30791. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30792. super( 'vec4' );
  30793. this.textureNode = textureNode;
  30794. this.tresholdNode = tresholdNode;
  30795. this.scaleNode = scaleNode;
  30796. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30797. this.samples = samples;
  30798. this.resolution = new Vector2( 1, 1 );
  30799. this._renderTarget = new RenderTarget();
  30800. this._renderTarget.texture.name = 'anamorphic';
  30801. this._invSize = uniform( new Vector2() );
  30802. this._textureNode = passTexture( this, this._renderTarget.texture );
  30803. this.updateBeforeType = NodeUpdateType.RENDER;
  30804. }
  30805. getTextureNode() {
  30806. return this._textureNode;
  30807. }
  30808. setSize( width, height ) {
  30809. this._invSize.value.set( 1 / width, 1 / height );
  30810. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30811. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30812. this._renderTarget.setSize( width, height );
  30813. }
  30814. updateBefore( frame ) {
  30815. const { renderer } = frame;
  30816. const textureNode = this.textureNode;
  30817. const map = textureNode.value;
  30818. this._renderTarget.texture.type = map.type;
  30819. const currentRenderTarget = renderer.getRenderTarget();
  30820. const currentTexture = textureNode.value;
  30821. _quadMesh$3.material = this._material;
  30822. this.setSize( map.image.width, map.image.height );
  30823. // render
  30824. renderer.setRenderTarget( this._renderTarget );
  30825. _quadMesh$3.render( renderer );
  30826. // restore
  30827. renderer.setRenderTarget( currentRenderTarget );
  30828. textureNode.value = currentTexture;
  30829. }
  30830. setup( builder ) {
  30831. const textureNode = this.textureNode;
  30832. const uvNode = textureNode.uvNode || uv();
  30833. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30834. const anamorph = tslFn( () => {
  30835. const samples = this.samples;
  30836. const halfSamples = Math.floor( samples / 2 );
  30837. const total = vec3( 0 ).toVar();
  30838. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30839. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30840. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30841. const color = sampleTexture( uv );
  30842. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30843. total.addAssign( pass );
  30844. } );
  30845. return total.mul( this.colorNode );
  30846. } );
  30847. //
  30848. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30849. material.fragmentNode = anamorph();
  30850. //
  30851. const properties = builder.getNodeProperties( this );
  30852. properties.textureNode = textureNode;
  30853. //
  30854. return this._textureNode;
  30855. }
  30856. dispose() {
  30857. this._renderTarget.dispose();
  30858. }
  30859. }
  30860. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ).toTexture(), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30861. addNodeElement( 'anamorphic', anamorphic );
  30862. class SobelOperatorNode extends TempNode {
  30863. constructor( textureNode ) {
  30864. super();
  30865. this.textureNode = textureNode;
  30866. this.updateBeforeType = NodeUpdateType.RENDER;
  30867. this._invSize = uniform( new Vector2() );
  30868. }
  30869. updateBefore() {
  30870. const map = this.textureNode.value;
  30871. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30872. }
  30873. setup() {
  30874. const { textureNode } = this;
  30875. const uvNode = textureNode.uvNode || uv();
  30876. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30877. const sobel = tslFn( () => {
  30878. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30879. const texel = this._invSize;
  30880. // kernel definition (in glsl matrices are filled in column-major order)
  30881. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30882. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30883. // fetch the 3x3 neighbourhood of a fragment
  30884. // first column
  30885. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30886. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30887. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30888. // second column
  30889. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30890. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30891. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30892. // third column
  30893. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  30894. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  30895. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  30896. // gradient value in x direction
  30897. const valueGx = add(
  30898. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  30899. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  30900. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  30901. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  30902. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  30903. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  30904. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  30905. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  30906. Gx[ 2 ][ 2 ].mul( tx2y2 )
  30907. );
  30908. // gradient value in y direction
  30909. const valueGy = add(
  30910. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  30911. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  30912. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  30913. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  30914. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  30915. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  30916. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  30917. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  30918. Gy[ 2 ][ 2 ].mul( tx2y2 )
  30919. );
  30920. // magnitute of the total gradient
  30921. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  30922. return vec4( vec3( G ), 1 );
  30923. } );
  30924. const outputNode = sobel();
  30925. return outputNode;
  30926. }
  30927. }
  30928. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ).toTexture() ) );
  30929. addNodeElement( 'sobel', sobel );
  30930. class DepthOfFieldNode extends TempNode {
  30931. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  30932. super();
  30933. this.textureNode = textureNode;
  30934. this.viewZNode = viewZNode;
  30935. this.focusNode = focusNode;
  30936. this.apertureNode = apertureNode;
  30937. this.maxblurNode = maxblurNode;
  30938. this._aspect = uniform( 0 );
  30939. this.updateBeforeType = NodeUpdateType.RENDER;
  30940. }
  30941. updateBefore() {
  30942. const map = this.textureNode.value;
  30943. this._aspect.value = map.image.width / map.image.height;
  30944. }
  30945. setup() {
  30946. const textureNode = this.textureNode;
  30947. const uvNode = textureNode.uvNode || uv();
  30948. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30949. const dof = tslFn( () => {
  30950. const aspectcorrect = vec2( 1.0, this._aspect );
  30951. const factor = this.focusNode.add( this.viewZNode );
  30952. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  30953. const dofblur9 = dofblur.mul( 0.9 );
  30954. const dofblur7 = dofblur.mul( 0.7 );
  30955. const dofblur4 = dofblur.mul( 0.4 );
  30956. let col = vec4( 0.0 );
  30957. col = col.add( sampleTexture( uvNode ) );
  30958. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30959. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30960. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30961. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30962. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30963. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30964. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30965. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30966. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30967. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30968. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30969. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30970. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30971. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30972. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30973. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30974. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30975. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30976. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30977. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30978. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30979. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30980. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30981. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30982. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30983. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30984. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30985. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30986. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30987. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30988. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30989. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30990. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30991. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30992. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30993. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30994. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30995. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30996. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30997. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30998. col = col.div( 41 );
  30999. col.a = 1;
  31000. return vec4( col );
  31001. } );
  31002. const outputNode = dof();
  31003. return outputNode;
  31004. }
  31005. }
  31006. const dof = ( node, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) => nodeObject( new DepthOfFieldNode( nodeObject( node ).toTexture(), nodeObject( viewZNode ), nodeObject( focus ), nodeObject( aperture ), nodeObject( maxblur ) ) );
  31007. addNodeElement( 'dof', dof );
  31008. class DotScreenNode extends TempNode {
  31009. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  31010. super( 'vec4' );
  31011. this.inputNode = inputNode;
  31012. this.center = uniform( center );
  31013. this.angle = uniform( angle );
  31014. this.scale = uniform( scale );
  31015. this._size = uniform( new Vector2() );
  31016. this.updateBeforeType = NodeUpdateType.RENDER;
  31017. }
  31018. updateBefore( frame ) {
  31019. const { renderer } = frame;
  31020. renderer.getDrawingBufferSize( this._size.value );
  31021. }
  31022. setup() {
  31023. const inputNode = this.inputNode;
  31024. const pattern = tslFn( () => {
  31025. const s = sin( this.angle );
  31026. const c = cos( this.angle );
  31027. const tex = uv().mul( this._size ).sub( this.center );
  31028. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  31029. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  31030. } );
  31031. const dotScreen = tslFn( () => {
  31032. const color = inputNode;
  31033. const average = add( color.r, color.g, color.b ).div( 3 );
  31034. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  31035. } );
  31036. const outputNode = dotScreen();
  31037. return outputNode;
  31038. }
  31039. }
  31040. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  31041. addNodeElement( 'dotScreen', dotScreen );
  31042. class RGBShiftNode extends TempNode {
  31043. constructor( textureNode, amount = 0.005, angle = 0 ) {
  31044. super( 'vec4' );
  31045. this.textureNode = textureNode;
  31046. this.amount = uniform( amount );
  31047. this.angle = uniform( angle );
  31048. }
  31049. setup() {
  31050. const { textureNode } = this;
  31051. const uvNode = textureNode.uvNode || uv();
  31052. const sampleTexture = ( uv ) => textureNode.uv( uv );
  31053. const rgbShift = tslFn( () => {
  31054. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  31055. const cr = sampleTexture( uvNode.add( offset ) );
  31056. const cga = sampleTexture( uvNode );
  31057. const cb = sampleTexture( uvNode.sub( offset ) );
  31058. return vec4( cr.r, cga.g, cb.b, cga.a );
  31059. } );
  31060. return rgbShift();
  31061. }
  31062. }
  31063. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ).toTexture(), amount, angle ) );
  31064. addNodeElement( 'rgbShift', rgbShift );
  31065. class FilmNode extends TempNode {
  31066. constructor( inputNode, intensityNode = null, uvNode = null ) {
  31067. super();
  31068. this.inputNode = inputNode;
  31069. this.intensityNode = intensityNode;
  31070. this.uvNode = uvNode;
  31071. }
  31072. setup() {
  31073. const uvNode = this.uvNode || uv();
  31074. const film = tslFn( () => {
  31075. const base = this.inputNode.rgb;
  31076. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  31077. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  31078. if ( this.intensityNode !== null ) {
  31079. color = mix( base, color, this.intensityNode );
  31080. }
  31081. return vec4( color, this.inputNode.a );
  31082. } );
  31083. const outputNode = film();
  31084. return outputNode;
  31085. }
  31086. }
  31087. const film = nodeProxy( FilmNode );
  31088. addNodeElement( 'film', film );
  31089. class Lut3DNode extends TempNode {
  31090. constructor( inputNode, lutNode, size, intensityNode ) {
  31091. super();
  31092. this.inputNode = inputNode;
  31093. this.lutNode = lutNode;
  31094. this.size = uniform( size );
  31095. this.intensityNode = intensityNode;
  31096. }
  31097. setup() {
  31098. const { inputNode, lutNode } = this;
  31099. const sampleLut = ( uv ) => lutNode.uv( uv );
  31100. const lut3D = tslFn( () => {
  31101. const base = inputNode;
  31102. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  31103. const pixelWidth = float( 1.0 ).div( this.size );
  31104. const halfPixelWidth = float( 0.5 ).div( this.size );
  31105. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  31106. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  31107. return vec4( mix( base, lutValue, this.intensityNode ) );
  31108. } );
  31109. const outputNode = lut3D();
  31110. return outputNode;
  31111. }
  31112. }
  31113. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  31114. addNodeElement( 'lut3D', lut3D );
  31115. const _quadMesh$2 = /*@__PURE__*/ new QuadMesh();
  31116. const _currentClearColor$1 = /*@__PURE__*/ new Color();
  31117. const _size$2 = /*@__PURE__*/ new Vector2();
  31118. class GTAONode extends TempNode {
  31119. constructor( depthNode, normalNode, camera ) {
  31120. super();
  31121. this.depthNode = depthNode;
  31122. this.normalNode = normalNode;
  31123. this.radius = uniform( 0.25 );
  31124. this.resolution = uniform( new Vector2() );
  31125. this.thickness = uniform( 1 );
  31126. this.distanceExponent = uniform( 1 );
  31127. this.distanceFallOff = uniform( 1 );
  31128. this.scale = uniform( 1 );
  31129. this.noiseNode = texture( generateMagicSquareNoise() );
  31130. this.cameraProjectionMatrix = uniform( camera.projectionMatrix );
  31131. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  31132. this.SAMPLES = uniform( 16 );
  31133. this._aoRenderTarget = new RenderTarget();
  31134. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  31135. this._material = null;
  31136. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  31137. this.updateBeforeType = NodeUpdateType.FRAME;
  31138. }
  31139. getTextureNode() {
  31140. return this._textureNode;
  31141. }
  31142. setSize( width, height ) {
  31143. this.resolution.value.set( width, height );
  31144. this._aoRenderTarget.setSize( width, height );
  31145. }
  31146. updateBefore( frame ) {
  31147. const { renderer } = frame;
  31148. const size = renderer.getDrawingBufferSize( _size$2 );
  31149. const currentRenderTarget = renderer.getRenderTarget();
  31150. const currentMRT = renderer.getMRT();
  31151. renderer.getClearColor( _currentClearColor$1 );
  31152. const currentClearAlpha = renderer.getClearAlpha();
  31153. _quadMesh$2.material = this._material;
  31154. this.setSize( size.width, size.height );
  31155. // clear
  31156. renderer.setMRT( null );
  31157. renderer.setClearColor( 0xffffff, 1 );
  31158. // ao
  31159. renderer.setRenderTarget( this._aoRenderTarget );
  31160. _quadMesh$2.render( renderer );
  31161. // restore
  31162. renderer.setRenderTarget( currentRenderTarget );
  31163. renderer.setMRT( currentMRT );
  31164. renderer.setClearColor( _currentClearColor$1, currentClearAlpha );
  31165. }
  31166. setup( builder ) {
  31167. const uvNode = uv();
  31168. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  31169. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  31170. const getSceneUvAndDepth = tslFn( ( [ sampleViewPos ] )=> {
  31171. const sampleClipPos = this.cameraProjectionMatrix.mul( vec4( sampleViewPos, 1.0 ) );
  31172. let sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  31173. sampleUv = vec2( sampleUv.x, sampleUv.y.oneMinus() );
  31174. const sampleSceneDepth = sampleDepth( sampleUv );
  31175. return vec3( sampleUv, sampleSceneDepth );
  31176. } );
  31177. const getViewPosition = tslFn( ( [ screenPosition, depth ] ) => {
  31178. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31179. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31180. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  31181. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31182. } );
  31183. const ao = tslFn( () => {
  31184. const depth = sampleDepth( uvNode );
  31185. depth.greaterThanEqual( 1.0 ).discard();
  31186. const viewPosition = getViewPosition( uvNode, depth );
  31187. const viewNormal = this.normalNode.rgb.normalize();
  31188. const radiusToUse = this.radius;
  31189. const noiseResolution = textureSize( this.noiseNode, 0 );
  31190. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  31191. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  31192. const noiseTexel = sampleNoise( noiseUv );
  31193. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  31194. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  31195. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  31196. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  31197. const DIRECTIONS = this.SAMPLES.lessThan( 30 ).cond( 3, 5 );
  31198. const STEPS = add( this.SAMPLES, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS );
  31199. const ao = float( 0 ).toVar();
  31200. loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  31201. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI );
  31202. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  31203. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  31204. const viewDir = normalize( viewPosition.xyz.negate() );
  31205. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) );
  31206. const sliceTangent = cross( sliceBitangent, viewDir );
  31207. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  31208. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent );
  31209. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  31210. loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  31211. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  31212. // x
  31213. const sampleSceneUvDepthX = getSceneUvAndDepth( viewPosition.add( sampleViewOffset ) );
  31214. const sampleSceneViewPositionX = getViewPosition( sampleSceneUvDepthX.xy, sampleSceneUvDepthX.z );
  31215. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition );
  31216. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  31217. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  31218. cosHorizons.x.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  31219. } );
  31220. // y
  31221. const sampleSceneUvDepthY = getSceneUvAndDepth( viewPosition.sub( sampleViewOffset ) );
  31222. const sampleSceneViewPositionY = getViewPosition( sampleSceneUvDepthY.xy, sampleSceneUvDepthY.z );
  31223. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition );
  31224. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  31225. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  31226. cosHorizons.y.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  31227. } );
  31228. } );
  31229. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) );
  31230. const nx = dot( normalInSlice, sliceTangent );
  31231. const ny = dot( normalInSlice, viewDir );
  31232. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  31233. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  31234. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  31235. ao.addAssign( occlusion );
  31236. } );
  31237. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  31238. ao.assign( pow( ao, this.scale ) );
  31239. return vec4( vec3( ao ), 1.0 );
  31240. } );
  31241. const material = this._material || ( this._material = builder.createNodeMaterial() );
  31242. material.fragmentNode = ao().context( builder.getSharedContext() );
  31243. material.needsUpdate = true;
  31244. //
  31245. return this._textureNode;
  31246. }
  31247. dispose() {
  31248. this._aoRenderTarget.dispose();
  31249. }
  31250. }
  31251. function generateMagicSquareNoise( size = 5 ) {
  31252. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  31253. const magicSquare = generateMagicSquare( noiseSize );
  31254. const noiseSquareSize = magicSquare.length;
  31255. const data = new Uint8Array( noiseSquareSize * 4 );
  31256. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  31257. const iAng = magicSquare[ inx ];
  31258. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  31259. const randomVec = new Vector3(
  31260. Math.cos( angle ),
  31261. Math.sin( angle ),
  31262. 0
  31263. ).normalize();
  31264. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  31265. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  31266. data[ inx * 4 + 2 ] = 127;
  31267. data[ inx * 4 + 3 ] = 255;
  31268. }
  31269. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  31270. noiseTexture.wrapS = RepeatWrapping;
  31271. noiseTexture.wrapT = RepeatWrapping;
  31272. noiseTexture.needsUpdate = true;
  31273. return noiseTexture;
  31274. }
  31275. function generateMagicSquare( size ) {
  31276. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  31277. const noiseSquareSize = noiseSize * noiseSize;
  31278. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  31279. let i = Math.floor( noiseSize / 2 );
  31280. let j = noiseSize - 1;
  31281. for ( let num = 1; num <= noiseSquareSize; ) {
  31282. if ( i === - 1 && j === noiseSize ) {
  31283. j = noiseSize - 2;
  31284. i = 0;
  31285. } else {
  31286. if ( j === noiseSize ) {
  31287. j = 0;
  31288. }
  31289. if ( i < 0 ) {
  31290. i = noiseSize - 1;
  31291. }
  31292. }
  31293. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  31294. j -= 2;
  31295. i ++;
  31296. continue;
  31297. } else {
  31298. magicSquare[ i * noiseSize + j ] = num ++;
  31299. }
  31300. j ++;
  31301. i --;
  31302. }
  31303. return magicSquare;
  31304. }
  31305. const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
  31306. addNodeElement( 'ao', ao );
  31307. class DenoiseNode extends TempNode {
  31308. constructor( textureNode, depthNode, normalNode, noiseNode, camera ) {
  31309. super();
  31310. this.textureNode = textureNode;
  31311. this.depthNode = depthNode;
  31312. this.normalNode = normalNode;
  31313. this.noiseNode = noiseNode;
  31314. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  31315. this.lumaPhi = uniform( 5 );
  31316. this.depthPhi = uniform( 5 );
  31317. this.normalPhi = uniform( 5 );
  31318. this.radius = uniform( 5 );
  31319. this.index = uniform( 0 );
  31320. this._resolution = uniform( new Vector2() );
  31321. this._sampleVectors = uniforms( generatePdSamplePointInitializer( 16, 2, 1 ) );
  31322. this.updateBeforeType = NodeUpdateType.RENDER;
  31323. }
  31324. updateBefore() {
  31325. const map = this.textureNode.value;
  31326. this._resolution.value.set( map.image.width, map.image.height );
  31327. }
  31328. setup() {
  31329. const uvNode = uv();
  31330. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  31331. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  31332. const sampleNormal = ( uv ) => this.normalNode.uv( uv );
  31333. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  31334. const getViewPosition = tslFn( ( [ screenPosition, depth ] ) => {
  31335. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31336. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31337. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  31338. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31339. } );
  31340. const denoiseSample = tslFn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  31341. const texel = sampleTexture( sampleUv );
  31342. const depth = sampleDepth( sampleUv );
  31343. const normal = sampleNormal( sampleUv ).rgb.normalize();
  31344. const neighborColor = texel.rgb;
  31345. const viewPos = getViewPosition( sampleUv, depth );
  31346. const normalDiff = dot( viewNormal, normal ).toVar();
  31347. const normalSimilarity = pow( max$1( normalDiff, 0 ), this.normalPhi ).toVar();
  31348. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  31349. const lumaSimilarity = max$1( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  31350. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  31351. const depthSimilarity = max$1( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  31352. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  31353. return vec4( neighborColor.mul( w ), w );
  31354. } );
  31355. const denoise = tslFn( ( [ uvNode ] ) => {
  31356. const depth = sampleDepth( uvNode );
  31357. const viewNormal = sampleNormal( uvNode ).rgb.normalize();
  31358. const texel = sampleTexture( uvNode );
  31359. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  31360. return texel;
  31361. } );
  31362. const center = vec3( texel.rgb );
  31363. const viewPosition = getViewPosition( uvNode, depth );
  31364. const noiseResolution = textureSize( this.noiseNode, 0 );
  31365. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  31366. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  31367. const noiseTexel = sampleNoise( noiseUv );
  31368. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  31369. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  31370. const noiseVec = vec2( x, y );
  31371. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y );
  31372. const totalWeight = float( 1.0 ).toVar();
  31373. const denoised = vec3( texel.rgb ).toVar();
  31374. loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  31375. const sampleDir = this._sampleVectors.element( i ).toVar();
  31376. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
  31377. const sampleUv = uvNode.add( offset ).toVar();
  31378. const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  31379. denoised.addAssign( result.xyz );
  31380. totalWeight.addAssign( result.w );
  31381. } );
  31382. If( totalWeight.greaterThan( float( 0 ) ), () => {
  31383. denoised.divAssign( totalWeight );
  31384. } );
  31385. return vec4( denoised, texel.a );
  31386. } ).setLayout( {
  31387. name: 'denoise',
  31388. type: 'vec4',
  31389. inputs: [
  31390. { name: 'uv', type: 'vec2' }
  31391. ]
  31392. } );
  31393. const output = tslFn( () => {
  31394. return denoise( uvNode );
  31395. } );
  31396. const outputNode = output();
  31397. return outputNode;
  31398. }
  31399. }
  31400. function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
  31401. const poissonDisk = generateDenoiseSamples( samples, rings, radiusExponent );
  31402. const array = [];
  31403. for ( let i = 0; i < samples; i ++ ) {
  31404. const sample = poissonDisk[ i ];
  31405. array.push( sample );
  31406. }
  31407. return array;
  31408. }
  31409. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  31410. const samples = [];
  31411. for ( let i = 0; i < numSamples; i ++ ) {
  31412. const angle = 2 * Math.PI * numRings * i / numSamples;
  31413. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  31414. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  31415. }
  31416. return samples;
  31417. }
  31418. const denoise = ( node, depthNode, normalNode, noiseNode, camera ) => nodeObject( new DenoiseNode( nodeObject( node ).toTexture(), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( noiseNode ), camera ) );
  31419. addNodeElement( 'denoise', denoise );
  31420. class FXAANode extends TempNode {
  31421. constructor( textureNode ) {
  31422. super();
  31423. this.textureNode = textureNode;
  31424. this.updateBeforeType = NodeUpdateType.RENDER;
  31425. this._invSize = uniform( new Vector2() );
  31426. }
  31427. updateBefore() {
  31428. const map = this.textureNode.value;
  31429. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  31430. }
  31431. setup() {
  31432. const textureNode = this.textureNode.bias( - 100 );
  31433. const uvNode = textureNode.uvNode || uv();
  31434. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro ([email protected])
  31435. //----------------------------------------------------------------------------------
  31436. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  31437. // SDK Version: v3.00
  31438. // Email: [email protected]
  31439. // Site: http://developer.nvidia.com/
  31440. //
  31441. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  31442. //
  31443. // Redistribution and use in source and binary forms, with or without
  31444. // modification, are permitted provided that the following conditions
  31445. // are met:
  31446. // * Redistributions of source code must retain the above copyright
  31447. // notice, this list of conditions and the following disclaimer.
  31448. // * Redistributions in binary form must reproduce the above copyright
  31449. // notice, this list of conditions and the following disclaimer in the
  31450. // documentation and/or other materials provided with the distribution.
  31451. // * Neither the name of NVIDIA CORPORATION nor the names of its
  31452. // contributors may be used to endorse or promote products derived
  31453. // from this software without specific prior written permission.
  31454. //
  31455. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  31456. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  31457. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  31458. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  31459. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  31460. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  31461. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  31462. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  31463. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31464. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31465. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31466. //
  31467. //----------------------------------------------------------------------------------
  31468. const FxaaTexTop = ( p ) => textureNode.uv( p );
  31469. const FxaaTexOff = ( p, o, r ) => textureNode.uv( p.add( o.mul( r ) ) );
  31470. const NUM_SAMPLES = int( 5 );
  31471. const contrast = tslFn( ( [ a_immutable, b_immutable ] ) => {
  31472. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  31473. const b = vec4( b_immutable ).toVar();
  31474. const a = vec4( a_immutable ).toVar();
  31475. const diff = vec4( abs( a.sub( b ) ) ).toVar();
  31476. return max$1( max$1( max$1( diff.r, diff.g ), diff.b ), diff.a );
  31477. } );
  31478. // FXAA3 QUALITY - PC
  31479. const FxaaPixelShader = tslFn( ( [ uv, fxaaQualityRcpFrame, fxaaQualityEdgeThreshold, fxaaQualityinvEdgeThreshold ] ) => {
  31480. const rgbaM = FxaaTexTop( uv ).toVar();
  31481. const rgbaS = FxaaTexOff( uv, vec2( 0.0, - 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31482. const rgbaE = FxaaTexOff( uv, vec2( 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31483. const rgbaN = FxaaTexOff( uv, vec2( 0.0, 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31484. const rgbaW = FxaaTexOff( uv, vec2( - 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31485. // . S .
  31486. // W M E
  31487. // . N .
  31488. const contrastN = contrast( rgbaM, rgbaN ).toVar();
  31489. const contrastS = contrast( rgbaM, rgbaS ).toVar();
  31490. const contrastE = contrast( rgbaM, rgbaE ).toVar();
  31491. const contrastW = contrast( rgbaM, rgbaW ).toVar();
  31492. const maxValue = max$1( contrastN, max$1( contrastS, max$1( contrastE, contrastW ) ) ).toVar();
  31493. // . 0 .
  31494. // 0 0 0
  31495. // . 0 .
  31496. If( maxValue.lessThan( fxaaQualityEdgeThreshold ), () => {
  31497. return rgbaM; // assuming define FXAA_DISCARD is always 0
  31498. } );
  31499. //
  31500. const relativeVContrast = sub( contrastN.add( contrastS ), ( contrastE.add( contrastW ) ) ).toVar();
  31501. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  31502. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  31503. If( abs( relativeVContrast ).lessThan( 0.3 ), () => {
  31504. // locate the edge
  31505. const x = contrastE.greaterThan( contrastW ).cond( 1, - 1 ).toVar();
  31506. const y = contrastS.greaterThan( contrastN ).cond( 1, - 1 ).toVar();
  31507. const dirToEdge = vec2( x, y ).toVar();
  31508. // . 2 . . 1 .
  31509. // 1 0 2 ~= 0 0 1
  31510. // . 1 . . 0 .
  31511. // tap 2 pixels and see which ones are "outside" the edge, to
  31512. // determine if the edge is vertical or horizontal
  31513. const rgbaAlongH = FxaaTexOff( uv, vec2( dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy );
  31514. const matchAlongH = contrast( rgbaM, rgbaAlongH ).toVar();
  31515. // . 1 .
  31516. // 0 0 1
  31517. // . 0 H
  31518. const rgbaAlongV = FxaaTexOff( uv, vec2( dirToEdge.x.negate(), dirToEdge.y.negate() ), fxaaQualityRcpFrame.xy );
  31519. const matchAlongV = contrast( rgbaM, rgbaAlongV ).toVar();
  31520. // V 1 .
  31521. // 0 0 1
  31522. // . 0 .
  31523. relativeVContrast.assign( matchAlongV.sub( matchAlongH ) );
  31524. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  31525. If( abs( relativeVContrast ).lessThan( 0.3 ), () => { // 45 deg edge
  31526. // 1 1 .
  31527. // 0 0 1
  31528. // . 0 1
  31529. // do a simple blur
  31530. const sum = rgbaN.add( rgbaS ).add( rgbaE ).add( rgbaW );
  31531. return mix( rgbaM, sum.mul( 0.25 ), 0.4 );
  31532. } );
  31533. } );
  31534. const offNP = vec2().toVar();
  31535. If( relativeVContrast.lessThanEqual( 0 ), () => {
  31536. rgbaN.assign( rgbaW );
  31537. rgbaS.assign( rgbaE );
  31538. // . 0 . 1
  31539. // 1 0 1 -> 0
  31540. // . 0 . 1
  31541. offNP.x.assign( 0 );
  31542. offNP.y.assign( fxaaQualityRcpFrame.y );
  31543. } ).else( () => {
  31544. offNP.x.assign( fxaaQualityRcpFrame.x );
  31545. offNP.y.assign( 0 );
  31546. } );
  31547. const mn = contrast( rgbaM, rgbaN ).toVar();
  31548. const ms = contrast( rgbaM, rgbaS ).toVar();
  31549. If( mn.lessThanEqual( ms ), () => {
  31550. rgbaN.assign( rgbaS );
  31551. } );
  31552. const doneN = int( 0 ).toVar();
  31553. const doneP = int( 0 ).toVar();
  31554. const nDist = float( 0 ).toVar();
  31555. const pDist = float( 0 ).toVar();
  31556. const posN = vec2( uv ).toVar();
  31557. const posP = vec2( uv ).toVar();
  31558. const iterationsUsedN = int( 0 ).toVar();
  31559. const iterationsUsedP = int( 0 ).toVar();
  31560. loop( NUM_SAMPLES, ( { i } ) => {
  31561. const increment = i.add( 1 ).toVar();
  31562. If( doneN.equal( 0 ), () => {
  31563. nDist.addAssign( increment );
  31564. posN.assign( uv.add( offNP.mul( nDist ) ) );
  31565. const rgbaEndN = FxaaTexTop( posN.xy );
  31566. const nm = contrast( rgbaEndN, rgbaM ).toVar();
  31567. const nn = contrast( rgbaEndN, rgbaN ).toVar();
  31568. If( nm.greaterThan( nn ), () => {
  31569. doneN.assign( 1 );
  31570. } );
  31571. iterationsUsedN.assign( i );
  31572. } );
  31573. If( doneP.equal( 0 ), () => {
  31574. pDist.addAssign( increment );
  31575. posP.assign( uv.sub( offNP.mul( pDist ) ) );
  31576. const rgbaEndP = FxaaTexTop( posP.xy );
  31577. const pm = contrast( rgbaEndP, rgbaM ).toVar();
  31578. const pn = contrast( rgbaEndP, rgbaN ).toVar();
  31579. If( pm.greaterThan( pn ), () => {
  31580. doneP.assign( 1 );
  31581. } );
  31582. iterationsUsedP.assign( i );
  31583. } );
  31584. If( doneN.equal( 1 ).or( doneP.equal( 1 ) ), () => {
  31585. Break();
  31586. } );
  31587. } );
  31588. If( doneN.equal( 0 ).and( doneP.equal( 0 ) ), () => {
  31589. return rgbaM; // failed to find end of edge
  31590. } );
  31591. const distN = float( 1 ).toVar();
  31592. const distP = float( 1 ).toVar();
  31593. If( doneN.equal( 1 ), () => {
  31594. distN.assign( float( iterationsUsedN ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  31595. } );
  31596. If( doneP.equal( 1 ), () => {
  31597. distP.assign( float( iterationsUsedP ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  31598. } );
  31599. const dist = min$1( distN, distP );
  31600. // hacky way of reduces blurriness of mostly diagonal edges
  31601. // but reduces AA quality
  31602. dist.assign( pow( dist, 0.5 ) );
  31603. dist.assign( float( 1 ).sub( dist ) );
  31604. return mix( rgbaM, rgbaN, dist.mul( 0.5 ) );
  31605. } ).setLayout( {
  31606. name: 'FxaaPixelShader',
  31607. type: 'vec4',
  31608. inputs: [
  31609. { name: 'uv', type: 'vec2' },
  31610. { name: 'fxaaQualityRcpFrame', type: 'vec2' },
  31611. { name: 'fxaaQualityEdgeThreshold', type: 'float' },
  31612. { name: 'fxaaQualityinvEdgeThreshold', type: 'float' },
  31613. ]
  31614. } );
  31615. const fxaa = tslFn( () => {
  31616. const edgeDetectionQuality = float( 0.2 );
  31617. const invEdgeDetectionQuality = float( 1 ).div( edgeDetectionQuality );
  31618. return FxaaPixelShader( uvNode, this._invSize, edgeDetectionQuality, invEdgeDetectionQuality );
  31619. } );
  31620. const outputNode = fxaa();
  31621. return outputNode;
  31622. }
  31623. }
  31624. const fxaa = ( node ) => nodeObject( new FXAANode( nodeObject( node ).toTexture() ) );
  31625. addNodeElement( 'fxaa', fxaa );
  31626. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  31627. const _clearColor$1 = /*@__PURE__*/ new Color( 0, 0, 0 );
  31628. const _currentClearColor = /*@__PURE__*/ new Color();
  31629. const _size$1 = /*@__PURE__*/ new Vector2();
  31630. const _BlurDirectionX = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
  31631. const _BlurDirectionY = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
  31632. class BloomNode extends TempNode {
  31633. constructor( inputNode, strength = 1, radius = 0, threshold = 0 ) {
  31634. super();
  31635. this.inputNode = inputNode;
  31636. this.strength = uniform( strength );
  31637. this.radius = uniform( radius );
  31638. this.threshold = uniform( threshold );
  31639. this.smoothWidth = uniform( 0.01 );
  31640. //
  31641. this._renderTargetsHorizontal = [];
  31642. this._renderTargetsVertical = [];
  31643. this._nMips = 5;
  31644. // render targets
  31645. this._renderTargetBright = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31646. this._renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  31647. this._renderTargetBright.texture.generateMipmaps = false;
  31648. for ( let i = 0; i < this._nMips; i ++ ) {
  31649. const renderTargetHorizontal = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31650. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  31651. renderTargetHorizontal.texture.generateMipmaps = false;
  31652. this._renderTargetsHorizontal.push( renderTargetHorizontal );
  31653. const renderTargetVertical = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31654. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  31655. renderTargetVertical.texture.generateMipmaps = false;
  31656. this._renderTargetsVertical.push( renderTargetVertical );
  31657. }
  31658. // materials
  31659. this._compositeMaterial = null;
  31660. this._highPassFilterMaterial = null;
  31661. this._separableBlurMaterials = [];
  31662. // pass and texture nodes
  31663. this._textureNodeBright = texture( this._renderTargetBright.texture );
  31664. this._textureNodeBlur0 = texture( this._renderTargetsVertical[ 0 ].texture );
  31665. this._textureNodeBlur1 = texture( this._renderTargetsVertical[ 1 ].texture );
  31666. this._textureNodeBlur2 = texture( this._renderTargetsVertical[ 2 ].texture );
  31667. this._textureNodeBlur3 = texture( this._renderTargetsVertical[ 3 ].texture );
  31668. this._textureNodeBlur4 = texture( this._renderTargetsVertical[ 4 ].texture );
  31669. this._textureOutput = passTexture( this, this._renderTargetsHorizontal[ 0 ].texture );
  31670. this.updateBeforeType = NodeUpdateType.FRAME;
  31671. }
  31672. getTextureNode() {
  31673. return this._textureOutput;
  31674. }
  31675. setSize( width, height ) {
  31676. let resx = Math.round( width / 2 );
  31677. let resy = Math.round( height / 2 );
  31678. this._renderTargetBright.setSize( resx, resy );
  31679. for ( let i = 0; i < this._nMips; i ++ ) {
  31680. this._renderTargetsHorizontal[ i ].setSize( resx, resy );
  31681. this._renderTargetsVertical[ i ].setSize( resx, resy );
  31682. this._separableBlurMaterials[ i ].invSize.value.set( 1 / resx, 1 / resy );
  31683. resx = Math.round( resx / 2 );
  31684. resy = Math.round( resy / 2 );
  31685. }
  31686. }
  31687. updateBefore( frame ) {
  31688. const { renderer } = frame;
  31689. const size = renderer.getDrawingBufferSize( _size$1 );
  31690. this.setSize( size.width, size.height );
  31691. const currentRenderTarget = renderer.getRenderTarget();
  31692. const currentMRT = renderer.getMRT();
  31693. renderer.getClearColor( _currentClearColor );
  31694. const currentClearAlpha = renderer.getClearAlpha();
  31695. this.setSize( size.width, size.height );
  31696. renderer.setMRT( null );
  31697. renderer.setClearColor( _clearColor$1, 0 );
  31698. // 1. Extract Bright Areas
  31699. renderer.setRenderTarget( this._renderTargetBright );
  31700. _quadMesh$1.material = this._highPassFilterMaterial;
  31701. _quadMesh$1.render( renderer );
  31702. // 2. Blur All the mips progressively
  31703. let inputRenderTarget = this._renderTargetBright;
  31704. for ( let i = 0; i < this._nMips; i ++ ) {
  31705. _quadMesh$1.material = this._separableBlurMaterials[ i ];
  31706. this._separableBlurMaterials[ i ].colorTexture.value = inputRenderTarget.texture;
  31707. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionX;
  31708. renderer.setRenderTarget( this._renderTargetsHorizontal[ i ] );
  31709. renderer.clear();
  31710. _quadMesh$1.render( renderer );
  31711. this._separableBlurMaterials[ i ].colorTexture.value = this._renderTargetsHorizontal[ i ].texture;
  31712. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionY;
  31713. renderer.setRenderTarget( this._renderTargetsVertical[ i ] );
  31714. renderer.clear();
  31715. _quadMesh$1.render( renderer );
  31716. inputRenderTarget = this._renderTargetsVertical[ i ];
  31717. }
  31718. // 3. Composite All the mips
  31719. renderer.setRenderTarget( this._renderTargetsHorizontal[ 0 ] );
  31720. renderer.clear();
  31721. _quadMesh$1.material = this._compositeMaterial;
  31722. _quadMesh$1.render( renderer );
  31723. // restore
  31724. renderer.setRenderTarget( currentRenderTarget );
  31725. renderer.setMRT( currentMRT );
  31726. renderer.setClearColor( _currentClearColor, currentClearAlpha );
  31727. }
  31728. setup( builder ) {
  31729. // luminosity high pass material
  31730. const luminosityHighPass = tslFn( () => {
  31731. const texel = this.inputNode;
  31732. const v = luminance( texel.rgb );
  31733. const alpha = smoothstep( this.threshold, this.threshold.add( this.smoothWidth ), v );
  31734. return mix( vec4( 0 ), texel, alpha );
  31735. } );
  31736. this._highPassFilterMaterial = this._highPassFilterMaterial || builder.createNodeMaterial();
  31737. this._highPassFilterMaterial.fragmentNode = luminosityHighPass().context( builder.getSharedContext() );
  31738. this._highPassFilterMaterial.needsUpdate = true;
  31739. // gaussian blur materials
  31740. const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
  31741. for ( let i = 0; i < this._nMips; i ++ ) {
  31742. this._separableBlurMaterials.push( this._getSeperableBlurMaterial( builder, kernelSizeArray[ i ] ) );
  31743. }
  31744. // composite material
  31745. const bloomFactors = uniforms( [ 1.0, 0.8, 0.6, 0.4, 0.2 ] );
  31746. const bloomTintColors = uniforms( [ 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 ) ] );
  31747. const lerpBloomFactor = tslFn( ( [ factor, radius ] ) => {
  31748. const mirrorFactor = float( 1.2 ).sub( factor );
  31749. return mix( factor, mirrorFactor, radius );
  31750. } ).setLayout( {
  31751. name: 'lerpBloomFactor',
  31752. type: 'float',
  31753. inputs: [
  31754. { name: 'factor', type: 'float' },
  31755. { name: 'radius', type: 'float' },
  31756. ]
  31757. } );
  31758. const compositePass = tslFn( () => {
  31759. const color0 = lerpBloomFactor( bloomFactors.element( 0 ), this.radius ).mul( vec4( bloomTintColors.element( 0 ), 1.0 ) ).mul( this._textureNodeBlur0 );
  31760. const color1 = lerpBloomFactor( bloomFactors.element( 1 ), this.radius ).mul( vec4( bloomTintColors.element( 1 ), 1.0 ) ).mul( this._textureNodeBlur1 );
  31761. const color2 = lerpBloomFactor( bloomFactors.element( 2 ), this.radius ).mul( vec4( bloomTintColors.element( 2 ), 1.0 ) ).mul( this._textureNodeBlur2 );
  31762. const color3 = lerpBloomFactor( bloomFactors.element( 3 ), this.radius ).mul( vec4( bloomTintColors.element( 3 ), 1.0 ) ).mul( this._textureNodeBlur3 );
  31763. const color4 = lerpBloomFactor( bloomFactors.element( 4 ), this.radius ).mul( vec4( bloomTintColors.element( 4 ), 1.0 ) ).mul( this._textureNodeBlur4 );
  31764. const sum = color0.add( color1 ).add( color2 ).add( color3 ).add( color4 );
  31765. return sum.mul( this.strength );
  31766. } );
  31767. this._compositeMaterial = this._compositeMaterial || builder.createNodeMaterial();
  31768. this._compositeMaterial.fragmentNode = compositePass().context( builder.getSharedContext() );
  31769. this._compositeMaterial.needsUpdate = true;
  31770. //
  31771. return this._textureOutput;
  31772. }
  31773. dispose() {
  31774. for ( let i = 0; i < this._renderTargetsHorizontal.length; i ++ ) {
  31775. this._renderTargetsHorizontal[ i ].dispose();
  31776. }
  31777. for ( let i = 0; i < this._renderTargetsVertical.length; i ++ ) {
  31778. this._renderTargetsVertical[ i ].dispose();
  31779. }
  31780. this._renderTargetBright.dispose();
  31781. }
  31782. _getSeperableBlurMaterial( builder, kernelRadius ) {
  31783. const coefficients = [];
  31784. for ( let i = 0; i < kernelRadius; i ++ ) {
  31785. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  31786. }
  31787. //
  31788. const colorTexture = texture();
  31789. const gaussianCoefficients = uniforms( coefficients );
  31790. const invSize = uniform( new Vector2() );
  31791. const direction = uniform( new Vector2( 0.5, 0.5 ) );
  31792. const uvNode = uv();
  31793. const sampleTexel = ( uv ) => colorTexture.uv( uv );
  31794. const seperableBlurPass = tslFn( () => {
  31795. const weightSum = gaussianCoefficients.element( 0 ).toVar();
  31796. const diffuseSum = sampleTexel( uvNode ).rgb.mul( weightSum ).toVar();
  31797. loop( { start: int( 1 ), end: int( kernelRadius ), type: 'int', condition: '<' }, ( { i } ) => {
  31798. const x = float( i );
  31799. const w = gaussianCoefficients.element( i );
  31800. const uvOffset = direction.mul( invSize ).mul( x );
  31801. const sample1 = sampleTexel( uvNode.add( uvOffset ) ).rgb;
  31802. const sample2 = sampleTexel( uvNode.sub( uvOffset ) ).rgb;
  31803. diffuseSum.addAssign( add( sample1, sample2 ).mul( w ) );
  31804. weightSum.addAssign( float( 2.0 ).mul( w ) );
  31805. } );
  31806. return vec4( diffuseSum.div( weightSum ), 1.0 );
  31807. } );
  31808. const seperableBlurMaterial = builder.createNodeMaterial();
  31809. seperableBlurMaterial.fragmentNode = seperableBlurPass().context( builder.getSharedContext() );
  31810. seperableBlurMaterial.needsUpdate = true;
  31811. // uniforms
  31812. seperableBlurMaterial.colorTexture = colorTexture;
  31813. seperableBlurMaterial.direction = direction;
  31814. seperableBlurMaterial.invSize = invSize;
  31815. return seperableBlurMaterial;
  31816. }
  31817. }
  31818. const bloom = ( node, strength, radius, threshold ) => nodeObject( new BloomNode( nodeObject( node ), strength, radius, threshold ) );
  31819. addNodeElement( 'bloom', bloom );
  31820. class TransitionNode extends TempNode {
  31821. constructor( textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode ) {
  31822. super();
  31823. // Input textures
  31824. this.textureNodeA = textureNodeA;
  31825. this.textureNodeB = textureNodeB;
  31826. this.mixTextureNode = mixTextureNode;
  31827. // Uniforms
  31828. this.mixRatioNode = mixRatioNode;
  31829. this.thresholdNode = thresholdNode;
  31830. this.useTextureNode = useTextureNode;
  31831. }
  31832. setup() {
  31833. const { textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode } = this;
  31834. const sampleTexture = ( textureNode ) => {
  31835. const uvNodeTexture = textureNode.uvNode || uv();
  31836. return textureNode.uv( uvNodeTexture );
  31837. };
  31838. const transition = tslFn( () => {
  31839. const texelOne = sampleTexture( textureNodeA );
  31840. const texelTwo = sampleTexture( textureNodeB );
  31841. const color = vec4().toVar();
  31842. If( useTextureNode.equal( int( 1 ) ), () => {
  31843. const transitionTexel = sampleTexture( mixTextureNode );
  31844. const r = mixRatioNode.mul( thresholdNode.mul( 2.0 ).add( 1.0 ) ).sub( thresholdNode );
  31845. const mixf = clamp( sub( transitionTexel.r, r ).mul( float( 1.0 ).div( thresholdNode ) ), 0.0, 1.0 );
  31846. color.assign( mix( texelOne, texelTwo, mixf ) );
  31847. } ).else( () => {
  31848. color.assign( mix( texelTwo, texelOne, mixRatioNode ) );
  31849. } );
  31850. return color;
  31851. } );
  31852. const outputNode = transition();
  31853. return outputNode;
  31854. }
  31855. }
  31856. const transition = ( nodeA, nodeB, mixTexture, mixRatio = 0.0, threshold = 0.1, useTexture = 0 ) => nodeObject( new TransitionNode( nodeObject( nodeA ).toTexture(), nodeObject( nodeB ).toTexture(), nodeObject( mixTexture ).toTexture(), nodeObject( mixRatio ), nodeObject( threshold ), nodeObject( useTexture ) ) );
  31857. addNodeElement( 'transition', transition );
  31858. class RenderOutputNode extends TempNode {
  31859. constructor( colorNode, toneMapping, outputColorSpace ) {
  31860. super( 'vec4' );
  31861. this.colorNode = colorNode;
  31862. this.toneMapping = toneMapping;
  31863. this.outputColorSpace = outputColorSpace;
  31864. this.isRenderOutput = true;
  31865. }
  31866. setup( { context } ) {
  31867. let outputNode = this.colorNode || context.color;
  31868. // tone mapping
  31869. const toneMapping = this.toneMapping !== null ? this.toneMapping : context.toneMapping;
  31870. const outputColorSpace = this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace;
  31871. if ( toneMapping !== NoToneMapping ) {
  31872. outputNode = outputNode.toneMapping( toneMapping );
  31873. }
  31874. // output color space
  31875. if ( outputColorSpace === SRGBColorSpace ) {
  31876. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  31877. }
  31878. return outputNode;
  31879. }
  31880. }
  31881. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  31882. addNodeElement( 'renderOutput', renderOutput );
  31883. addNodeClass( 'RenderOutputNode', RenderOutputNode );
  31884. class PixelationNode extends TempNode {
  31885. constructor( textureNode, depthNode, normalNode, pixelSize, normalEdgeStrength, depthEdgeStrength ) {
  31886. super();
  31887. // Input textures
  31888. this.textureNode = textureNode;
  31889. this.depthNode = depthNode;
  31890. this.normalNode = normalNode;
  31891. // Input uniforms
  31892. this.pixelSize = pixelSize;
  31893. this.normalEdgeStrength = normalEdgeStrength;
  31894. this.depthEdgeStrength = depthEdgeStrength;
  31895. // Private uniforms
  31896. this._resolution = uniform( new Vector4() );
  31897. this.updateBeforeType = NodeUpdateType.RENDER;
  31898. }
  31899. updateBefore() {
  31900. const map = this.textureNode.value;
  31901. const width = map.image.width;
  31902. const height = map.image.height;
  31903. this._resolution.value.set( width, height, 1 / width, 1 / height );
  31904. }
  31905. setup() {
  31906. const { textureNode, depthNode, normalNode } = this;
  31907. const uvNodeTexture = textureNode.uvNode || uv();
  31908. const uvNodeDepth = depthNode.uvNode || uv();
  31909. const uvNodeNormal = normalNode.uvNode || uv();
  31910. const sampleTexture = () => textureNode.uv( uvNodeTexture );
  31911. const sampleDepth = ( x, y ) => depthNode.uv( uvNodeDepth.add( vec2( x, y ).mul( this._resolution.zw ) ) ).r;
  31912. const sampleNormal = ( x, y ) => normalNode.uv( uvNodeNormal.add( vec2( x, y ).mul( this._resolution.zw ) ) ).rgb.normalize();
  31913. const depthEdgeIndicator = ( depth ) => {
  31914. const diff = property( 'float', 'diff' );
  31915. diff.addAssign( clamp( sampleDepth( 1, 0 ).sub( depth ) ) );
  31916. diff.addAssign( clamp( sampleDepth( - 1, 0 ).sub( depth ) ) );
  31917. diff.addAssign( clamp( sampleDepth( 0, 1 ).sub( depth ) ) );
  31918. diff.addAssign( clamp( sampleDepth( 0, - 1 ).sub( depth ) ) );
  31919. return floor( smoothstep( 0.01, 0.02, diff ).mul( 2 ) ).div( 2 );
  31920. };
  31921. const neighborNormalEdgeIndicator = ( x, y, depth, normal ) => {
  31922. const depthDiff = sampleDepth( x, y ).sub( depth );
  31923. const neighborNormal = sampleNormal( x, y );
  31924. // Edge pixels should yield to faces who's normals are closer to the bias normal.
  31925. const normalEdgeBias = vec3( 1, 1, 1 ); // This should probably be a parameter.
  31926. const normalDiff = dot( normal.sub( neighborNormal ), normalEdgeBias );
  31927. const normalIndicator = clamp( smoothstep( - 0.01, 0.01, normalDiff ), 0.0, 1.0 );
  31928. // Only the shallower pixel should detect the normal edge.
  31929. const depthIndicator = clamp( sign( depthDiff.mul( .25 ).add( .0025 ) ), 0.0, 1.0 );
  31930. return float( 1.0 ).sub( dot( normal, neighborNormal ) ).mul( depthIndicator ).mul( normalIndicator );
  31931. };
  31932. const normalEdgeIndicator = ( depth, normal ) => {
  31933. const indicator = property( 'float', 'indicator' );
  31934. indicator.addAssign( neighborNormalEdgeIndicator( 0, - 1, depth, normal ) );
  31935. indicator.addAssign( neighborNormalEdgeIndicator( 0, 1, depth, normal ) );
  31936. indicator.addAssign( neighborNormalEdgeIndicator( - 1, 0, depth, normal ) );
  31937. indicator.addAssign( neighborNormalEdgeIndicator( 1, 0, depth, normal ) );
  31938. return step( 0.1, indicator );
  31939. };
  31940. const pixelation = tslFn( () => {
  31941. const texel = sampleTexture();
  31942. const depth = property( 'float', 'depth' );
  31943. const normal = property( 'vec3', 'normal' );
  31944. If( this.depthEdgeStrength.greaterThan( 0.0 ).or( this.normalEdgeStrength.greaterThan( 0.0 ) ), () => {
  31945. depth.assign( sampleDepth( 0, 0 ) );
  31946. normal.assign( sampleNormal( 0, 0 ) );
  31947. } );
  31948. const dei = property( 'float', 'dei' );
  31949. If( this.depthEdgeStrength.greaterThan( 0.0 ), () => {
  31950. dei.assign( depthEdgeIndicator( depth ) );
  31951. } );
  31952. const nei = property( 'float', 'nei' );
  31953. If( this.normalEdgeStrength.greaterThan( 0.0 ), () => {
  31954. nei.assign( normalEdgeIndicator( depth, normal ) );
  31955. } );
  31956. const strength = dei.greaterThan( 0 ).cond( float( 1.0 ).sub( dei.mul( this.depthEdgeStrength ) ), nei.mul( this.normalEdgeStrength ).add( 1 ) );
  31957. return texel.mul( strength );
  31958. } );
  31959. const outputNode = pixelation();
  31960. return outputNode;
  31961. }
  31962. }
  31963. const pixelation = ( node, depthNode, normalNode, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) => nodeObject( new PixelationNode( nodeObject( node ).toTexture(), nodeObject( depthNode ).toTexture(), nodeObject( normalNode ).toTexture(), nodeObject( pixelSize ), nodeObject( normalEdgeStrength ), nodeObject( depthEdgeStrength ) ) );
  31964. addNodeElement( 'pixelation', pixelation );
  31965. class PixelationPassNode extends PassNode {
  31966. constructor( scene, camera, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) {
  31967. super( 'color', scene, camera, { minFilter: NearestFilter, magFilter: NearestFilter } );
  31968. this.pixelSize = pixelSize;
  31969. this.normalEdgeStrength = normalEdgeStrength;
  31970. this.depthEdgeStrength = depthEdgeStrength;
  31971. this.isPixelationPassNode = true;
  31972. this._mrt = mrt( {
  31973. output: output,
  31974. normal: normalView
  31975. } );
  31976. }
  31977. setSize( width, height ) {
  31978. const pixelSize = this.pixelSize.value ? this.pixelSize.value : this.pixelSize;
  31979. const adjustedWidth = Math.floor( width / pixelSize );
  31980. const adjustedHeight = Math.floor( height / pixelSize );
  31981. super.setSize( adjustedWidth, adjustedHeight );
  31982. }
  31983. setup() {
  31984. const color = super.getTextureNode( 'output' );
  31985. const depth = super.getTextureNode( 'depth' );
  31986. const normal = super.getTextureNode( 'normal' );
  31987. return pixelation( color, depth, normal, this.pixelSize, this.normalEdgeStrength, this.depthEdgeStrength );
  31988. }
  31989. }
  31990. const pixelationPass = ( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) => nodeObject( new PixelationPassNode( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) );
  31991. class FunctionCallNode extends TempNode {
  31992. constructor( functionNode = null, parameters = {} ) {
  31993. super();
  31994. this.functionNode = functionNode;
  31995. this.parameters = parameters;
  31996. }
  31997. setParameters( parameters ) {
  31998. this.parameters = parameters;
  31999. return this;
  32000. }
  32001. getParameters() {
  32002. return this.parameters;
  32003. }
  32004. getNodeType( builder ) {
  32005. return this.functionNode.getNodeType( builder );
  32006. }
  32007. generate( builder ) {
  32008. const params = [];
  32009. const functionNode = this.functionNode;
  32010. const inputs = functionNode.getInputs( builder );
  32011. const parameters = this.parameters;
  32012. if ( Array.isArray( parameters ) ) {
  32013. for ( let i = 0; i < parameters.length; i ++ ) {
  32014. const inputNode = inputs[ i ];
  32015. const node = parameters[ i ];
  32016. params.push( node.build( builder, inputNode.type ) );
  32017. }
  32018. } else {
  32019. for ( const inputNode of inputs ) {
  32020. const node = parameters[ inputNode.name ];
  32021. if ( node !== undefined ) {
  32022. params.push( node.build( builder, inputNode.type ) );
  32023. } else {
  32024. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  32025. }
  32026. }
  32027. }
  32028. const functionName = functionNode.build( builder, 'property' );
  32029. return `${functionName}( ${params.join( ', ' )} )`;
  32030. }
  32031. }
  32032. const call = ( func, ...params ) => {
  32033. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  32034. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  32035. };
  32036. addNodeElement( 'call', call );
  32037. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  32038. class ScriptableValueNode extends Node {
  32039. constructor( value = null ) {
  32040. super();
  32041. this._value = value;
  32042. this._cache = null;
  32043. this.inputType = null;
  32044. this.outpuType = null;
  32045. this.events = new EventDispatcher();
  32046. this.isScriptableValueNode = true;
  32047. }
  32048. get isScriptableOutputNode() {
  32049. return this.outputType !== null;
  32050. }
  32051. set value( val ) {
  32052. if ( this._value === val ) return;
  32053. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  32054. URL.revokeObjectURL( this._cache );
  32055. this._cache = null;
  32056. }
  32057. this._value = val;
  32058. this.events.dispatchEvent( { type: 'change' } );
  32059. this.refresh();
  32060. }
  32061. get value() {
  32062. return this._value;
  32063. }
  32064. refresh() {
  32065. this.events.dispatchEvent( { type: 'refresh' } );
  32066. }
  32067. getValue() {
  32068. const value = this.value;
  32069. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  32070. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  32071. } else if ( value && value.value !== null && value.value !== undefined && (
  32072. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  32073. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  32074. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  32075. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  32076. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  32077. ( this.inputType === 'Color' && value.value.isColor ) ||
  32078. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  32079. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  32080. ) ) {
  32081. return value.value;
  32082. }
  32083. return this._cache || value;
  32084. }
  32085. getNodeType( builder ) {
  32086. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  32087. }
  32088. setup() {
  32089. return this.value && this.value.isNode ? this.value : float();
  32090. }
  32091. serialize( data ) {
  32092. super.serialize( data );
  32093. if ( this.value !== null ) {
  32094. if ( this.inputType === 'ArrayBuffer' ) {
  32095. data.value = arrayBufferToBase64( this.value );
  32096. } else {
  32097. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  32098. }
  32099. } else {
  32100. data.value = null;
  32101. }
  32102. data.inputType = this.inputType;
  32103. data.outputType = this.outputType;
  32104. }
  32105. deserialize( data ) {
  32106. super.deserialize( data );
  32107. let value = null;
  32108. if ( data.value !== null ) {
  32109. if ( data.inputType === 'ArrayBuffer' ) {
  32110. value = base64ToArrayBuffer( data.value );
  32111. } else if ( data.inputType === 'Texture' ) {
  32112. value = data.meta.textures[ data.value ];
  32113. } else {
  32114. value = data.meta.nodes[ data.value ] || null;
  32115. }
  32116. }
  32117. this.value = value;
  32118. this.inputType = data.inputType;
  32119. this.outputType = data.outputType;
  32120. }
  32121. }
  32122. const scriptableValue = nodeProxy( ScriptableValueNode );
  32123. addNodeElement( 'scriptableValue', scriptableValue );
  32124. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  32125. class Resources extends Map {
  32126. get( key, callback = null, ...params ) {
  32127. if ( this.has( key ) ) return super.get( key );
  32128. if ( callback !== null ) {
  32129. const value = callback( ...params );
  32130. this.set( key, value );
  32131. return value;
  32132. }
  32133. }
  32134. }
  32135. class Parameters {
  32136. constructor( scriptableNode ) {
  32137. this.scriptableNode = scriptableNode;
  32138. }
  32139. get parameters() {
  32140. return this.scriptableNode.parameters;
  32141. }
  32142. get layout() {
  32143. return this.scriptableNode.getLayout();
  32144. }
  32145. getInputLayout( id ) {
  32146. return this.scriptableNode.getInputLayout( id );
  32147. }
  32148. get( name ) {
  32149. const param = this.parameters[ name ];
  32150. const value = param ? param.getValue() : null;
  32151. return value;
  32152. }
  32153. }
  32154. const global = new Resources();
  32155. class ScriptableNode extends Node {
  32156. constructor( codeNode = null, parameters = {} ) {
  32157. super();
  32158. this.codeNode = codeNode;
  32159. this.parameters = parameters;
  32160. this._local = new Resources();
  32161. this._output = scriptableValue();
  32162. this._outputs = {};
  32163. this._source = this.source;
  32164. this._method = null;
  32165. this._object = null;
  32166. this._value = null;
  32167. this._needsOutputUpdate = true;
  32168. this.onRefresh = this.onRefresh.bind( this );
  32169. this.isScriptableNode = true;
  32170. }
  32171. get source() {
  32172. return this.codeNode ? this.codeNode.code : '';
  32173. }
  32174. setLocal( name, value ) {
  32175. return this._local.set( name, value );
  32176. }
  32177. getLocal( name ) {
  32178. return this._local.get( name );
  32179. }
  32180. onRefresh() {
  32181. this._refresh();
  32182. }
  32183. getInputLayout( id ) {
  32184. for ( const element of this.getLayout() ) {
  32185. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  32186. return element;
  32187. }
  32188. }
  32189. }
  32190. getOutputLayout( id ) {
  32191. for ( const element of this.getLayout() ) {
  32192. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  32193. return element;
  32194. }
  32195. }
  32196. }
  32197. setOutput( name, value ) {
  32198. const outputs = this._outputs;
  32199. if ( outputs[ name ] === undefined ) {
  32200. outputs[ name ] = scriptableValue( value );
  32201. } else {
  32202. outputs[ name ].value = value;
  32203. }
  32204. return this;
  32205. }
  32206. getOutput( name ) {
  32207. return this._outputs[ name ];
  32208. }
  32209. getParameter( name ) {
  32210. return this.parameters[ name ];
  32211. }
  32212. setParameter( name, value ) {
  32213. const parameters = this.parameters;
  32214. if ( value && value.isScriptableNode ) {
  32215. this.deleteParameter( name );
  32216. parameters[ name ] = value;
  32217. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  32218. } else if ( value && value.isScriptableValueNode ) {
  32219. this.deleteParameter( name );
  32220. parameters[ name ] = value;
  32221. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32222. } else if ( parameters[ name ] === undefined ) {
  32223. parameters[ name ] = scriptableValue( value );
  32224. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32225. } else {
  32226. parameters[ name ].value = value;
  32227. }
  32228. return this;
  32229. }
  32230. getValue() {
  32231. return this.getDefaultOutput().getValue();
  32232. }
  32233. deleteParameter( name ) {
  32234. let valueNode = this.parameters[ name ];
  32235. if ( valueNode ) {
  32236. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32237. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  32238. }
  32239. return this;
  32240. }
  32241. clearParameters() {
  32242. for ( const name of Object.keys( this.parameters ) ) {
  32243. this.deleteParameter( name );
  32244. }
  32245. this.needsUpdate = true;
  32246. return this;
  32247. }
  32248. call( name, ...params ) {
  32249. const object = this.getObject();
  32250. const method = object[ name ];
  32251. if ( typeof method === 'function' ) {
  32252. return method( ...params );
  32253. }
  32254. }
  32255. async callAsync( name, ...params ) {
  32256. const object = this.getObject();
  32257. const method = object[ name ];
  32258. if ( typeof method === 'function' ) {
  32259. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  32260. }
  32261. }
  32262. getNodeType( builder ) {
  32263. return this.getDefaultOutputNode().getNodeType( builder );
  32264. }
  32265. refresh( output = null ) {
  32266. if ( output !== null ) {
  32267. this.getOutput( output ).refresh();
  32268. } else {
  32269. this._refresh();
  32270. }
  32271. }
  32272. getObject() {
  32273. if ( this.needsUpdate ) this.dispose();
  32274. if ( this._object !== null ) return this._object;
  32275. //
  32276. const refresh = () => this.refresh();
  32277. const setOutput = ( id, value ) => this.setOutput( id, value );
  32278. const parameters = new Parameters( this );
  32279. const THREE = global.get( 'THREE' );
  32280. const TSL = global.get( 'TSL' );
  32281. const method = this.getMethod( this.codeNode );
  32282. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  32283. this._object = method( ...params );
  32284. const layout = this._object.layout;
  32285. if ( layout ) {
  32286. if ( layout.cache === false ) {
  32287. this._local.clear();
  32288. }
  32289. // default output
  32290. this._output.outputType = layout.outputType || null;
  32291. if ( Array.isArray( layout.elements ) ) {
  32292. for ( const element of layout.elements ) {
  32293. const id = element.id || element.name;
  32294. if ( element.inputType ) {
  32295. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  32296. this.getParameter( id ).inputType = element.inputType;
  32297. }
  32298. if ( element.outputType ) {
  32299. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  32300. this.getOutput( id ).outputType = element.outputType;
  32301. }
  32302. }
  32303. }
  32304. }
  32305. return this._object;
  32306. }
  32307. deserialize( data ) {
  32308. super.deserialize( data );
  32309. for ( const name in this.parameters ) {
  32310. let valueNode = this.parameters[ name ];
  32311. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32312. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  32313. }
  32314. }
  32315. getLayout() {
  32316. return this.getObject().layout;
  32317. }
  32318. getDefaultOutputNode() {
  32319. const output = this.getDefaultOutput().value;
  32320. if ( output && output.isNode ) {
  32321. return output;
  32322. }
  32323. return float();
  32324. }
  32325. getDefaultOutput() {
  32326. return this._exec()._output;
  32327. }
  32328. getMethod() {
  32329. if ( this.needsUpdate ) this.dispose();
  32330. if ( this._method !== null ) return this._method;
  32331. //
  32332. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  32333. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  32334. const properties = interfaceProps.join( ', ' );
  32335. const declarations = 'var ' + properties + '; var output = {};\n';
  32336. const returns = '\nreturn { ...output, ' + properties + ' };';
  32337. const code = declarations + this.codeNode.code + returns;
  32338. //
  32339. this._method = new Function( ...parametersProps, code );
  32340. return this._method;
  32341. }
  32342. dispose() {
  32343. if ( this._method === null ) return;
  32344. if ( this._object && typeof this._object.dispose === 'function' ) {
  32345. this._object.dispose();
  32346. }
  32347. this._method = null;
  32348. this._object = null;
  32349. this._source = null;
  32350. this._value = null;
  32351. this._needsOutputUpdate = true;
  32352. this._output.value = null;
  32353. this._outputs = {};
  32354. }
  32355. setup() {
  32356. return this.getDefaultOutputNode();
  32357. }
  32358. set needsUpdate( value ) {
  32359. if ( value === true ) this.dispose();
  32360. }
  32361. get needsUpdate() {
  32362. return this.source !== this._source;
  32363. }
  32364. _exec() {
  32365. if ( this.codeNode === null ) return this;
  32366. if ( this._needsOutputUpdate === true ) {
  32367. this._value = this.call( 'main' );
  32368. this._needsOutputUpdate = false;
  32369. }
  32370. this._output.value = this._value;
  32371. return this;
  32372. }
  32373. _refresh() {
  32374. this.needsUpdate = true;
  32375. this._exec();
  32376. this._output.refresh();
  32377. }
  32378. }
  32379. const scriptable = nodeProxy( ScriptableNode );
  32380. addNodeElement( 'scriptable', scriptable );
  32381. addNodeClass( 'ScriptableNode', ScriptableNode );
  32382. class FogNode extends Node {
  32383. constructor( colorNode, factorNode ) {
  32384. super( 'float' );
  32385. this.isFogNode = true;
  32386. this.colorNode = colorNode;
  32387. this.factorNode = factorNode;
  32388. }
  32389. getViewZNode( builder ) {
  32390. let viewZ;
  32391. const getViewZ = builder.context.getViewZ;
  32392. if ( getViewZ !== undefined ) {
  32393. viewZ = getViewZ( this );
  32394. }
  32395. return ( viewZ || positionView.z ).negate();
  32396. }
  32397. setup() {
  32398. return this.factorNode;
  32399. }
  32400. }
  32401. const fog = nodeProxy( FogNode );
  32402. addNodeElement( 'fog', fog );
  32403. addNodeClass( 'FogNode', FogNode );
  32404. class FogRangeNode extends FogNode {
  32405. constructor( colorNode, nearNode, farNode ) {
  32406. super( colorNode );
  32407. this.isFogRangeNode = true;
  32408. this.nearNode = nearNode;
  32409. this.farNode = farNode;
  32410. }
  32411. setup( builder ) {
  32412. const viewZ = this.getViewZNode( builder );
  32413. return smoothstep( this.nearNode, this.farNode, viewZ );
  32414. }
  32415. }
  32416. const rangeFog = nodeProxy( FogRangeNode );
  32417. addNodeElement( 'rangeFog', rangeFog );
  32418. addNodeClass( 'FogRangeNode', FogRangeNode );
  32419. class FogExp2Node extends FogNode {
  32420. constructor( colorNode, densityNode ) {
  32421. super( colorNode );
  32422. this.isFogExp2Node = true;
  32423. this.densityNode = densityNode;
  32424. }
  32425. setup( builder ) {
  32426. const viewZ = this.getViewZNode( builder );
  32427. const density = this.densityNode;
  32428. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  32429. }
  32430. }
  32431. const densityFog = nodeProxy( FogExp2Node );
  32432. addNodeElement( 'densityFog', densityFog );
  32433. addNodeClass( 'FogExp2Node', FogExp2Node );
  32434. let min = null;
  32435. let max = null;
  32436. class RangeNode extends Node {
  32437. constructor( minNode = float(), maxNode = float() ) {
  32438. super();
  32439. this.minNode = minNode;
  32440. this.maxNode = maxNode;
  32441. }
  32442. getVectorLength( builder ) {
  32443. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  32444. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  32445. return minLength > maxLength ? minLength : maxLength;
  32446. }
  32447. getNodeType( builder ) {
  32448. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  32449. }
  32450. setup( builder ) {
  32451. const object = builder.object;
  32452. let output = null;
  32453. if ( object.count > 1 ) {
  32454. const minValue = this.minNode.value;
  32455. const maxValue = this.maxNode.value;
  32456. const minLength = builder.getTypeLength( getValueType( minValue ) );
  32457. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  32458. min = min || new Vector4();
  32459. max = max || new Vector4();
  32460. min.setScalar( 0 );
  32461. max.setScalar( 0 );
  32462. if ( minLength === 1 ) min.setScalar( minValue );
  32463. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  32464. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  32465. if ( maxLength === 1 ) max.setScalar( maxValue );
  32466. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  32467. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  32468. const stride = 4;
  32469. const length = stride * object.count;
  32470. const array = new Float32Array( length );
  32471. for ( let i = 0; i < length; i ++ ) {
  32472. const index = i % stride;
  32473. const minElementValue = min.getComponent( index );
  32474. const maxElementValue = max.getComponent( index );
  32475. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  32476. }
  32477. const nodeType = this.getNodeType( builder );
  32478. if ( object.count <= 4096 ) {
  32479. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  32480. } else {
  32481. // TODO: Improve anonymous buffer attribute creation removing this part
  32482. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  32483. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  32484. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  32485. }
  32486. } else {
  32487. output = float( 0 );
  32488. }
  32489. return output;
  32490. }
  32491. }
  32492. const range = nodeProxy( RangeNode );
  32493. addNodeClass( 'RangeNode', RangeNode );
  32494. class ComputeNode extends Node {
  32495. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  32496. super( 'void' );
  32497. this.isComputeNode = true;
  32498. this.computeNode = computeNode;
  32499. this.count = count;
  32500. this.workgroupSize = workgroupSize;
  32501. this.dispatchCount = 0;
  32502. this.version = 1;
  32503. this.updateBeforeType = NodeUpdateType.OBJECT;
  32504. this.updateDispatchCount();
  32505. }
  32506. dispose() {
  32507. this.dispatchEvent( { type: 'dispose' } );
  32508. }
  32509. set needsUpdate( value ) {
  32510. if ( value === true ) this.version ++;
  32511. }
  32512. updateDispatchCount() {
  32513. const { count, workgroupSize } = this;
  32514. let size = workgroupSize[ 0 ];
  32515. for ( let i = 1; i < workgroupSize.length; i ++ )
  32516. size *= workgroupSize[ i ];
  32517. this.dispatchCount = Math.ceil( count / size );
  32518. }
  32519. onInit() { }
  32520. updateBefore( { renderer } ) {
  32521. renderer.compute( this );
  32522. }
  32523. generate( builder ) {
  32524. const { shaderStage } = builder;
  32525. if ( shaderStage === 'compute' ) {
  32526. const snippet = this.computeNode.build( builder, 'void' );
  32527. if ( snippet !== '' ) {
  32528. builder.addLineFlowCode( snippet );
  32529. }
  32530. }
  32531. }
  32532. }
  32533. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  32534. addNodeElement( 'compute', compute );
  32535. addNodeClass( 'ComputeNode', ComputeNode );
  32536. class LightNode extends Node {
  32537. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  32538. super();
  32539. this.scope = scope;
  32540. this.light = light;
  32541. }
  32542. setup() {
  32543. const { scope, light } = this;
  32544. let output = null;
  32545. if ( scope === LightNode.TARGET_DIRECTION ) {
  32546. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  32547. }
  32548. return output;
  32549. }
  32550. serialize( data ) {
  32551. super.serialize( data );
  32552. data.scope = this.scope;
  32553. }
  32554. deserialize( data ) {
  32555. super.deserialize( data );
  32556. this.scope = data.scope;
  32557. }
  32558. }
  32559. LightNode.TARGET_DIRECTION = 'targetDirection';
  32560. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  32561. addNodeClass( 'LightNode', LightNode );
  32562. const getDistanceAttenuation = tslFn( ( inputs ) => {
  32563. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  32564. // based upon Frostbite 3 Moving to Physically-based Rendering
  32565. // page 32, equation 26: E[window1]
  32566. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32567. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32568. return cutoffDistance.greaterThan( 0 ).cond(
  32569. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32570. distanceFalloff
  32571. );
  32572. } ); // validated
  32573. class PointLightNode extends AnalyticLightNode {
  32574. constructor( light = null ) {
  32575. super( light );
  32576. this.cutoffDistanceNode = uniform( 0 );
  32577. this.decayExponentNode = uniform( 0 );
  32578. }
  32579. update( frame ) {
  32580. const { light } = this;
  32581. super.update( frame );
  32582. this.cutoffDistanceNode.value = light.distance;
  32583. this.decayExponentNode.value = light.decay;
  32584. }
  32585. setup( builder ) {
  32586. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32587. const lightingModel = builder.context.lightingModel;
  32588. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32589. const lightDirection = lVector.normalize();
  32590. const lightDistance = lVector.length();
  32591. const lightAttenuation = getDistanceAttenuation( {
  32592. lightDistance,
  32593. cutoffDistance: cutoffDistanceNode,
  32594. decayExponent: decayExponentNode
  32595. } );
  32596. const lightColor = colorNode.mul( lightAttenuation );
  32597. const reflectedLight = builder.context.reflectedLight;
  32598. lightingModel.direct( {
  32599. lightDirection,
  32600. lightColor,
  32601. reflectedLight,
  32602. shadowMask: this.shadowMaskNode
  32603. }, builder.stack, builder );
  32604. }
  32605. }
  32606. addNodeClass( 'PointLightNode', PointLightNode );
  32607. addLightNode( PointLight, PointLightNode );
  32608. class DirectionalLightNode extends AnalyticLightNode {
  32609. constructor( light = null ) {
  32610. super( light );
  32611. }
  32612. setup( builder ) {
  32613. super.setup( builder );
  32614. const lightingModel = builder.context.lightingModel;
  32615. const lightColor = this.colorNode;
  32616. const lightDirection = lightTargetDirection( this.light );
  32617. const reflectedLight = builder.context.reflectedLight;
  32618. lightingModel.direct( {
  32619. lightDirection,
  32620. lightColor,
  32621. reflectedLight,
  32622. shadowMask: this.shadowMaskNode
  32623. }, builder.stack, builder );
  32624. }
  32625. }
  32626. addNodeClass( 'DirectionalLightNode', DirectionalLightNode );
  32627. addLightNode( DirectionalLight, DirectionalLightNode );
  32628. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32629. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32630. let ltcLib = null;
  32631. class RectAreaLightNode extends AnalyticLightNode {
  32632. constructor( light = null ) {
  32633. super( light );
  32634. this.halfHeight = uniform( new Vector3() );
  32635. this.halfWidth = uniform( new Vector3() );
  32636. }
  32637. update( frame ) {
  32638. super.update( frame );
  32639. const { light } = this;
  32640. const viewMatrix = frame.camera.matrixWorldInverse;
  32641. _matrix42.identity();
  32642. _matrix41.copy( light.matrixWorld );
  32643. _matrix41.premultiply( viewMatrix );
  32644. _matrix42.extractRotation( _matrix41 );
  32645. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32646. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32647. this.halfWidth.value.applyMatrix4( _matrix42 );
  32648. this.halfHeight.value.applyMatrix4( _matrix42 );
  32649. }
  32650. setup( builder ) {
  32651. super.setup( builder );
  32652. let ltc_1, ltc_2;
  32653. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32654. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  32655. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  32656. } else {
  32657. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  32658. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  32659. }
  32660. const { colorNode, light } = this;
  32661. const lightingModel = builder.context.lightingModel;
  32662. const lightPosition = objectViewPosition( light );
  32663. const reflectedLight = builder.context.reflectedLight;
  32664. lightingModel.directRectArea( {
  32665. lightColor: colorNode,
  32666. lightPosition,
  32667. halfWidth: this.halfWidth,
  32668. halfHeight: this.halfHeight,
  32669. reflectedLight,
  32670. ltc_1,
  32671. ltc_2
  32672. }, builder.stack, builder );
  32673. }
  32674. static setLTC( ltc ) {
  32675. ltcLib = ltc;
  32676. }
  32677. }
  32678. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  32679. addLightNode( RectAreaLight, RectAreaLightNode );
  32680. class SpotLightNode extends AnalyticLightNode {
  32681. constructor( light = null ) {
  32682. super( light );
  32683. this.coneCosNode = uniform( 0 );
  32684. this.penumbraCosNode = uniform( 0 );
  32685. this.cutoffDistanceNode = uniform( 0 );
  32686. this.decayExponentNode = uniform( 0 );
  32687. }
  32688. update( frame ) {
  32689. super.update( frame );
  32690. const { light } = this;
  32691. this.coneCosNode.value = Math.cos( light.angle );
  32692. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32693. this.cutoffDistanceNode.value = light.distance;
  32694. this.decayExponentNode.value = light.decay;
  32695. }
  32696. getSpotAttenuation( angleCosine ) {
  32697. const { coneCosNode, penumbraCosNode } = this;
  32698. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32699. }
  32700. setup( builder ) {
  32701. super.setup( builder );
  32702. const lightingModel = builder.context.lightingModel;
  32703. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32704. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32705. const lightDirection = lVector.normalize();
  32706. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32707. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32708. const lightDistance = lVector.length();
  32709. const lightAttenuation = getDistanceAttenuation( {
  32710. lightDistance,
  32711. cutoffDistance: cutoffDistanceNode,
  32712. decayExponent: decayExponentNode
  32713. } );
  32714. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32715. const reflectedLight = builder.context.reflectedLight;
  32716. lightingModel.direct( {
  32717. lightDirection,
  32718. lightColor,
  32719. reflectedLight,
  32720. shadowMask: this.shadowMaskNode
  32721. }, builder.stack, builder );
  32722. }
  32723. }
  32724. addNodeClass( 'SpotLightNode', SpotLightNode );
  32725. addLightNode( SpotLight, SpotLightNode );
  32726. class IESSpotLight extends SpotLight {
  32727. constructor( color, intensity, distance, angle, penumbra, decay ) {
  32728. super( color, intensity, distance, angle, penumbra, decay );
  32729. this.iesMap = null;
  32730. }
  32731. copy( source, recursive ) {
  32732. super.copy( source, recursive );
  32733. this.iesMap = source.iesMap;
  32734. return this;
  32735. }
  32736. }
  32737. class IESSpotLightNode extends SpotLightNode {
  32738. getSpotAttenuation( angleCosine ) {
  32739. const iesMap = this.light.iesMap;
  32740. let spotAttenuation = null;
  32741. if ( iesMap && iesMap.isTexture === true ) {
  32742. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32743. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32744. } else {
  32745. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32746. }
  32747. return spotAttenuation;
  32748. }
  32749. }
  32750. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  32751. addLightNode( IESSpotLight, IESSpotLightNode );
  32752. class AmbientLightNode extends AnalyticLightNode {
  32753. constructor( light = null ) {
  32754. super( light );
  32755. }
  32756. setup( { context } ) {
  32757. context.irradiance.addAssign( this.colorNode );
  32758. }
  32759. }
  32760. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  32761. addLightNode( AmbientLight, AmbientLightNode );
  32762. class HemisphereLightNode extends AnalyticLightNode {
  32763. constructor( light = null ) {
  32764. super( light );
  32765. this.lightPositionNode = objectPosition( light );
  32766. this.lightDirectionNode = this.lightPositionNode.normalize();
  32767. this.groundColorNode = uniform( new Color() );
  32768. }
  32769. update( frame ) {
  32770. const { light } = this;
  32771. super.update( frame );
  32772. this.lightPositionNode.object3d = light;
  32773. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32774. }
  32775. setup( builder ) {
  32776. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32777. const dotNL = normalView.dot( lightDirectionNode );
  32778. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32779. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32780. builder.context.irradiance.addAssign( irradiance );
  32781. }
  32782. }
  32783. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  32784. addLightNode( HemisphereLight, HemisphereLightNode );
  32785. let _generator = null;
  32786. const _cache = new WeakMap();
  32787. function _generateCubeUVSize( imageHeight ) {
  32788. const maxMip = Math.log2( imageHeight ) - 2;
  32789. const texelHeight = 1.0 / imageHeight;
  32790. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  32791. return { texelWidth, texelHeight, maxMip };
  32792. }
  32793. function _getPMREMFromTexture( texture ) {
  32794. let cacheTexture = _cache.get( texture );
  32795. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  32796. if ( pmremVersion !== texture.pmremVersion ) {
  32797. if ( texture.isCubeTexture ) {
  32798. if ( texture.source.data.some( ( texture ) => texture === undefined ) ) {
  32799. throw new Error( 'PMREMNode: Undefined texture in CubeTexture. Use onLoad callback or async loader' );
  32800. }
  32801. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  32802. } else {
  32803. if ( texture.image === undefined ) {
  32804. throw new Error( 'PMREMNode: Undefined image in Texture. Use onLoad callback or async loader' );
  32805. }
  32806. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  32807. }
  32808. cacheTexture.pmremVersion = texture.pmremVersion;
  32809. _cache.set( texture, cacheTexture );
  32810. }
  32811. return cacheTexture.texture;
  32812. }
  32813. class PMREMNode extends TempNode {
  32814. constructor( value, uvNode = null, levelNode = null ) {
  32815. super( 'vec3' );
  32816. this._value = value;
  32817. this._pmrem = null;
  32818. this.uvNode = uvNode;
  32819. this.levelNode = levelNode;
  32820. this._generator = null;
  32821. this._texture = texture( null );
  32822. this._width = uniform( 0 );
  32823. this._height = uniform( 0 );
  32824. this._maxMip = uniform( 0 );
  32825. this.updateBeforeType = NodeUpdateType.RENDER;
  32826. }
  32827. set value( value ) {
  32828. this._value = value;
  32829. this._pmrem = null;
  32830. }
  32831. get value() {
  32832. return this._value;
  32833. }
  32834. updateFromTexture( texture ) {
  32835. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  32836. this._texture.value = texture;
  32837. this._width.value = cubeUVSize.texelWidth;
  32838. this._height.value = cubeUVSize.texelHeight;
  32839. this._maxMip.value = cubeUVSize.maxMip;
  32840. }
  32841. updateBefore() {
  32842. let pmrem = this._pmrem;
  32843. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  32844. const texture = this._value;
  32845. if ( pmremVersion !== texture.pmremVersion ) {
  32846. if ( texture.isPMREMTexture === true ) {
  32847. pmrem = texture;
  32848. } else {
  32849. pmrem = _getPMREMFromTexture( texture );
  32850. }
  32851. this._pmrem = pmrem;
  32852. this.updateFromTexture( pmrem );
  32853. }
  32854. }
  32855. setup( builder ) {
  32856. if ( _generator === null ) {
  32857. _generator = builder.createPMREMGenerator();
  32858. }
  32859. //
  32860. this.updateBefore( builder );
  32861. //
  32862. let uvNode = this.uvNode;
  32863. if ( uvNode === null && builder.context.getUV ) {
  32864. uvNode = builder.context.getUV( this );
  32865. }
  32866. //
  32867. const texture = this.value;
  32868. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  32869. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  32870. }
  32871. //
  32872. let levelNode = this.levelNode;
  32873. if ( levelNode === null && builder.context.getTextureLevel ) {
  32874. levelNode = builder.context.getTextureLevel( this );
  32875. }
  32876. //
  32877. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  32878. }
  32879. }
  32880. const pmremTexture = nodeProxy( PMREMNode );
  32881. addNodeClass( 'PMREMNode', PMREMNode );
  32882. const _envNodeCache = new WeakMap();
  32883. class EnvironmentNode extends LightingNode {
  32884. constructor( envNode = null ) {
  32885. super();
  32886. this.envNode = envNode;
  32887. }
  32888. setup( builder ) {
  32889. let envNode = this.envNode;
  32890. if ( envNode.isTextureNode ) {
  32891. let cacheEnvNode = _envNodeCache.get( envNode.value );
  32892. if ( cacheEnvNode === undefined ) {
  32893. cacheEnvNode = pmremTexture( envNode.value );
  32894. _envNodeCache.set( envNode.value, cacheEnvNode );
  32895. }
  32896. envNode = cacheEnvNode;
  32897. }
  32898. //
  32899. const { material } = builder;
  32900. const envMap = material.envMap;
  32901. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  32902. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  32903. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  32904. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  32905. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  32906. const isolateRadiance = cache( radiance );
  32907. const isolateIrradiance = cache( irradiance );
  32908. //
  32909. builder.context.radiance.addAssign( isolateRadiance );
  32910. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  32911. //
  32912. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  32913. if ( clearcoatRadiance ) {
  32914. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  32915. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  32916. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  32917. }
  32918. }
  32919. }
  32920. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  32921. let reflectVec = null;
  32922. return {
  32923. getUV: () => {
  32924. if ( reflectVec === null ) {
  32925. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  32926. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  32927. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  32928. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  32929. }
  32930. return reflectVec;
  32931. },
  32932. getTextureLevel: () => {
  32933. return roughnessNode;
  32934. }
  32935. };
  32936. };
  32937. const createIrradianceContext = ( normalWorldNode ) => {
  32938. return {
  32939. getUV: () => {
  32940. return normalWorldNode;
  32941. },
  32942. getTextureLevel: () => {
  32943. return float( 1.0 );
  32944. }
  32945. };
  32946. };
  32947. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  32948. class BasicEnvironmentNode extends LightingNode {
  32949. constructor( envNode = null ) {
  32950. super();
  32951. this.envNode = envNode;
  32952. }
  32953. setup( builder ) {
  32954. // environment property is used in the finish() method of BasicLightingModel
  32955. builder.context.environment = this.envNode;
  32956. }
  32957. }
  32958. addNodeClass( 'BasicEnvironmentNode', BasicEnvironmentNode );
  32959. const checkerShaderNode = tslFn( ( inputs ) => {
  32960. const uv = inputs.uv.mul( 2.0 );
  32961. const cx = uv.x.floor();
  32962. const cy = uv.y.floor();
  32963. const result = cx.add( cy ).mod( 2.0 );
  32964. return result.sign();
  32965. } );
  32966. class CheckerNode extends TempNode {
  32967. constructor( uvNode = uv() ) {
  32968. super( 'float' );
  32969. this.uvNode = uvNode;
  32970. }
  32971. setup() {
  32972. return checkerShaderNode( { uv: this.uvNode } );
  32973. }
  32974. }
  32975. const checker = nodeProxy( CheckerNode );
  32976. addNodeElement( 'checker', checker );
  32977. addNodeClass( 'CheckerNode', CheckerNode );
  32978. class NodeLoader extends Loader {
  32979. constructor( manager ) {
  32980. super( manager );
  32981. this.textures = {};
  32982. }
  32983. load( url, onLoad, onProgress, onError ) {
  32984. const loader = new FileLoader( this.manager );
  32985. loader.setPath( this.path );
  32986. loader.setRequestHeader( this.requestHeader );
  32987. loader.setWithCredentials( this.withCredentials );
  32988. loader.load( url, ( text ) => {
  32989. try {
  32990. onLoad( this.parse( JSON.parse( text ) ) );
  32991. } catch ( e ) {
  32992. if ( onError ) {
  32993. onError( e );
  32994. } else {
  32995. console.error( e );
  32996. }
  32997. this.manager.itemError( url );
  32998. }
  32999. }, onProgress, onError );
  33000. }
  33001. parseNodes( json ) {
  33002. const nodes = {};
  33003. if ( json !== undefined ) {
  33004. for ( const nodeJSON of json ) {
  33005. const { uuid, type } = nodeJSON;
  33006. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  33007. nodes[ uuid ].uuid = uuid;
  33008. }
  33009. const meta = { nodes, textures: this.textures };
  33010. for ( const nodeJSON of json ) {
  33011. nodeJSON.meta = meta;
  33012. const node = nodes[ nodeJSON.uuid ];
  33013. node.deserialize( nodeJSON );
  33014. delete nodeJSON.meta;
  33015. }
  33016. }
  33017. return nodes;
  33018. }
  33019. parse( json ) {
  33020. const node = nodeObject( createNodeFromType( json.type ) );
  33021. node.uuid = json.uuid;
  33022. const nodes = this.parseNodes( json.nodes );
  33023. const meta = { nodes, textures: this.textures };
  33024. json.meta = meta;
  33025. node.deserialize( json );
  33026. delete json.meta;
  33027. return node;
  33028. }
  33029. setTextures( value ) {
  33030. this.textures = value;
  33031. return this;
  33032. }
  33033. }
  33034. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  33035. class InstancedPointsNodeMaterial extends NodeMaterial {
  33036. constructor( params = {} ) {
  33037. super();
  33038. this.normals = false;
  33039. this.lights = false;
  33040. this.useAlphaToCoverage = true;
  33041. this.useColor = params.vertexColors;
  33042. this.pointWidth = 1;
  33043. this.pointColorNode = null;
  33044. this.setDefaultValues( _defaultValues$e );
  33045. this.setupShaders();
  33046. this.setValues( params );
  33047. }
  33048. setupShaders() {
  33049. const useAlphaToCoverage = this.alphaToCoverage;
  33050. const useColor = this.useColor;
  33051. this.vertexNode = tslFn( () => {
  33052. //vUv = uv;
  33053. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  33054. const instancePosition = attribute( 'instancePosition' );
  33055. // camera space
  33056. const mvPos = property( 'vec4', 'mvPos' );
  33057. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  33058. const aspect = viewport.z.div( viewport.w );
  33059. // clip space
  33060. const clipPos = cameraProjectionMatrix.mul( mvPos );
  33061. // offset in ndc space
  33062. const offset = property( 'vec2', 'offset' );
  33063. offset.assign( positionGeometry.xy );
  33064. offset.assign( offset.mul( materialPointWidth ) );
  33065. offset.assign( offset.div( viewport.z ) );
  33066. offset.y.assign( offset.y.mul( aspect ) );
  33067. // back to clip space
  33068. offset.assign( offset.mul( clipPos.w ) );
  33069. //clipPos.xy += offset;
  33070. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  33071. return clipPos;
  33072. //vec4 mvPosition = mvPos; // this was used for somethihng...
  33073. } )();
  33074. this.fragmentNode = tslFn( () => {
  33075. const vUv = varying( vec2(), 'vUv' );
  33076. // force assignment into correct place in flow
  33077. const alpha = property( 'float', 'alpha' );
  33078. alpha.assign( 1 );
  33079. const a = vUv.x;
  33080. const b = vUv.y;
  33081. const len2 = a.mul( a ).add( b.mul( b ) );
  33082. if ( useAlphaToCoverage ) {
  33083. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  33084. const dlen = property( 'float', 'dlen' );
  33085. dlen.assign( len2.fwidth() );
  33086. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  33087. } else {
  33088. len2.greaterThan( 1.0 ).discard();
  33089. }
  33090. let pointColorNode;
  33091. if ( this.pointColorNode ) {
  33092. pointColorNode = this.pointColorNode;
  33093. } else {
  33094. if ( useColor ) {
  33095. const instanceColor = attribute( 'instanceColor' );
  33096. pointColorNode = instanceColor.mul( materialColor );
  33097. } else {
  33098. pointColorNode = materialColor;
  33099. }
  33100. }
  33101. return vec4( pointColorNode, alpha );
  33102. } )();
  33103. this.needsUpdate = true;
  33104. }
  33105. get alphaToCoverage() {
  33106. return this.useAlphaToCoverage;
  33107. }
  33108. set alphaToCoverage( value ) {
  33109. if ( this.useAlphaToCoverage !== value ) {
  33110. this.useAlphaToCoverage = value;
  33111. this.setupShaders();
  33112. }
  33113. }
  33114. }
  33115. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  33116. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  33117. class LineBasicNodeMaterial extends NodeMaterial {
  33118. constructor( parameters ) {
  33119. super();
  33120. this.isLineBasicNodeMaterial = true;
  33121. this.lights = false;
  33122. this.normals = false;
  33123. this.setDefaultValues( _defaultValues$d );
  33124. this.setValues( parameters );
  33125. }
  33126. }
  33127. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  33128. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  33129. class LineDashedNodeMaterial extends NodeMaterial {
  33130. constructor( parameters ) {
  33131. super();
  33132. this.isLineDashedNodeMaterial = true;
  33133. this.lights = false;
  33134. this.normals = false;
  33135. this.setDefaultValues( _defaultValues$c );
  33136. this.offsetNode = null;
  33137. this.dashScaleNode = null;
  33138. this.dashSizeNode = null;
  33139. this.gapSizeNode = null;
  33140. this.setValues( parameters );
  33141. }
  33142. setupVariants() {
  33143. const offsetNode = this.offsetNode;
  33144. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  33145. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  33146. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  33147. dashSize.assign( dashSizeNode );
  33148. gapSize.assign( gapSizeNode );
  33149. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  33150. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  33151. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  33152. }
  33153. }
  33154. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  33155. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  33156. class Line2NodeMaterial extends NodeMaterial {
  33157. constructor( params = {} ) {
  33158. super();
  33159. this.normals = false;
  33160. this.lights = false;
  33161. this.setDefaultValues( _defaultValues$b );
  33162. this.useAlphaToCoverage = true;
  33163. this.useColor = params.vertexColors;
  33164. this.useDash = params.dashed;
  33165. this.useWorldUnits = false;
  33166. this.dashOffset = 0;
  33167. this.lineWidth = 1;
  33168. this.lineColorNode = null;
  33169. this.offsetNode = null;
  33170. this.dashScaleNode = null;
  33171. this.dashSizeNode = null;
  33172. this.gapSizeNode = null;
  33173. this.setValues( params );
  33174. }
  33175. setup( builder ) {
  33176. this.setupShaders();
  33177. super.setup( builder );
  33178. }
  33179. setupShaders() {
  33180. const useAlphaToCoverage = this.alphaToCoverage;
  33181. const useColor = this.useColor;
  33182. const useDash = this.dashed;
  33183. const useWorldUnits = this.worldUnits;
  33184. const trimSegment = tslFn( ( { start, end } ) => {
  33185. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  33186. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  33187. const nearEstimate = b.mul( - 0.5 ).div( a );
  33188. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  33189. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  33190. } );
  33191. this.vertexNode = tslFn( () => {
  33192. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  33193. const instanceStart = attribute( 'instanceStart' );
  33194. const instanceEnd = attribute( 'instanceEnd' );
  33195. // camera space
  33196. const start = property( 'vec4', 'start' );
  33197. const end = property( 'vec4', 'end' );
  33198. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  33199. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  33200. if ( useWorldUnits ) {
  33201. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  33202. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  33203. }
  33204. const aspect = viewport.z.div( viewport.w );
  33205. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  33206. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  33207. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  33208. // perhaps there is a more elegant solution -- WestLangley
  33209. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  33210. If( perspective, () => {
  33211. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  33212. end.assign( trimSegment( { start: start, end: end } ) );
  33213. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  33214. start.assign( trimSegment( { start: end, end: start } ) );
  33215. } );
  33216. } );
  33217. // clip space
  33218. const clipStart = cameraProjectionMatrix.mul( start );
  33219. const clipEnd = cameraProjectionMatrix.mul( end );
  33220. // ndc space
  33221. const ndcStart = clipStart.xyz.div( clipStart.w );
  33222. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  33223. // direction
  33224. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  33225. // account for clip-space aspect ratio
  33226. dir.x.assign( dir.x.mul( aspect ) );
  33227. dir.assign( dir.normalize() );
  33228. const clip = temp( vec4() );
  33229. if ( useWorldUnits ) {
  33230. // get the offset direction as perpendicular to the view vector
  33231. const worldDir = end.xyz.sub( start.xyz ).normalize();
  33232. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  33233. const worldUp = worldDir.cross( tmpFwd ).normalize();
  33234. const worldFwd = worldDir.cross( worldUp );
  33235. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  33236. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  33237. // height offset
  33238. const hw = materialLineWidth.mul( 0.5 );
  33239. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  33240. // don't extend the line if we're rendering dashes because we
  33241. // won't be rendering the endcaps
  33242. if ( ! useDash ) {
  33243. // cap extension
  33244. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  33245. // add width to the box
  33246. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  33247. // endcaps
  33248. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  33249. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  33250. } );
  33251. }
  33252. // project the worldpos
  33253. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  33254. // shift the depth of the projected points so the line
  33255. // segments overlap neatly
  33256. const clipPose = temp( vec3() );
  33257. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  33258. clip.z.assign( clipPose.z.mul( clip.w ) );
  33259. } else {
  33260. const offset = property( 'vec2', 'offset' );
  33261. offset.assign( vec2( dir.y, dir.x.negate() ) );
  33262. // undo aspect ratio adjustment
  33263. dir.x.assign( dir.x.div( aspect ) );
  33264. offset.x.assign( offset.x.div( aspect ) );
  33265. // sign flip
  33266. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  33267. // endcaps
  33268. If( positionGeometry.y.lessThan( 0.0 ), () => {
  33269. offset.assign( offset.sub( dir ) );
  33270. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  33271. offset.assign( offset.add( dir ) );
  33272. } );
  33273. // adjust for linewidth
  33274. offset.assign( offset.mul( materialLineWidth ) );
  33275. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  33276. offset.assign( offset.div( viewport.w ) );
  33277. // select end
  33278. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  33279. // back to clip space
  33280. offset.assign( offset.mul( clip.w ) );
  33281. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  33282. }
  33283. return clip;
  33284. } )();
  33285. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  33286. const p13 = p1.sub( p3 );
  33287. const p43 = p4.sub( p3 );
  33288. const p21 = p2.sub( p1 );
  33289. const d1343 = p13.dot( p43 );
  33290. const d4321 = p43.dot( p21 );
  33291. const d1321 = p13.dot( p21 );
  33292. const d4343 = p43.dot( p43 );
  33293. const d2121 = p21.dot( p21 );
  33294. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  33295. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  33296. const mua = numer.div( denom ).clamp();
  33297. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  33298. return vec2( mua, mub );
  33299. } );
  33300. this.fragmentNode = tslFn( () => {
  33301. const vUv = varyingProperty( 'vec2', 'vUv' );
  33302. if ( useDash ) {
  33303. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  33304. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  33305. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  33306. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  33307. dashSize.assign( dashSizeNode );
  33308. gapSize.assign( gapSizeNode );
  33309. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  33310. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  33311. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  33312. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  33313. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  33314. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  33315. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  33316. }
  33317. // force assignment into correct place in flow
  33318. const alpha = property( 'float', 'alpha' );
  33319. alpha.assign( 1 );
  33320. if ( useWorldUnits ) {
  33321. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  33322. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  33323. // Find the closest points on the view ray and the line segment
  33324. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  33325. const lineDir = worldEnd.sub( worldStart );
  33326. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  33327. const p1 = worldStart.add( lineDir.mul( params.x ) );
  33328. const p2 = rayEnd.mul( params.y );
  33329. const delta = p1.sub( p2 );
  33330. const len = delta.length();
  33331. const norm = len.div( materialLineWidth );
  33332. if ( ! useDash ) {
  33333. if ( useAlphaToCoverage ) {
  33334. const dnorm = norm.fwidth();
  33335. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  33336. } else {
  33337. norm.greaterThan( 0.5 ).discard();
  33338. }
  33339. }
  33340. } else {
  33341. // round endcaps
  33342. if ( useAlphaToCoverage ) {
  33343. const a = vUv.x;
  33344. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  33345. const len2 = a.mul( a ).add( b.mul( b ) );
  33346. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  33347. const dlen = property( 'float', 'dlen' );
  33348. dlen.assign( len2.fwidth() );
  33349. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  33350. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  33351. } );
  33352. } else {
  33353. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  33354. const a = vUv.x;
  33355. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  33356. const len2 = a.mul( a ).add( b.mul( b ) );
  33357. len2.greaterThan( 1.0 ).discard();
  33358. } );
  33359. }
  33360. }
  33361. let lineColorNode;
  33362. if ( this.lineColorNode ) {
  33363. lineColorNode = this.lineColorNode;
  33364. } else {
  33365. if ( useColor ) {
  33366. const instanceColorStart = attribute( 'instanceColorStart' );
  33367. const instanceColorEnd = attribute( 'instanceColorEnd' );
  33368. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  33369. lineColorNode = instanceColor.mul( materialColor );
  33370. } else {
  33371. lineColorNode = materialColor;
  33372. }
  33373. }
  33374. return vec4( lineColorNode, alpha );
  33375. } )();
  33376. }
  33377. get worldUnits() {
  33378. return this.useWorldUnits;
  33379. }
  33380. set worldUnits( value ) {
  33381. if ( this.useWorldUnits !== value ) {
  33382. this.useWorldUnits = value;
  33383. this.needsUpdate = true;
  33384. }
  33385. }
  33386. get dashed() {
  33387. return this.useDash;
  33388. }
  33389. set dashed( value ) {
  33390. if ( this.useDash !== value ) {
  33391. this.useDash = value;
  33392. this.needsUpdate = true;
  33393. }
  33394. }
  33395. get alphaToCoverage() {
  33396. return this.useAlphaToCoverage;
  33397. }
  33398. set alphaToCoverage( value ) {
  33399. if ( this.useAlphaToCoverage !== value ) {
  33400. this.useAlphaToCoverage = value;
  33401. this.needsUpdate = true;
  33402. }
  33403. }
  33404. }
  33405. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  33406. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  33407. class MeshNormalNodeMaterial extends NodeMaterial {
  33408. constructor( parameters ) {
  33409. super();
  33410. this.lights = false;
  33411. this.isMeshNormalNodeMaterial = true;
  33412. this.setDefaultValues( _defaultValues$a );
  33413. this.setValues( parameters );
  33414. }
  33415. setupDiffuseColor() {
  33416. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  33417. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  33418. }
  33419. }
  33420. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  33421. class BasicLightMapNode extends LightingNode {
  33422. constructor( lightMapNode = null ) {
  33423. super();
  33424. this.lightMapNode = lightMapNode;
  33425. }
  33426. setup( builder ) {
  33427. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  33428. const RECIPROCAL_PI = float( 1 / Math.PI );
  33429. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  33430. }
  33431. }
  33432. addNodeClass( 'BasicLightMapNode', BasicLightMapNode );
  33433. class BasicLightingModel extends LightingModel {
  33434. constructor() {
  33435. super();
  33436. }
  33437. indirect( context, stack, builder ) {
  33438. const ambientOcclusion = context.ambientOcclusion;
  33439. const reflectedLight = context.reflectedLight;
  33440. const irradianceLightMap = builder.context.irradianceLightMap;
  33441. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  33442. // accumulation (baked indirect lighting only)
  33443. if ( irradianceLightMap ) {
  33444. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  33445. } else {
  33446. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  33447. }
  33448. // modulation
  33449. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33450. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  33451. }
  33452. finish( context, stack, builder ) {
  33453. const material = builder.material;
  33454. const outgoingLight = context.outgoingLight;
  33455. const envNode = builder.context.environment;
  33456. if ( envNode ) {
  33457. switch ( material.combine ) {
  33458. case MultiplyOperation:
  33459. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  33460. break;
  33461. case MixOperation:
  33462. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  33463. break;
  33464. case AddOperation:
  33465. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  33466. break;
  33467. default:
  33468. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  33469. break;
  33470. }
  33471. }
  33472. }
  33473. }
  33474. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  33475. class MeshBasicNodeMaterial extends NodeMaterial {
  33476. constructor( parameters ) {
  33477. super();
  33478. this.isMeshBasicNodeMaterial = true;
  33479. this.lights = true;
  33480. //this.normals = false; @TODO: normals usage by context
  33481. this.setDefaultValues( _defaultValues$9 );
  33482. this.setValues( parameters );
  33483. }
  33484. setupNormal() {
  33485. transformedNormalView.assign( normalView ); // see #28839
  33486. }
  33487. setupEnvironment( builder ) {
  33488. const envNode = super.setupEnvironment( builder );
  33489. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33490. }
  33491. setupLightMap( builder ) {
  33492. let node = null;
  33493. if ( builder.material.lightMap ) {
  33494. node = new BasicLightMapNode( materialLightMap );
  33495. }
  33496. return node;
  33497. }
  33498. setupLightingModel() {
  33499. return new BasicLightingModel();
  33500. }
  33501. }
  33502. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  33503. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  33504. // Original approximation by Christophe Schlick '94
  33505. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  33506. // Optimized variant (presented by Epic at SIGGRAPH '13)
  33507. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  33508. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  33509. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  33510. } ); // validated
  33511. const BRDF_Lambert = tslFn( ( inputs ) => {
  33512. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  33513. } ); // validated
  33514. const G_BlinnPhong_Implicit = () => float( 0.25 );
  33515. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  33516. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  33517. } );
  33518. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  33519. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33520. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  33521. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  33522. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  33523. const G = G_BlinnPhong_Implicit();
  33524. const D = D_BlinnPhong( { dotNH } );
  33525. return F.mul( G ).mul( D );
  33526. } );
  33527. class PhongLightingModel extends BasicLightingModel {
  33528. constructor( specular = true ) {
  33529. super();
  33530. this.specular = specular;
  33531. }
  33532. direct( { lightDirection, lightColor, reflectedLight } ) {
  33533. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33534. const irradiance = dotNL.mul( lightColor );
  33535. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33536. if ( this.specular === true ) {
  33537. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  33538. }
  33539. }
  33540. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  33541. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33542. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33543. }
  33544. }
  33545. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  33546. class MeshLambertNodeMaterial extends NodeMaterial {
  33547. constructor( parameters ) {
  33548. super();
  33549. this.isMeshLambertNodeMaterial = true;
  33550. this.lights = true;
  33551. this.setDefaultValues( _defaultValues$8 );
  33552. this.setValues( parameters );
  33553. }
  33554. setupEnvironment( builder ) {
  33555. const envNode = super.setupEnvironment( builder );
  33556. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33557. }
  33558. setupLightingModel( /*builder*/ ) {
  33559. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  33560. }
  33561. }
  33562. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  33563. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  33564. class MeshPhongNodeMaterial extends NodeMaterial {
  33565. constructor( parameters ) {
  33566. super();
  33567. this.isMeshPhongNodeMaterial = true;
  33568. this.lights = true;
  33569. this.shininessNode = null;
  33570. this.specularNode = null;
  33571. this.setDefaultValues( _defaultValues$7 );
  33572. this.setValues( parameters );
  33573. }
  33574. setupEnvironment( builder ) {
  33575. const envNode = super.setupEnvironment( builder );
  33576. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33577. }
  33578. setupLightingModel( /*builder*/ ) {
  33579. return new PhongLightingModel();
  33580. }
  33581. setupVariants() {
  33582. // SHININESS
  33583. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  33584. shininess.assign( shininessNode );
  33585. // SPECULAR COLOR
  33586. const specularNode = this.specularNode || materialSpecular;
  33587. specularColor.assign( specularNode );
  33588. }
  33589. copy( source ) {
  33590. this.shininessNode = source.shininessNode;
  33591. this.specularNode = source.specularNode;
  33592. return super.copy( source );
  33593. }
  33594. }
  33595. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  33596. const getGeometryRoughness = tslFn( () => {
  33597. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  33598. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  33599. return geometryRoughness;
  33600. } );
  33601. const getRoughness = tslFn( ( inputs ) => {
  33602. const { roughness } = inputs;
  33603. const geometryRoughness = getGeometryRoughness();
  33604. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  33605. roughnessFactor = roughnessFactor.add( geometryRoughness );
  33606. roughnessFactor = roughnessFactor.min( 1.0 );
  33607. return roughnessFactor;
  33608. } );
  33609. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  33610. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  33611. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  33612. const a2 = alpha.pow2();
  33613. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  33614. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  33615. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  33616. } ).setLayout( {
  33617. name: 'V_GGX_SmithCorrelated',
  33618. type: 'float',
  33619. inputs: [
  33620. { name: 'alpha', type: 'float' },
  33621. { name: 'dotNL', type: 'float' },
  33622. { name: 'dotNV', type: 'float' }
  33623. ]
  33624. } ); // validated
  33625. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  33626. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  33627. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  33628. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  33629. const v = div( 0.5, gv.add( gl ) );
  33630. return v.saturate();
  33631. } ).setLayout( {
  33632. name: 'V_GGX_SmithCorrelated_Anisotropic',
  33633. type: 'float',
  33634. inputs: [
  33635. { name: 'alphaT', type: 'float', qualifier: 'in' },
  33636. { name: 'alphaB', type: 'float', qualifier: 'in' },
  33637. { name: 'dotTV', type: 'float', qualifier: 'in' },
  33638. { name: 'dotBV', type: 'float', qualifier: 'in' },
  33639. { name: 'dotTL', type: 'float', qualifier: 'in' },
  33640. { name: 'dotBL', type: 'float', qualifier: 'in' },
  33641. { name: 'dotNV', type: 'float', qualifier: 'in' },
  33642. { name: 'dotNL', type: 'float', qualifier: 'in' }
  33643. ]
  33644. } );
  33645. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  33646. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  33647. // alpha is "roughness squared" in Disney’s reparameterization
  33648. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  33649. const a2 = alpha.pow2();
  33650. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  33651. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  33652. } ).setLayout( {
  33653. name: 'D_GGX',
  33654. type: 'float',
  33655. inputs: [
  33656. { name: 'alpha', type: 'float' },
  33657. { name: 'dotNH', type: 'float' }
  33658. ]
  33659. } ); // validated
  33660. const RECIPROCAL_PI = float( 1 / Math.PI );
  33661. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  33662. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  33663. const a2 = alphaT.mul( alphaB );
  33664. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  33665. const v2 = v.dot( v );
  33666. const w2 = a2.div( v2 );
  33667. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  33668. } ).setLayout( {
  33669. name: 'D_GGX_Anisotropic',
  33670. type: 'float',
  33671. inputs: [
  33672. { name: 'alphaT', type: 'float', qualifier: 'in' },
  33673. { name: 'alphaB', type: 'float', qualifier: 'in' },
  33674. { name: 'dotNH', type: 'float', qualifier: 'in' },
  33675. { name: 'dotTH', type: 'float', qualifier: 'in' },
  33676. { name: 'dotBH', type: 'float', qualifier: 'in' }
  33677. ]
  33678. } );
  33679. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  33680. const BRDF_GGX = tslFn( ( inputs ) => {
  33681. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  33682. const normalView = inputs.normalView || transformedNormalView;
  33683. const alpha = roughness.pow2(); // UE4's roughness
  33684. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33685. const dotNL = normalView.dot( lightDirection ).clamp();
  33686. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33687. const dotNH = normalView.dot( halfDir ).clamp();
  33688. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  33689. let F = F_Schlick( { f0, f90, dotVH } );
  33690. let V, D;
  33691. if ( defined( USE_IRIDESCENCE ) ) {
  33692. F = iridescence.mix( F, f );
  33693. }
  33694. if ( defined( USE_ANISOTROPY ) ) {
  33695. const dotTL = anisotropyT.dot( lightDirection );
  33696. const dotTV = anisotropyT.dot( positionViewDirection );
  33697. const dotTH = anisotropyT.dot( halfDir );
  33698. const dotBL = anisotropyB.dot( lightDirection );
  33699. const dotBV = anisotropyB.dot( positionViewDirection );
  33700. const dotBH = anisotropyB.dot( halfDir );
  33701. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  33702. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  33703. } else {
  33704. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  33705. D = D_GGX( { alpha, dotNH } );
  33706. }
  33707. return F.mul( V ).mul( D );
  33708. } ); // validated
  33709. // Analytical approximation of the DFG LUT, one half of the
  33710. // split-sum approximation used in indirect specular lighting.
  33711. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  33712. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  33713. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  33714. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  33715. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  33716. const r = roughness.mul( c0 ).add( c1 );
  33717. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  33718. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  33719. return fab;
  33720. } ).setLayout( {
  33721. name: 'DFGApprox',
  33722. type: 'vec2',
  33723. inputs: [
  33724. { name: 'roughness', type: 'float' },
  33725. { name: 'dotNV', type: 'vec3' }
  33726. ]
  33727. } );
  33728. const EnvironmentBRDF = tslFn( ( inputs ) => {
  33729. const { dotNV, specularColor, specularF90, roughness } = inputs;
  33730. const fab = DFGApprox( { dotNV, roughness } );
  33731. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  33732. } );
  33733. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  33734. const x = dotVH.oneMinus().saturate();
  33735. const x2 = x.mul( x );
  33736. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  33737. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  33738. } ).setLayout( {
  33739. name: 'Schlick_to_F0',
  33740. type: 'vec3',
  33741. inputs: [
  33742. { name: 'f', type: 'vec3' },
  33743. { name: 'f90', type: 'float' },
  33744. { name: 'dotVH', type: 'float' }
  33745. ]
  33746. } );
  33747. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  33748. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  33749. const alpha = roughness.pow2();
  33750. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  33751. const invAlpha = float( 1.0 ).div( alpha );
  33752. const cos2h = dotNH.pow2();
  33753. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  33754. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  33755. } ).setLayout( {
  33756. name: 'D_Charlie',
  33757. type: 'float',
  33758. inputs: [
  33759. { name: 'roughness', type: 'float' },
  33760. { name: 'dotNH', type: 'float' }
  33761. ]
  33762. } );
  33763. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  33764. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  33765. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  33766. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  33767. } ).setLayout( {
  33768. name: 'V_Neubelt',
  33769. type: 'float',
  33770. inputs: [
  33771. { name: 'dotNV', type: 'float' },
  33772. { name: 'dotNL', type: 'float' }
  33773. ]
  33774. } );
  33775. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  33776. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33777. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33778. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  33779. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  33780. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  33781. const V = V_Neubelt( { dotNV, dotNL } );
  33782. return sheen.mul( D ).mul( V );
  33783. } );
  33784. // Rect Area Light
  33785. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  33786. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  33787. // code: https://github.com/selfshadow/ltc_code/
  33788. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  33789. const LUT_SIZE = 64.0;
  33790. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  33791. const LUT_BIAS = 0.5 / LUT_SIZE;
  33792. const dotNV = N.dot( V ).saturate();
  33793. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  33794. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  33795. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  33796. return uv;
  33797. } ).setLayout( {
  33798. name: 'LTC_Uv',
  33799. type: 'vec2',
  33800. inputs: [
  33801. { name: 'N', type: 'vec3' },
  33802. { name: 'V', type: 'vec3' },
  33803. { name: 'roughness', type: 'float' }
  33804. ]
  33805. } );
  33806. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  33807. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  33808. // An approximation of the form factor of a horizon-clipped rectangle.
  33809. const l = f.length();
  33810. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  33811. } ).setLayout( {
  33812. name: 'LTC_ClippedSphereFormFactor',
  33813. type: 'float',
  33814. inputs: [
  33815. { name: 'f', type: 'vec3' }
  33816. ]
  33817. } );
  33818. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  33819. const x = v1.dot( v2 );
  33820. const y = x.abs().toVar();
  33821. // rational polynomial approximation to theta / sin( theta ) / 2PI
  33822. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  33823. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  33824. const v = a.div( b );
  33825. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  33826. return v1.cross( v2 ).mul( theta_sintheta );
  33827. } ).setLayout( {
  33828. name: 'LTC_EdgeVectorFormFactor',
  33829. type: 'vec3',
  33830. inputs: [
  33831. { name: 'v1', type: 'vec3' },
  33832. { name: 'v2', type: 'vec3' }
  33833. ]
  33834. } );
  33835. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  33836. // bail if point is on back side of plane of light
  33837. // assumes ccw winding order of light vertices
  33838. const v1 = p1.sub( p0 ).toVar();
  33839. const v2 = p3.sub( p0 ).toVar();
  33840. const lightNormal = v1.cross( v2 );
  33841. const result = vec3().toVar();
  33842. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  33843. // construct orthonormal basis around N
  33844. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  33845. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  33846. // compute transform
  33847. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  33848. // transform rect
  33849. // & project rect onto sphere
  33850. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  33851. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  33852. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  33853. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  33854. // calculate vector form factor
  33855. const vectorFormFactor = vec3( 0 ).toVar();
  33856. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  33857. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  33858. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  33859. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  33860. // adjust for horizon clipping
  33861. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  33862. } );
  33863. return result;
  33864. } ).setLayout( {
  33865. name: 'LTC_Evaluate',
  33866. type: 'vec3',
  33867. inputs: [
  33868. { name: 'N', type: 'vec3' },
  33869. { name: 'V', type: 'vec3' },
  33870. { name: 'P', type: 'vec3' },
  33871. { name: 'mInv', type: 'mat3' },
  33872. { name: 'p0', type: 'vec3' },
  33873. { name: 'p1', type: 'vec3' },
  33874. { name: 'p2', type: 'vec3' },
  33875. { name: 'p3', type: 'vec3' }
  33876. ]
  33877. } );
  33878. //
  33879. // Transmission
  33880. //
  33881. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  33882. // Direction of refracted light.
  33883. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  33884. // Compute rotation-independant scaling of the model matrix.
  33885. const modelScale = vec3(
  33886. length( modelMatrix[ 0 ].xyz ),
  33887. length( modelMatrix[ 1 ].xyz ),
  33888. length( modelMatrix[ 2 ].xyz )
  33889. );
  33890. // The thickness is specified in local space.
  33891. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  33892. } ).setLayout( {
  33893. name: 'getVolumeTransmissionRay',
  33894. type: 'vec3',
  33895. inputs: [
  33896. { name: 'n', type: 'vec3' },
  33897. { name: 'v', type: 'vec3' },
  33898. { name: 'thickness', type: 'float' },
  33899. { name: 'ior', type: 'float' },
  33900. { name: 'modelMatrix', type: 'mat4' }
  33901. ]
  33902. } );
  33903. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  33904. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  33905. // an IOR of 1.5 results in the default amount of microfacet refraction.
  33906. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  33907. } ).setLayout( {
  33908. name: 'applyIorToRoughness',
  33909. type: 'float',
  33910. inputs: [
  33911. { name: 'roughness', type: 'float' },
  33912. { name: 'ior', type: 'float' }
  33913. ]
  33914. } );
  33915. const singleViewportMipTexture = viewportMipTexture();
  33916. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  33917. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  33918. //const transmissionSample = viewportMipTexture( fragCoord );
  33919. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  33920. return transmissionSample.bicubic( lod );
  33921. } );
  33922. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  33923. If( attenuationDistance.notEqual( 0 ), () => {
  33924. // Compute light attenuation using Beer's law.
  33925. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  33926. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  33927. return transmittance;
  33928. } );
  33929. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  33930. return vec3( 1.0 );
  33931. } ).setLayout( {
  33932. name: 'volumeAttenuation',
  33933. type: 'vec3',
  33934. inputs: [
  33935. { name: 'transmissionDistance', type: 'float' },
  33936. { name: 'attenuationColor', type: 'vec3' },
  33937. { name: 'attenuationDistance', type: 'float' }
  33938. ]
  33939. } );
  33940. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  33941. let transmittedLight, transmittance;
  33942. if ( dispersion ) {
  33943. transmittedLight = vec4().toVar();
  33944. transmittance = vec3().toVar();
  33945. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  33946. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  33947. loop( { start: 0, end: 3 }, ( { i } ) => {
  33948. const ior = iors.element( i );
  33949. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  33950. const refractedRayExit = position.add( transmissionRay );
  33951. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  33952. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  33953. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  33954. refractionCoords.addAssign( 1.0 );
  33955. refractionCoords.divAssign( 2.0 );
  33956. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  33957. // Sample framebuffer to get pixel the refracted ray hits.
  33958. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  33959. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  33960. transmittedLight.a.addAssign( transmissionSample.a );
  33961. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  33962. } );
  33963. transmittedLight.a.divAssign( 3.0 );
  33964. } else {
  33965. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  33966. const refractedRayExit = position.add( transmissionRay );
  33967. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  33968. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  33969. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  33970. refractionCoords.addAssign( 1.0 );
  33971. refractionCoords.divAssign( 2.0 );
  33972. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  33973. // Sample framebuffer to get pixel the refracted ray hits.
  33974. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  33975. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  33976. }
  33977. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  33978. const dotNV = n.dot( v ).clamp();
  33979. // Get the specular component.
  33980. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  33981. dotNV,
  33982. specularColor,
  33983. specularF90,
  33984. roughness
  33985. } ) );
  33986. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  33987. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  33988. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  33989. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  33990. } );
  33991. //
  33992. // Iridescence
  33993. //
  33994. // XYZ to linear-sRGB color space
  33995. const XYZ_TO_REC709 = mat3(
  33996. 3.2404542, - 0.9692660, 0.0556434,
  33997. - 1.5371385, 1.8760108, - 0.2040259,
  33998. - 0.4985314, 0.0415560, 1.0572252
  33999. );
  34000. // Assume air interface for top
  34001. // Note: We don't handle the case fresnel0 == 1
  34002. const Fresnel0ToIor = ( fresnel0 ) => {
  34003. const sqrtF0 = fresnel0.sqrt();
  34004. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  34005. };
  34006. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  34007. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  34008. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  34009. };
  34010. // Fresnel equations for dielectric/dielectric interfaces.
  34011. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  34012. // Evaluation XYZ sensitivity curves in Fourier space
  34013. const evalSensitivity = ( OPD, shift ) => {
  34014. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  34015. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  34016. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  34017. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  34018. 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() );
  34019. 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() );
  34020. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  34021. const rgb = XYZ_TO_REC709.mul( xyz );
  34022. return rgb;
  34023. };
  34024. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  34025. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  34026. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  34027. // Evaluate the cosTheta on the base layer (Snell law)
  34028. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  34029. // Handle TIR:
  34030. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  34031. /*if ( cosTheta2Sq < 0.0 ) {
  34032. return vec3( 1.0 );
  34033. }*/
  34034. const cosTheta2 = cosTheta2Sq.sqrt();
  34035. // First interface
  34036. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  34037. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  34038. //const R21 = R12;
  34039. const T121 = R12.oneMinus();
  34040. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  34041. const phi21 = float( Math.PI ).sub( phi12 );
  34042. // Second interface
  34043. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  34044. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  34045. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  34046. const phi23 = vec3(
  34047. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  34048. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  34049. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  34050. );
  34051. // Phase shift
  34052. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  34053. const phi = vec3( phi21 ).add( phi23 );
  34054. // Compound terms
  34055. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  34056. const r123 = R123.sqrt();
  34057. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  34058. // Reflectance term for m = 0 (DC term amplitude)
  34059. const C0 = R12.add( Rs );
  34060. let I = C0;
  34061. // Reflectance term for m > 0 (pairs of diracs)
  34062. let Cm = Rs.sub( T121 );
  34063. for ( let m = 1; m <= 2; ++ m ) {
  34064. Cm = Cm.mul( r123 );
  34065. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  34066. I = I.add( Cm.mul( Sm ) );
  34067. }
  34068. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  34069. return I.max( vec3( 0.0 ) );
  34070. } ).setLayout( {
  34071. name: 'evalIridescence',
  34072. type: 'vec3',
  34073. inputs: [
  34074. { name: 'outsideIOR', type: 'float' },
  34075. { name: 'eta2', type: 'float' },
  34076. { name: 'cosTheta1', type: 'float' },
  34077. { name: 'thinFilmThickness', type: 'float' },
  34078. { name: 'baseF0', type: 'vec3' }
  34079. ]
  34080. } );
  34081. //
  34082. // Sheen
  34083. //
  34084. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  34085. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  34086. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  34087. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  34088. const dotNV = normal.dot( viewDir ).saturate();
  34089. const r2 = roughness.pow2();
  34090. const a = cond(
  34091. roughness.lessThan( 0.25 ),
  34092. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  34093. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  34094. );
  34095. const b = cond(
  34096. roughness.lessThan( 0.25 ),
  34097. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  34098. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  34099. );
  34100. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  34101. return DG.mul( 1.0 / Math.PI ).saturate();
  34102. } );
  34103. const clearcoatF0 = vec3( 0.04 );
  34104. const clearcoatF90 = float( 1 );
  34105. //
  34106. class PhysicalLightingModel extends LightingModel {
  34107. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  34108. super();
  34109. this.clearcoat = clearcoat;
  34110. this.sheen = sheen;
  34111. this.iridescence = iridescence;
  34112. this.anisotropy = anisotropy;
  34113. this.transmission = transmission;
  34114. this.dispersion = dispersion;
  34115. this.clearcoatRadiance = null;
  34116. this.clearcoatSpecularDirect = null;
  34117. this.clearcoatSpecularIndirect = null;
  34118. this.sheenSpecularDirect = null;
  34119. this.sheenSpecularIndirect = null;
  34120. this.iridescenceFresnel = null;
  34121. this.iridescenceF0 = null;
  34122. }
  34123. start( context ) {
  34124. if ( this.clearcoat === true ) {
  34125. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  34126. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  34127. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  34128. }
  34129. if ( this.sheen === true ) {
  34130. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  34131. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  34132. }
  34133. if ( this.iridescence === true ) {
  34134. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  34135. this.iridescenceFresnel = evalIridescence( {
  34136. outsideIOR: float( 1.0 ),
  34137. eta2: iridescenceIOR,
  34138. cosTheta1: dotNVi,
  34139. thinFilmThickness: iridescenceThickness,
  34140. baseF0: specularColor
  34141. } );
  34142. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  34143. }
  34144. if ( this.transmission === true ) {
  34145. const position = positionWorld;
  34146. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  34147. const n = transformedNormalWorld;
  34148. context.backdrop = getIBLVolumeRefraction(
  34149. n,
  34150. v,
  34151. roughness,
  34152. diffuseColor,
  34153. specularColor,
  34154. specularF90, // specularF90
  34155. position, // positionWorld
  34156. modelWorldMatrix, // modelMatrix
  34157. cameraViewMatrix, // viewMatrix
  34158. cameraProjectionMatrix, // projMatrix
  34159. ior,
  34160. thickness,
  34161. attenuationColor,
  34162. attenuationDistance,
  34163. this.dispersion ? dispersion : null
  34164. );
  34165. context.backdropAlpha = transmission;
  34166. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  34167. }
  34168. }
  34169. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  34170. // Approximates multiscattering in order to preserve energy.
  34171. // http://www.jcgt.org/published/0008/01/03/
  34172. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  34173. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  34174. const fab = DFGApprox( { roughness, dotNV } );
  34175. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  34176. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  34177. const Ess = fab.x.add( fab.y );
  34178. const Ems = Ess.oneMinus();
  34179. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  34180. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  34181. singleScatter.addAssign( FssEss );
  34182. multiScatter.addAssign( Fms.mul( Ems ) );
  34183. }
  34184. direct( { lightDirection, lightColor, reflectedLight } ) {
  34185. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  34186. const irradiance = dotNL.mul( lightColor );
  34187. if ( this.sheen === true ) {
  34188. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  34189. }
  34190. if ( this.clearcoat === true ) {
  34191. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  34192. const ccIrradiance = dotNLcc.mul( lightColor );
  34193. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  34194. }
  34195. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  34196. 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 } ) ) );
  34197. }
  34198. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  34199. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  34200. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  34201. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  34202. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  34203. const N = transformedNormalView;
  34204. const V = positionViewDirection;
  34205. const P = positionView.toVar();
  34206. const uv = LTC_Uv( { N, V, roughness } );
  34207. const t1 = ltc_1.uv( uv ).toVar();
  34208. const t2 = ltc_2.uv( uv ).toVar();
  34209. const mInv = mat3(
  34210. vec3( t1.x, 0, t1.y ),
  34211. vec3( 0, 1, 0 ),
  34212. vec3( t1.z, 0, t1.w )
  34213. ).toVar();
  34214. // LTC Fresnel Approximation by Stephen Hill
  34215. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  34216. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  34217. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  34218. 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 } ) ) );
  34219. }
  34220. indirect( context, stack, builder ) {
  34221. this.indirectDiffuse( context, stack, builder );
  34222. this.indirectSpecular( context, stack, builder );
  34223. this.ambientOcclusion( context, stack, builder );
  34224. }
  34225. indirectDiffuse( { irradiance, reflectedLight } ) {
  34226. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  34227. }
  34228. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  34229. if ( this.sheen === true ) {
  34230. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  34231. sheen,
  34232. IBLSheenBRDF( {
  34233. normal: transformedNormalView,
  34234. viewDir: positionViewDirection,
  34235. roughness: sheenRoughness
  34236. } )
  34237. ) );
  34238. }
  34239. if ( this.clearcoat === true ) {
  34240. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  34241. const clearcoatEnv = EnvironmentBRDF( {
  34242. dotNV: dotNVcc,
  34243. specularColor: clearcoatF0,
  34244. specularF90: clearcoatF90,
  34245. roughness: clearcoatRoughness
  34246. } );
  34247. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  34248. }
  34249. // Both indirect specular and indirect diffuse light accumulate here
  34250. const singleScattering = vec3().temp( 'singleScattering' );
  34251. const multiScattering = vec3().temp( 'multiScattering' );
  34252. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  34253. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  34254. const totalScattering = singleScattering.add( multiScattering );
  34255. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  34256. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  34257. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  34258. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  34259. }
  34260. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  34261. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  34262. const aoNV = dotNV.add( ambientOcclusion );
  34263. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  34264. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  34265. if ( this.clearcoat === true ) {
  34266. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  34267. }
  34268. if ( this.sheen === true ) {
  34269. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  34270. }
  34271. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  34272. reflectedLight.indirectSpecular.mulAssign( aoNode );
  34273. }
  34274. finish( context ) {
  34275. const { outgoingLight } = context;
  34276. if ( this.clearcoat === true ) {
  34277. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  34278. const Fcc = F_Schlick( {
  34279. dotVH: dotNVcc,
  34280. f0: clearcoatF0,
  34281. f90: clearcoatF90
  34282. } );
  34283. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  34284. outgoingLight.assign( clearcoatLight );
  34285. }
  34286. if ( this.sheen === true ) {
  34287. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  34288. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  34289. outgoingLight.assign( sheenLight );
  34290. }
  34291. }
  34292. }
  34293. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  34294. class MeshStandardNodeMaterial extends NodeMaterial {
  34295. constructor( parameters ) {
  34296. super();
  34297. this.isMeshStandardNodeMaterial = true;
  34298. this.emissiveNode = null;
  34299. this.metalnessNode = null;
  34300. this.roughnessNode = null;
  34301. this.setDefaultValues( _defaultValues$6 );
  34302. this.setValues( parameters );
  34303. }
  34304. setupEnvironment( builder ) {
  34305. const envNode = super.setupEnvironment( builder );
  34306. return envNode ? new EnvironmentNode( envNode ) : null;
  34307. }
  34308. setupLightingModel( /*builder*/ ) {
  34309. return new PhysicalLightingModel();
  34310. }
  34311. setupSpecular() {
  34312. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  34313. specularColor.assign( specularColorNode );
  34314. specularF90.assign( 1.0 );
  34315. }
  34316. setupVariants() {
  34317. // METALNESS
  34318. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  34319. metalness.assign( metalnessNode );
  34320. // ROUGHNESS
  34321. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  34322. roughnessNode = getRoughness( { roughness: roughnessNode } );
  34323. roughness.assign( roughnessNode );
  34324. // SPECULAR COLOR
  34325. this.setupSpecular();
  34326. // DIFFUSE COLOR
  34327. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  34328. }
  34329. copy( source ) {
  34330. this.emissiveNode = source.emissiveNode;
  34331. this.metalnessNode = source.metalnessNode;
  34332. this.roughnessNode = source.roughnessNode;
  34333. return super.copy( source );
  34334. }
  34335. }
  34336. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  34337. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  34338. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  34339. constructor( parameters ) {
  34340. super();
  34341. this.isMeshPhysicalNodeMaterial = true;
  34342. this.clearcoatNode = null;
  34343. this.clearcoatRoughnessNode = null;
  34344. this.clearcoatNormalNode = null;
  34345. this.sheenNode = null;
  34346. this.sheenRoughnessNode = null;
  34347. this.iridescenceNode = null;
  34348. this.iridescenceIORNode = null;
  34349. this.iridescenceThicknessNode = null;
  34350. this.specularIntensityNode = null;
  34351. this.specularColorNode = null;
  34352. this.iorNode = null;
  34353. this.transmissionNode = null;
  34354. this.thicknessNode = null;
  34355. this.attenuationDistanceNode = null;
  34356. this.attenuationColorNode = null;
  34357. this.dispersionNode = null;
  34358. this.anisotropyNode = null;
  34359. this.setDefaultValues( _defaultValues$5 );
  34360. this.setValues( parameters );
  34361. }
  34362. get useClearcoat() {
  34363. return this.clearcoat > 0 || this.clearcoatNode !== null;
  34364. }
  34365. get useIridescence() {
  34366. return this.iridescence > 0 || this.iridescenceNode !== null;
  34367. }
  34368. get useSheen() {
  34369. return this.sheen > 0 || this.sheenNode !== null;
  34370. }
  34371. get useAnisotropy() {
  34372. return this.anisotropy > 0 || this.anisotropyNode !== null;
  34373. }
  34374. get useTransmission() {
  34375. return this.transmission > 0 || this.transmissionNode !== null;
  34376. }
  34377. get useDispersion() {
  34378. return this.dispersion > 0 || this.dispersionNode !== null;
  34379. }
  34380. setupSpecular() {
  34381. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  34382. ior.assign( iorNode );
  34383. 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 ) );
  34384. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  34385. }
  34386. setupLightingModel( /*builder*/ ) {
  34387. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  34388. }
  34389. setupVariants( builder ) {
  34390. super.setupVariants( builder );
  34391. // CLEARCOAT
  34392. if ( this.useClearcoat ) {
  34393. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  34394. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  34395. clearcoat.assign( clearcoatNode );
  34396. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  34397. }
  34398. // SHEEN
  34399. if ( this.useSheen ) {
  34400. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  34401. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  34402. sheen.assign( sheenNode );
  34403. sheenRoughness.assign( sheenRoughnessNode );
  34404. }
  34405. // IRIDESCENCE
  34406. if ( this.useIridescence ) {
  34407. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  34408. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  34409. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  34410. iridescence.assign( iridescenceNode );
  34411. iridescenceIOR.assign( iridescenceIORNode );
  34412. iridescenceThickness.assign( iridescenceThicknessNode );
  34413. }
  34414. // ANISOTROPY
  34415. if ( this.useAnisotropy ) {
  34416. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  34417. anisotropy.assign( anisotropyV.length() );
  34418. If( anisotropy.equal( 0.0 ), () => {
  34419. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  34420. } ).else( () => {
  34421. anisotropyV.divAssign( vec2( anisotropy ) );
  34422. anisotropy.assign( anisotropy.saturate() );
  34423. } );
  34424. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  34425. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  34426. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  34427. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  34428. }
  34429. // TRANSMISSION
  34430. if ( this.useTransmission ) {
  34431. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  34432. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  34433. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  34434. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  34435. transmission.assign( transmissionNode );
  34436. thickness.assign( thicknessNode );
  34437. attenuationDistance.assign( attenuationDistanceNode );
  34438. attenuationColor.assign( attenuationColorNode );
  34439. if ( this.useDispersion ) {
  34440. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  34441. dispersion.assign( dispersionNode );
  34442. }
  34443. }
  34444. }
  34445. setupNormal( builder ) {
  34446. super.setupNormal( builder );
  34447. // CLEARCOAT NORMAL
  34448. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  34449. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  34450. }
  34451. copy( source ) {
  34452. this.clearcoatNode = source.clearcoatNode;
  34453. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  34454. this.clearcoatNormalNode = source.clearcoatNormalNode;
  34455. this.sheenNode = source.sheenNode;
  34456. this.sheenRoughnessNode = source.sheenRoughnessNode;
  34457. this.iridescenceNode = source.iridescenceNode;
  34458. this.iridescenceIORNode = source.iridescenceIORNode;
  34459. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  34460. this.specularIntensityNode = source.specularIntensityNode;
  34461. this.specularColorNode = source.specularColorNode;
  34462. this.transmissionNode = source.transmissionNode;
  34463. this.thicknessNode = source.thicknessNode;
  34464. this.attenuationDistanceNode = source.attenuationDistanceNode;
  34465. this.attenuationColorNode = source.attenuationColorNode;
  34466. this.dispersionNode = source.dispersionNode;
  34467. this.anisotropyNode = source.anisotropyNode;
  34468. return super.copy( source );
  34469. }
  34470. }
  34471. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  34472. class SSSLightingModel extends PhysicalLightingModel {
  34473. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  34474. super( useClearcoat, useSheen, useIridescence );
  34475. this.useSSS = useSSS;
  34476. }
  34477. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  34478. if ( this.useSSS === true ) {
  34479. const material = builder.material;
  34480. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  34481. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  34482. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  34483. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  34484. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  34485. }
  34486. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  34487. }
  34488. }
  34489. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  34490. constructor( parameters ) {
  34491. super( parameters );
  34492. this.thicknessColorNode = null;
  34493. this.thicknessDistortionNode = float( 0.1 );
  34494. this.thicknessAmbientNode = float( 0.0 );
  34495. this.thicknessAttenuationNode = float( .1 );
  34496. this.thicknessPowerNode = float( 2.0 );
  34497. this.thicknessScaleNode = float( 10.0 );
  34498. }
  34499. get useSSS() {
  34500. return this.thicknessColorNode !== null;
  34501. }
  34502. setupLightingModel( /*builder*/ ) {
  34503. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  34504. }
  34505. copy( source ) {
  34506. this.thicknessColorNode = source.thicknessColorNode;
  34507. this.thicknessDistortionNode = source.thicknessDistortionNode;
  34508. this.thicknessAmbientNode = source.thicknessAmbientNode;
  34509. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  34510. this.thicknessPowerNode = source.thicknessPowerNode;
  34511. this.thicknessScaleNode = source.thicknessScaleNode;
  34512. return super.copy( source );
  34513. }
  34514. }
  34515. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  34516. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  34517. // dotNL will be from -1.0 to 1.0
  34518. const dotNL = normal.dot( lightDirection );
  34519. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  34520. if ( builder.material.gradientMap ) {
  34521. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  34522. return vec3( gradientMap.r );
  34523. } else {
  34524. const fw = coord.fwidth().mul( 0.5 );
  34525. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  34526. }
  34527. } );
  34528. class ToonLightingModel extends LightingModel {
  34529. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  34530. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  34531. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  34532. }
  34533. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  34534. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  34535. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  34536. }
  34537. }
  34538. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  34539. class MeshToonNodeMaterial extends NodeMaterial {
  34540. constructor( parameters ) {
  34541. super();
  34542. this.isMeshToonNodeMaterial = true;
  34543. this.lights = true;
  34544. this.setDefaultValues( _defaultValues$4 );
  34545. this.setValues( parameters );
  34546. }
  34547. setupLightingModel( /*builder*/ ) {
  34548. return new ToonLightingModel();
  34549. }
  34550. }
  34551. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  34552. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  34553. class MeshMatcapNodeMaterial extends NodeMaterial {
  34554. constructor( parameters ) {
  34555. super();
  34556. this.lights = false;
  34557. this.isMeshMatcapNodeMaterial = true;
  34558. this.setDefaultValues( _defaultValues$3 );
  34559. this.setValues( parameters );
  34560. }
  34561. setupVariants( builder ) {
  34562. const uv = matcapUV;
  34563. let matcapColor;
  34564. if ( builder.material.matcap ) {
  34565. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  34566. } else {
  34567. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  34568. }
  34569. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  34570. }
  34571. }
  34572. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  34573. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  34574. class PointsNodeMaterial extends NodeMaterial {
  34575. constructor( parameters ) {
  34576. super();
  34577. this.isPointsNodeMaterial = true;
  34578. this.lights = false;
  34579. this.normals = false;
  34580. this.transparent = true;
  34581. this.sizeNode = null;
  34582. this.setDefaultValues( _defaultValues$2 );
  34583. this.setValues( parameters );
  34584. }
  34585. copy( source ) {
  34586. this.sizeNode = source.sizeNode;
  34587. return super.copy( source );
  34588. }
  34589. }
  34590. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  34591. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  34592. class SpriteNodeMaterial extends NodeMaterial {
  34593. constructor( parameters ) {
  34594. super();
  34595. this.isSpriteNodeMaterial = true;
  34596. this.lights = false;
  34597. this.normals = false;
  34598. this.positionNode = null;
  34599. this.rotationNode = null;
  34600. this.scaleNode = null;
  34601. this.setDefaultValues( _defaultValues$1 );
  34602. this.setValues( parameters );
  34603. }
  34604. setupPosition( { object, context } ) {
  34605. // < VERTEX STAGE >
  34606. const { positionNode, rotationNode, scaleNode } = this;
  34607. const vertex = positionLocal;
  34608. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  34609. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  34610. if ( scaleNode !== null ) {
  34611. scale = scale.mul( scaleNode );
  34612. }
  34613. let alignedPosition = vertex.xy;
  34614. if ( object.center && object.center.isVector2 === true ) {
  34615. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  34616. }
  34617. alignedPosition = alignedPosition.mul( scale );
  34618. const rotation = float( rotationNode || materialRotation );
  34619. const rotatedPosition = alignedPosition.rotate( rotation );
  34620. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  34621. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  34622. context.vertex = vertex;
  34623. return modelViewProjection;
  34624. }
  34625. copy( source ) {
  34626. this.positionNode = source.positionNode;
  34627. this.rotationNode = source.rotationNode;
  34628. this.scaleNode = source.scaleNode;
  34629. return super.copy( source );
  34630. }
  34631. }
  34632. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  34633. class ShadowMaskModel extends LightingModel {
  34634. constructor() {
  34635. super();
  34636. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  34637. }
  34638. direct( { shadowMask } ) {
  34639. this.shadowNode.mulAssign( shadowMask );
  34640. }
  34641. finish( context ) {
  34642. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  34643. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  34644. }
  34645. }
  34646. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  34647. class ShadowNodeMaterial extends NodeMaterial {
  34648. constructor( parameters ) {
  34649. super();
  34650. this.isShadowNodeMaterial = true;
  34651. this.lights = true;
  34652. this.setDefaultValues( _defaultValues );
  34653. this.setValues( parameters );
  34654. }
  34655. setupLightingModel( /*builder*/ ) {
  34656. return new ShadowMaskModel();
  34657. }
  34658. }
  34659. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  34660. class VolumeNodeMaterial extends NodeMaterial {
  34661. constructor( params = {} ) {
  34662. super();
  34663. this.normals = false;
  34664. this.lights = false;
  34665. this.isVolumeNodeMaterial = true;
  34666. this.testNode = null;
  34667. this.setValues( params );
  34668. }
  34669. setup( builder ) {
  34670. const map = texture3D( this.map, null, 0 );
  34671. const hitBox = tslFn( ( { orig, dir } ) => {
  34672. const box_min = vec3( - 0.5 );
  34673. const box_max = vec3( 0.5 );
  34674. const inv_dir = dir.reciprocal();
  34675. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  34676. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  34677. const tmin = min$1( tmin_tmp, tmax_tmp );
  34678. const tmax = max$1( tmin_tmp, tmax_tmp );
  34679. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  34680. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  34681. return vec2( t0, t1 );
  34682. } );
  34683. this.fragmentNode = tslFn( () => {
  34684. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  34685. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  34686. const rayDir = vDirection.normalize();
  34687. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  34688. bounds.x.greaterThan( bounds.y ).discard();
  34689. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  34690. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  34691. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  34692. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  34693. delta.divAssign( materialReference( 'steps', 'float' ) );
  34694. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  34695. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  34696. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  34697. if ( this.testNode !== null ) {
  34698. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  34699. } else {
  34700. // default to show surface of mesh
  34701. ac.a.assign( 1 );
  34702. Break();
  34703. }
  34704. p.addAssign( rayDir.mul( delta ) );
  34705. } );
  34706. ac.a.equal( 0 ).discard();
  34707. return vec4( ac );
  34708. } )();
  34709. super.setup( builder );
  34710. }
  34711. }
  34712. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  34713. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  34714. MaterialLoader.createMaterialFromType = function ( type ) {
  34715. const material = createNodeMaterialFromType( type );
  34716. if ( material !== undefined ) {
  34717. return material;
  34718. }
  34719. return superFromTypeFunction.call( this, type );
  34720. };
  34721. class NodeMaterialLoader extends MaterialLoader {
  34722. constructor( manager ) {
  34723. super( manager );
  34724. this.nodes = {};
  34725. }
  34726. parse( json ) {
  34727. const material = super.parse( json );
  34728. const nodes = this.nodes;
  34729. const inputNodes = json.inputNodes;
  34730. for ( const property in inputNodes ) {
  34731. const uuid = inputNodes[ property ];
  34732. material[ property ] = nodes[ uuid ];
  34733. }
  34734. return material;
  34735. }
  34736. setNodes( value ) {
  34737. this.nodes = value;
  34738. return this;
  34739. }
  34740. }
  34741. class NodeObjectLoader extends ObjectLoader {
  34742. constructor( manager ) {
  34743. super( manager );
  34744. this._nodesJSON = null;
  34745. }
  34746. parse( json, onLoad ) {
  34747. this._nodesJSON = json.nodes;
  34748. const data = super.parse( json, onLoad );
  34749. this._nodesJSON = null; // dispose
  34750. return data;
  34751. }
  34752. parseNodes( json, textures ) {
  34753. if ( json !== undefined ) {
  34754. const loader = new NodeLoader();
  34755. loader.setTextures( textures );
  34756. return loader.parseNodes( json );
  34757. }
  34758. return {};
  34759. }
  34760. parseMaterials( json, textures ) {
  34761. const materials = {};
  34762. if ( json !== undefined ) {
  34763. const nodes = this.parseNodes( this._nodesJSON, textures );
  34764. const loader = new NodeMaterialLoader();
  34765. loader.setTextures( textures );
  34766. loader.setNodes( nodes );
  34767. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34768. const data = json[ i ];
  34769. materials[ data.uuid ] = loader.parse( data );
  34770. }
  34771. }
  34772. return materials;
  34773. }
  34774. }
  34775. class NodeParser {
  34776. parseFunction( /*source*/ ) {
  34777. console.warn( 'Abstract function.' );
  34778. }
  34779. }
  34780. class NodeFunction {
  34781. constructor( type, inputs, name = '', precision = '' ) {
  34782. this.type = type;
  34783. this.inputs = inputs;
  34784. this.name = name;
  34785. this.precision = precision;
  34786. }
  34787. getCode( /*name = this.name*/ ) {
  34788. console.warn( 'Abstract function.' );
  34789. }
  34790. }
  34791. NodeFunction.isNodeFunction = true;
  34792. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  34793. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  34794. const pragmaMain = '#pragma main';
  34795. const parse$1 = ( source ) => {
  34796. source = source.trim();
  34797. const pragmaMainIndex = source.indexOf( pragmaMain );
  34798. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  34799. const declaration = mainCode.match( declarationRegexp$1 );
  34800. if ( declaration !== null && declaration.length === 5 ) {
  34801. // tokenizer
  34802. const inputsCode = declaration[ 4 ];
  34803. const propsMatches = [];
  34804. let nameMatch = null;
  34805. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  34806. propsMatches.push( nameMatch );
  34807. }
  34808. // parser
  34809. const inputs = [];
  34810. let i = 0;
  34811. while ( i < propsMatches.length ) {
  34812. const isConst = propsMatches[ i ][ 0 ] === 'const';
  34813. if ( isConst === true ) {
  34814. i ++;
  34815. }
  34816. let qualifier = propsMatches[ i ][ 0 ];
  34817. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  34818. i ++;
  34819. } else {
  34820. qualifier = '';
  34821. }
  34822. const type = propsMatches[ i ++ ][ 0 ];
  34823. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  34824. if ( Number.isNaN( count ) === false ) i ++;
  34825. else count = null;
  34826. const name = propsMatches[ i ++ ][ 0 ];
  34827. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  34828. }
  34829. //
  34830. const blockCode = mainCode.substring( declaration[ 0 ].length );
  34831. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  34832. const type = declaration[ 2 ];
  34833. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  34834. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  34835. return {
  34836. type,
  34837. inputs,
  34838. name,
  34839. precision,
  34840. inputsCode,
  34841. blockCode,
  34842. headerCode
  34843. };
  34844. } else {
  34845. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34846. }
  34847. };
  34848. class GLSLNodeFunction extends NodeFunction {
  34849. constructor( source ) {
  34850. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34851. super( type, inputs, name, precision );
  34852. this.inputsCode = inputsCode;
  34853. this.blockCode = blockCode;
  34854. this.headerCode = headerCode;
  34855. }
  34856. getCode( name = this.name ) {
  34857. let code;
  34858. const blockCode = this.blockCode;
  34859. if ( blockCode !== '' ) {
  34860. const { type, inputsCode, headerCode, precision } = this;
  34861. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  34862. if ( precision !== '' ) {
  34863. declarationCode = `${ precision } ${ declarationCode }`;
  34864. }
  34865. code = headerCode + declarationCode + blockCode;
  34866. } else {
  34867. // interface function
  34868. code = '';
  34869. }
  34870. return code;
  34871. }
  34872. }
  34873. class GLSLNodeParser extends NodeParser {
  34874. parseFunction( source ) {
  34875. return new GLSLNodeFunction( source );
  34876. }
  34877. }
  34878. // Three.js Transpiler
  34879. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  34880. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  34881. const f = float( f_immutable ).toVar();
  34882. const t = float( t_immutable ).toVar();
  34883. const b = bool( b_immutable ).toVar();
  34884. return cond( b, t, f );
  34885. } ).setLayout( {
  34886. name: 'mx_select',
  34887. type: 'float',
  34888. inputs: [
  34889. { name: 'b', type: 'bool' },
  34890. { name: 't', type: 'float' },
  34891. { name: 'f', type: 'float' }
  34892. ]
  34893. } );
  34894. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  34895. const b = bool( b_immutable ).toVar();
  34896. const val = float( val_immutable ).toVar();
  34897. return cond( b, val.negate(), val );
  34898. } ).setLayout( {
  34899. name: 'mx_negate_if',
  34900. type: 'float',
  34901. inputs: [
  34902. { name: 'val', type: 'float' },
  34903. { name: 'b', type: 'bool' }
  34904. ]
  34905. } );
  34906. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  34907. const x = float( x_immutable ).toVar();
  34908. return int( floor( x ) );
  34909. } ).setLayout( {
  34910. name: 'mx_floor',
  34911. type: 'int',
  34912. inputs: [
  34913. { name: 'x', type: 'float' }
  34914. ]
  34915. } );
  34916. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  34917. const x = float( x_immutable ).toVar();
  34918. i.assign( mx_floor( x ) );
  34919. return x.sub( float( i ) );
  34920. } );
  34921. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  34922. const t = float( t_immutable ).toVar();
  34923. const s = float( s_immutable ).toVar();
  34924. const v3 = float( v3_immutable ).toVar();
  34925. const v2 = float( v2_immutable ).toVar();
  34926. const v1 = float( v1_immutable ).toVar();
  34927. const v0 = float( v0_immutable ).toVar();
  34928. const s1 = float( sub( 1.0, s ) ).toVar();
  34929. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34930. } ).setLayout( {
  34931. name: 'mx_bilerp_0',
  34932. type: 'float',
  34933. inputs: [
  34934. { name: 'v0', type: 'float' },
  34935. { name: 'v1', type: 'float' },
  34936. { name: 'v2', type: 'float' },
  34937. { name: 'v3', type: 'float' },
  34938. { name: 's', type: 'float' },
  34939. { name: 't', type: 'float' }
  34940. ]
  34941. } );
  34942. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  34943. const t = float( t_immutable ).toVar();
  34944. const s = float( s_immutable ).toVar();
  34945. const v3 = vec3( v3_immutable ).toVar();
  34946. const v2 = vec3( v2_immutable ).toVar();
  34947. const v1 = vec3( v1_immutable ).toVar();
  34948. const v0 = vec3( v0_immutable ).toVar();
  34949. const s1 = float( sub( 1.0, s ) ).toVar();
  34950. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34951. } ).setLayout( {
  34952. name: 'mx_bilerp_1',
  34953. type: 'vec3',
  34954. inputs: [
  34955. { name: 'v0', type: 'vec3' },
  34956. { name: 'v1', type: 'vec3' },
  34957. { name: 'v2', type: 'vec3' },
  34958. { name: 'v3', type: 'vec3' },
  34959. { name: 's', type: 'float' },
  34960. { name: 't', type: 'float' }
  34961. ]
  34962. } );
  34963. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  34964. const mx_trilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  34965. const r = float( r_immutable ).toVar();
  34966. const t = float( t_immutable ).toVar();
  34967. const s = float( s_immutable ).toVar();
  34968. const v7 = float( v7_immutable ).toVar();
  34969. const v6 = float( v6_immutable ).toVar();
  34970. const v5 = float( v5_immutable ).toVar();
  34971. const v4 = float( v4_immutable ).toVar();
  34972. const v3 = float( v3_immutable ).toVar();
  34973. const v2 = float( v2_immutable ).toVar();
  34974. const v1 = float( v1_immutable ).toVar();
  34975. const v0 = float( v0_immutable ).toVar();
  34976. const s1 = float( sub( 1.0, s ) ).toVar();
  34977. const t1 = float( sub( 1.0, t ) ).toVar();
  34978. const r1 = float( sub( 1.0, r ) ).toVar();
  34979. 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 ) ) ) ) ) );
  34980. } ).setLayout( {
  34981. name: 'mx_trilerp_0',
  34982. type: 'float',
  34983. inputs: [
  34984. { name: 'v0', type: 'float' },
  34985. { name: 'v1', type: 'float' },
  34986. { name: 'v2', type: 'float' },
  34987. { name: 'v3', type: 'float' },
  34988. { name: 'v4', type: 'float' },
  34989. { name: 'v5', type: 'float' },
  34990. { name: 'v6', type: 'float' },
  34991. { name: 'v7', type: 'float' },
  34992. { name: 's', type: 'float' },
  34993. { name: 't', type: 'float' },
  34994. { name: 'r', type: 'float' }
  34995. ]
  34996. } );
  34997. const mx_trilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  34998. const r = float( r_immutable ).toVar();
  34999. const t = float( t_immutable ).toVar();
  35000. const s = float( s_immutable ).toVar();
  35001. const v7 = vec3( v7_immutable ).toVar();
  35002. const v6 = vec3( v6_immutable ).toVar();
  35003. const v5 = vec3( v5_immutable ).toVar();
  35004. const v4 = vec3( v4_immutable ).toVar();
  35005. const v3 = vec3( v3_immutable ).toVar();
  35006. const v2 = vec3( v2_immutable ).toVar();
  35007. const v1 = vec3( v1_immutable ).toVar();
  35008. const v0 = vec3( v0_immutable ).toVar();
  35009. const s1 = float( sub( 1.0, s ) ).toVar();
  35010. const t1 = float( sub( 1.0, t ) ).toVar();
  35011. const r1 = float( sub( 1.0, r ) ).toVar();
  35012. 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 ) ) ) ) ) );
  35013. } ).setLayout( {
  35014. name: 'mx_trilerp_1',
  35015. type: 'vec3',
  35016. inputs: [
  35017. { name: 'v0', type: 'vec3' },
  35018. { name: 'v1', type: 'vec3' },
  35019. { name: 'v2', type: 'vec3' },
  35020. { name: 'v3', type: 'vec3' },
  35021. { name: 'v4', type: 'vec3' },
  35022. { name: 'v5', type: 'vec3' },
  35023. { name: 'v6', type: 'vec3' },
  35024. { name: 'v7', type: 'vec3' },
  35025. { name: 's', type: 'float' },
  35026. { name: 't', type: 'float' },
  35027. { name: 'r', type: 'float' }
  35028. ]
  35029. } );
  35030. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  35031. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35032. const y = float( y_immutable ).toVar();
  35033. const x = float( x_immutable ).toVar();
  35034. const hash = uint( hash_immutable ).toVar();
  35035. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  35036. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  35037. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  35038. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35039. } ).setLayout( {
  35040. name: 'mx_gradient_float_0',
  35041. type: 'float',
  35042. inputs: [
  35043. { name: 'hash', type: 'uint' },
  35044. { name: 'x', type: 'float' },
  35045. { name: 'y', type: 'float' }
  35046. ]
  35047. } );
  35048. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35049. const z = float( z_immutable ).toVar();
  35050. const y = float( y_immutable ).toVar();
  35051. const x = float( x_immutable ).toVar();
  35052. const hash = uint( hash_immutable ).toVar();
  35053. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  35054. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  35055. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  35056. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35057. } ).setLayout( {
  35058. name: 'mx_gradient_float_1',
  35059. type: 'float',
  35060. inputs: [
  35061. { name: 'hash', type: 'uint' },
  35062. { name: 'x', type: 'float' },
  35063. { name: 'y', type: 'float' },
  35064. { name: 'z', type: 'float' }
  35065. ]
  35066. } );
  35067. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  35068. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35069. const y = float( y_immutable ).toVar();
  35070. const x = float( x_immutable ).toVar();
  35071. const hash = uvec3( hash_immutable ).toVar();
  35072. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  35073. } ).setLayout( {
  35074. name: 'mx_gradient_vec3_0',
  35075. type: 'vec3',
  35076. inputs: [
  35077. { name: 'hash', type: 'uvec3' },
  35078. { name: 'x', type: 'float' },
  35079. { name: 'y', type: 'float' }
  35080. ]
  35081. } );
  35082. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35083. const z = float( z_immutable ).toVar();
  35084. const y = float( y_immutable ).toVar();
  35085. const x = float( x_immutable ).toVar();
  35086. const hash = uvec3( hash_immutable ).toVar();
  35087. 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 ) );
  35088. } ).setLayout( {
  35089. name: 'mx_gradient_vec3_1',
  35090. type: 'vec3',
  35091. inputs: [
  35092. { name: 'hash', type: 'uvec3' },
  35093. { name: 'x', type: 'float' },
  35094. { name: 'y', type: 'float' },
  35095. { name: 'z', type: 'float' }
  35096. ]
  35097. } );
  35098. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  35099. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35100. const v = float( v_immutable ).toVar();
  35101. return mul( 0.6616, v );
  35102. } ).setLayout( {
  35103. name: 'mx_gradient_scale2d_0',
  35104. type: 'float',
  35105. inputs: [
  35106. { name: 'v', type: 'float' }
  35107. ]
  35108. } );
  35109. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35110. const v = float( v_immutable ).toVar();
  35111. return mul( 0.9820, v );
  35112. } ).setLayout( {
  35113. name: 'mx_gradient_scale3d_0',
  35114. type: 'float',
  35115. inputs: [
  35116. { name: 'v', type: 'float' }
  35117. ]
  35118. } );
  35119. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35120. const v = vec3( v_immutable ).toVar();
  35121. return mul( 0.6616, v );
  35122. } ).setLayout( {
  35123. name: 'mx_gradient_scale2d_1',
  35124. type: 'vec3',
  35125. inputs: [
  35126. { name: 'v', type: 'vec3' }
  35127. ]
  35128. } );
  35129. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  35130. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35131. const v = vec3( v_immutable ).toVar();
  35132. return mul( 0.9820, v );
  35133. } ).setLayout( {
  35134. name: 'mx_gradient_scale3d_1',
  35135. type: 'vec3',
  35136. inputs: [
  35137. { name: 'v', type: 'vec3' }
  35138. ]
  35139. } );
  35140. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  35141. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  35142. const k = int( k_immutable ).toVar();
  35143. const x = uint( x_immutable ).toVar();
  35144. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  35145. } ).setLayout( {
  35146. name: 'mx_rotl32',
  35147. type: 'uint',
  35148. inputs: [
  35149. { name: 'x', type: 'uint' },
  35150. { name: 'k', type: 'int' }
  35151. ]
  35152. } );
  35153. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  35154. a.subAssign( c );
  35155. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  35156. c.addAssign( b );
  35157. b.subAssign( a );
  35158. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  35159. a.addAssign( c );
  35160. c.subAssign( b );
  35161. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  35162. b.addAssign( a );
  35163. a.subAssign( c );
  35164. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  35165. c.addAssign( b );
  35166. b.subAssign( a );
  35167. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  35168. a.addAssign( c );
  35169. c.subAssign( b );
  35170. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  35171. b.addAssign( a );
  35172. } );
  35173. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  35174. const c = uint( c_immutable ).toVar();
  35175. const b = uint( b_immutable ).toVar();
  35176. const a = uint( a_immutable ).toVar();
  35177. c.bitXorAssign( b );
  35178. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  35179. a.bitXorAssign( c );
  35180. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  35181. b.bitXorAssign( a );
  35182. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  35183. c.bitXorAssign( b );
  35184. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  35185. a.bitXorAssign( c );
  35186. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  35187. b.bitXorAssign( a );
  35188. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  35189. c.bitXorAssign( b );
  35190. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  35191. return c;
  35192. } ).setLayout( {
  35193. name: 'mx_bjfinal',
  35194. type: 'uint',
  35195. inputs: [
  35196. { name: 'a', type: 'uint' },
  35197. { name: 'b', type: 'uint' },
  35198. { name: 'c', type: 'uint' }
  35199. ]
  35200. } );
  35201. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  35202. const bits = uint( bits_immutable ).toVar();
  35203. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  35204. } ).setLayout( {
  35205. name: 'mx_bits_to_01',
  35206. type: 'float',
  35207. inputs: [
  35208. { name: 'bits', type: 'uint' }
  35209. ]
  35210. } );
  35211. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  35212. const t = float( t_immutable ).toVar();
  35213. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  35214. } ).setLayout( {
  35215. name: 'mx_fade',
  35216. type: 'float',
  35217. inputs: [
  35218. { name: 't', type: 'float' }
  35219. ]
  35220. } );
  35221. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  35222. const x = int( x_immutable ).toVar();
  35223. const len = uint( uint( 1 ) ).toVar();
  35224. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  35225. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  35226. } ).setLayout( {
  35227. name: 'mx_hash_int_0',
  35228. type: 'uint',
  35229. inputs: [
  35230. { name: 'x', type: 'int' }
  35231. ]
  35232. } );
  35233. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  35234. const y = int( y_immutable ).toVar();
  35235. const x = int( x_immutable ).toVar();
  35236. const len = uint( uint( 2 ) ).toVar();
  35237. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35238. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35239. a.addAssign( uint( x ) );
  35240. b.addAssign( uint( y ) );
  35241. return mx_bjfinal( a, b, c );
  35242. } ).setLayout( {
  35243. name: 'mx_hash_int_1',
  35244. type: 'uint',
  35245. inputs: [
  35246. { name: 'x', type: 'int' },
  35247. { name: 'y', type: 'int' }
  35248. ]
  35249. } );
  35250. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35251. const z = int( z_immutable ).toVar();
  35252. const y = int( y_immutable ).toVar();
  35253. const x = int( x_immutable ).toVar();
  35254. const len = uint( uint( 3 ) ).toVar();
  35255. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35256. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35257. a.addAssign( uint( x ) );
  35258. b.addAssign( uint( y ) );
  35259. c.addAssign( uint( z ) );
  35260. return mx_bjfinal( a, b, c );
  35261. } ).setLayout( {
  35262. name: 'mx_hash_int_2',
  35263. type: 'uint',
  35264. inputs: [
  35265. { name: 'x', type: 'int' },
  35266. { name: 'y', type: 'int' },
  35267. { name: 'z', type: 'int' }
  35268. ]
  35269. } );
  35270. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  35271. const xx = int( xx_immutable ).toVar();
  35272. const z = int( z_immutable ).toVar();
  35273. const y = int( y_immutable ).toVar();
  35274. const x = int( x_immutable ).toVar();
  35275. const len = uint( uint( 4 ) ).toVar();
  35276. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35277. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35278. a.addAssign( uint( x ) );
  35279. b.addAssign( uint( y ) );
  35280. c.addAssign( uint( z ) );
  35281. mx_bjmix( a, b, c );
  35282. a.addAssign( uint( xx ) );
  35283. return mx_bjfinal( a, b, c );
  35284. } ).setLayout( {
  35285. name: 'mx_hash_int_3',
  35286. type: 'uint',
  35287. inputs: [
  35288. { name: 'x', type: 'int' },
  35289. { name: 'y', type: 'int' },
  35290. { name: 'z', type: 'int' },
  35291. { name: 'xx', type: 'int' }
  35292. ]
  35293. } );
  35294. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  35295. const yy = int( yy_immutable ).toVar();
  35296. const xx = int( xx_immutable ).toVar();
  35297. const z = int( z_immutable ).toVar();
  35298. const y = int( y_immutable ).toVar();
  35299. const x = int( x_immutable ).toVar();
  35300. const len = uint( uint( 5 ) ).toVar();
  35301. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35302. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35303. a.addAssign( uint( x ) );
  35304. b.addAssign( uint( y ) );
  35305. c.addAssign( uint( z ) );
  35306. mx_bjmix( a, b, c );
  35307. a.addAssign( uint( xx ) );
  35308. b.addAssign( uint( yy ) );
  35309. return mx_bjfinal( a, b, c );
  35310. } ).setLayout( {
  35311. name: 'mx_hash_int_4',
  35312. type: 'uint',
  35313. inputs: [
  35314. { name: 'x', type: 'int' },
  35315. { name: 'y', type: 'int' },
  35316. { name: 'z', type: 'int' },
  35317. { name: 'xx', type: 'int' },
  35318. { name: 'yy', type: 'int' }
  35319. ]
  35320. } );
  35321. 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 ] );
  35322. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  35323. const y = int( y_immutable ).toVar();
  35324. const x = int( x_immutable ).toVar();
  35325. const h = uint( mx_hash_int( x, y ) ).toVar();
  35326. const result = uvec3().toVar();
  35327. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35328. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35329. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35330. return result;
  35331. } ).setLayout( {
  35332. name: 'mx_hash_vec3_0',
  35333. type: 'uvec3',
  35334. inputs: [
  35335. { name: 'x', type: 'int' },
  35336. { name: 'y', type: 'int' }
  35337. ]
  35338. } );
  35339. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35340. const z = int( z_immutable ).toVar();
  35341. const y = int( y_immutable ).toVar();
  35342. const x = int( x_immutable ).toVar();
  35343. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  35344. const result = uvec3().toVar();
  35345. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35346. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35347. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35348. return result;
  35349. } ).setLayout( {
  35350. name: 'mx_hash_vec3_1',
  35351. type: 'uvec3',
  35352. inputs: [
  35353. { name: 'x', type: 'int' },
  35354. { name: 'y', type: 'int' },
  35355. { name: 'z', type: 'int' }
  35356. ]
  35357. } );
  35358. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  35359. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35360. const p = vec2( p_immutable ).toVar();
  35361. const X = int().toVar(), Y = int().toVar();
  35362. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35363. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35364. const u = float( mx_fade( fx ) ).toVar();
  35365. const v = float( mx_fade( fy ) ).toVar();
  35366. 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();
  35367. return mx_gradient_scale2d( result );
  35368. } ).setLayout( {
  35369. name: 'mx_perlin_noise_float_0',
  35370. type: 'float',
  35371. inputs: [
  35372. { name: 'p', type: 'vec2' }
  35373. ]
  35374. } );
  35375. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35376. const p = vec3( p_immutable ).toVar();
  35377. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35378. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35379. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35380. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35381. const u = float( mx_fade( fx ) ).toVar();
  35382. const v = float( mx_fade( fy ) ).toVar();
  35383. const w = float( mx_fade( fz ) ).toVar();
  35384. 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();
  35385. return mx_gradient_scale3d( result );
  35386. } ).setLayout( {
  35387. name: 'mx_perlin_noise_float_1',
  35388. type: 'float',
  35389. inputs: [
  35390. { name: 'p', type: 'vec3' }
  35391. ]
  35392. } );
  35393. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  35394. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35395. const p = vec2( p_immutable ).toVar();
  35396. const X = int().toVar(), Y = int().toVar();
  35397. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35398. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35399. const u = float( mx_fade( fx ) ).toVar();
  35400. const v = float( mx_fade( fy ) ).toVar();
  35401. 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();
  35402. return mx_gradient_scale2d( result );
  35403. } ).setLayout( {
  35404. name: 'mx_perlin_noise_vec3_0',
  35405. type: 'vec3',
  35406. inputs: [
  35407. { name: 'p', type: 'vec2' }
  35408. ]
  35409. } );
  35410. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35411. const p = vec3( p_immutable ).toVar();
  35412. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35413. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35414. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35415. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35416. const u = float( mx_fade( fx ) ).toVar();
  35417. const v = float( mx_fade( fy ) ).toVar();
  35418. const w = float( mx_fade( fz ) ).toVar();
  35419. 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();
  35420. return mx_gradient_scale3d( result );
  35421. } ).setLayout( {
  35422. name: 'mx_perlin_noise_vec3_1',
  35423. type: 'vec3',
  35424. inputs: [
  35425. { name: 'p', type: 'vec3' }
  35426. ]
  35427. } );
  35428. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  35429. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35430. const p = float( p_immutable ).toVar();
  35431. const ix = int( mx_floor( p ) ).toVar();
  35432. return mx_bits_to_01( mx_hash_int( ix ) );
  35433. } ).setLayout( {
  35434. name: 'mx_cell_noise_float_0',
  35435. type: 'float',
  35436. inputs: [
  35437. { name: 'p', type: 'float' }
  35438. ]
  35439. } );
  35440. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35441. const p = vec2( p_immutable ).toVar();
  35442. const ix = int( mx_floor( p.x ) ).toVar();
  35443. const iy = int( mx_floor( p.y ) ).toVar();
  35444. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  35445. } ).setLayout( {
  35446. name: 'mx_cell_noise_float_1',
  35447. type: 'float',
  35448. inputs: [
  35449. { name: 'p', type: 'vec2' }
  35450. ]
  35451. } );
  35452. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35453. const p = vec3( p_immutable ).toVar();
  35454. const ix = int( mx_floor( p.x ) ).toVar();
  35455. const iy = int( mx_floor( p.y ) ).toVar();
  35456. const iz = int( mx_floor( p.z ) ).toVar();
  35457. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  35458. } ).setLayout( {
  35459. name: 'mx_cell_noise_float_2',
  35460. type: 'float',
  35461. inputs: [
  35462. { name: 'p', type: 'vec3' }
  35463. ]
  35464. } );
  35465. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35466. const p = vec4( p_immutable ).toVar();
  35467. const ix = int( mx_floor( p.x ) ).toVar();
  35468. const iy = int( mx_floor( p.y ) ).toVar();
  35469. const iz = int( mx_floor( p.z ) ).toVar();
  35470. const iw = int( mx_floor( p.w ) ).toVar();
  35471. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  35472. } ).setLayout( {
  35473. name: 'mx_cell_noise_float_3',
  35474. type: 'float',
  35475. inputs: [
  35476. { name: 'p', type: 'vec4' }
  35477. ]
  35478. } );
  35479. 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 ] );
  35480. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35481. const p = float( p_immutable ).toVar();
  35482. const ix = int( mx_floor( p ) ).toVar();
  35483. 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 ) ) ) );
  35484. } ).setLayout( {
  35485. name: 'mx_cell_noise_vec3_0',
  35486. type: 'vec3',
  35487. inputs: [
  35488. { name: 'p', type: 'float' }
  35489. ]
  35490. } );
  35491. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35492. const p = vec2( p_immutable ).toVar();
  35493. const ix = int( mx_floor( p.x ) ).toVar();
  35494. const iy = int( mx_floor( p.y ) ).toVar();
  35495. 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 ) ) ) );
  35496. } ).setLayout( {
  35497. name: 'mx_cell_noise_vec3_1',
  35498. type: 'vec3',
  35499. inputs: [
  35500. { name: 'p', type: 'vec2' }
  35501. ]
  35502. } );
  35503. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35504. const p = vec3( p_immutable ).toVar();
  35505. const ix = int( mx_floor( p.x ) ).toVar();
  35506. const iy = int( mx_floor( p.y ) ).toVar();
  35507. const iz = int( mx_floor( p.z ) ).toVar();
  35508. 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 ) ) ) );
  35509. } ).setLayout( {
  35510. name: 'mx_cell_noise_vec3_2',
  35511. type: 'vec3',
  35512. inputs: [
  35513. { name: 'p', type: 'vec3' }
  35514. ]
  35515. } );
  35516. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35517. const p = vec4( p_immutable ).toVar();
  35518. const ix = int( mx_floor( p.x ) ).toVar();
  35519. const iy = int( mx_floor( p.y ) ).toVar();
  35520. const iz = int( mx_floor( p.z ) ).toVar();
  35521. const iw = int( mx_floor( p.w ) ).toVar();
  35522. 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 ) ) ) );
  35523. } ).setLayout( {
  35524. name: 'mx_cell_noise_vec3_3',
  35525. type: 'vec3',
  35526. inputs: [
  35527. { name: 'p', type: 'vec4' }
  35528. ]
  35529. } );
  35530. 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 ] );
  35531. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35532. const diminish = float( diminish_immutable ).toVar();
  35533. const lacunarity = float( lacunarity_immutable ).toVar();
  35534. const octaves = int( octaves_immutable ).toVar();
  35535. const p = vec3( p_immutable ).toVar();
  35536. const result = float( 0.0 ).toVar();
  35537. const amplitude = float( 1.0 ).toVar();
  35538. loop( octaves, () => {
  35539. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  35540. amplitude.mulAssign( diminish );
  35541. p.mulAssign( lacunarity );
  35542. } );
  35543. return result;
  35544. } ).setLayout( {
  35545. name: 'mx_fractal_noise_float',
  35546. type: 'float',
  35547. inputs: [
  35548. { name: 'p', type: 'vec3' },
  35549. { name: 'octaves', type: 'int' },
  35550. { name: 'lacunarity', type: 'float' },
  35551. { name: 'diminish', type: 'float' }
  35552. ]
  35553. } );
  35554. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35555. const diminish = float( diminish_immutable ).toVar();
  35556. const lacunarity = float( lacunarity_immutable ).toVar();
  35557. const octaves = int( octaves_immutable ).toVar();
  35558. const p = vec3( p_immutable ).toVar();
  35559. const result = vec3( 0.0 ).toVar();
  35560. const amplitude = float( 1.0 ).toVar();
  35561. loop( octaves, () => {
  35562. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  35563. amplitude.mulAssign( diminish );
  35564. p.mulAssign( lacunarity );
  35565. } );
  35566. return result;
  35567. } ).setLayout( {
  35568. name: 'mx_fractal_noise_vec3',
  35569. type: 'vec3',
  35570. inputs: [
  35571. { name: 'p', type: 'vec3' },
  35572. { name: 'octaves', type: 'int' },
  35573. { name: 'lacunarity', type: 'float' },
  35574. { name: 'diminish', type: 'float' }
  35575. ]
  35576. } );
  35577. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35578. const diminish = float( diminish_immutable ).toVar();
  35579. const lacunarity = float( lacunarity_immutable ).toVar();
  35580. const octaves = int( octaves_immutable ).toVar();
  35581. const p = vec3( p_immutable ).toVar();
  35582. 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 ) );
  35583. } ).setLayout( {
  35584. name: 'mx_fractal_noise_vec2',
  35585. type: 'vec2',
  35586. inputs: [
  35587. { name: 'p', type: 'vec3' },
  35588. { name: 'octaves', type: 'int' },
  35589. { name: 'lacunarity', type: 'float' },
  35590. { name: 'diminish', type: 'float' }
  35591. ]
  35592. } );
  35593. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35594. const diminish = float( diminish_immutable ).toVar();
  35595. const lacunarity = float( lacunarity_immutable ).toVar();
  35596. const octaves = int( octaves_immutable ).toVar();
  35597. const p = vec3( p_immutable ).toVar();
  35598. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  35599. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  35600. return vec4( c, f );
  35601. } ).setLayout( {
  35602. name: 'mx_fractal_noise_vec4',
  35603. type: 'vec4',
  35604. inputs: [
  35605. { name: 'p', type: 'vec3' },
  35606. { name: 'octaves', type: 'int' },
  35607. { name: 'lacunarity', type: 'float' },
  35608. { name: 'diminish', type: 'float' }
  35609. ]
  35610. } );
  35611. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35612. const metric = int( metric_immutable ).toVar();
  35613. const jitter = float( jitter_immutable ).toVar();
  35614. const yoff = int( yoff_immutable ).toVar();
  35615. const xoff = int( xoff_immutable ).toVar();
  35616. const y = int( y_immutable ).toVar();
  35617. const x = int( x_immutable ).toVar();
  35618. const p = vec2( p_immutable ).toVar();
  35619. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  35620. const off = vec2( tmp.x, tmp.y ).toVar();
  35621. off.subAssign( 0.5 );
  35622. off.mulAssign( jitter );
  35623. off.addAssign( 0.5 );
  35624. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  35625. const diff = vec2( cellpos.sub( p ) ).toVar();
  35626. If( metric.equal( int( 2 ) ), () => {
  35627. return abs( diff.x ).add( abs( diff.y ) );
  35628. } );
  35629. If( metric.equal( int( 3 ) ), () => {
  35630. return max$1( abs( diff.x ), abs( diff.y ) );
  35631. } );
  35632. return dot( diff, diff );
  35633. } ).setLayout( {
  35634. name: 'mx_worley_distance_0',
  35635. type: 'float',
  35636. inputs: [
  35637. { name: 'p', type: 'vec2' },
  35638. { name: 'x', type: 'int' },
  35639. { name: 'y', type: 'int' },
  35640. { name: 'xoff', type: 'int' },
  35641. { name: 'yoff', type: 'int' },
  35642. { name: 'jitter', type: 'float' },
  35643. { name: 'metric', type: 'int' }
  35644. ]
  35645. } );
  35646. const mx_worley_distance_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35647. const metric = int( metric_immutable ).toVar();
  35648. const jitter = float( jitter_immutable ).toVar();
  35649. const zoff = int( zoff_immutable ).toVar();
  35650. const yoff = int( yoff_immutable ).toVar();
  35651. const xoff = int( xoff_immutable ).toVar();
  35652. const z = int( z_immutable ).toVar();
  35653. const y = int( y_immutable ).toVar();
  35654. const x = int( x_immutable ).toVar();
  35655. const p = vec3( p_immutable ).toVar();
  35656. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  35657. off.subAssign( 0.5 );
  35658. off.mulAssign( jitter );
  35659. off.addAssign( 0.5 );
  35660. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  35661. const diff = vec3( cellpos.sub( p ) ).toVar();
  35662. If( metric.equal( int( 2 ) ), () => {
  35663. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  35664. } );
  35665. If( metric.equal( int( 3 ) ), () => {
  35666. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  35667. } );
  35668. return dot( diff, diff );
  35669. } ).setLayout( {
  35670. name: 'mx_worley_distance_1',
  35671. type: 'float',
  35672. inputs: [
  35673. { name: 'p', type: 'vec3' },
  35674. { name: 'x', type: 'int' },
  35675. { name: 'y', type: 'int' },
  35676. { name: 'z', type: 'int' },
  35677. { name: 'xoff', type: 'int' },
  35678. { name: 'yoff', type: 'int' },
  35679. { name: 'zoff', type: 'int' },
  35680. { name: 'jitter', type: 'float' },
  35681. { name: 'metric', type: 'int' }
  35682. ]
  35683. } );
  35684. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  35685. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35686. const metric = int( metric_immutable ).toVar();
  35687. const jitter = float( jitter_immutable ).toVar();
  35688. const p = vec2( p_immutable ).toVar();
  35689. const X = int().toVar(), Y = int().toVar();
  35690. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35691. const sqdist = float( 1e6 ).toVar();
  35692. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35693. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35694. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35695. sqdist.assign( min$1( sqdist, dist ) );
  35696. } );
  35697. } );
  35698. If( metric.equal( int( 0 ) ), () => {
  35699. sqdist.assign( sqrt( sqdist ) );
  35700. } );
  35701. return sqdist;
  35702. } ).setLayout( {
  35703. name: 'mx_worley_noise_float_0',
  35704. type: 'float',
  35705. inputs: [
  35706. { name: 'p', type: 'vec2' },
  35707. { name: 'jitter', type: 'float' },
  35708. { name: 'metric', type: 'int' }
  35709. ]
  35710. } );
  35711. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35712. const metric = int( metric_immutable ).toVar();
  35713. const jitter = float( jitter_immutable ).toVar();
  35714. const p = vec2( p_immutable ).toVar();
  35715. const X = int().toVar(), Y = int().toVar();
  35716. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35717. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35718. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35719. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35720. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35721. If( dist.lessThan( sqdist.x ), () => {
  35722. sqdist.y.assign( sqdist.x );
  35723. sqdist.x.assign( dist );
  35724. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35725. sqdist.y.assign( dist );
  35726. } );
  35727. } );
  35728. } );
  35729. If( metric.equal( int( 0 ) ), () => {
  35730. sqdist.assign( sqrt( sqdist ) );
  35731. } );
  35732. return sqdist;
  35733. } ).setLayout( {
  35734. name: 'mx_worley_noise_vec2_0',
  35735. type: 'vec2',
  35736. inputs: [
  35737. { name: 'p', type: 'vec2' },
  35738. { name: 'jitter', type: 'float' },
  35739. { name: 'metric', type: 'int' }
  35740. ]
  35741. } );
  35742. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35743. const metric = int( metric_immutable ).toVar();
  35744. const jitter = float( jitter_immutable ).toVar();
  35745. const p = vec2( p_immutable ).toVar();
  35746. const X = int().toVar(), Y = int().toVar();
  35747. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35748. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35749. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35750. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35751. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35752. If( dist.lessThan( sqdist.x ), () => {
  35753. sqdist.z.assign( sqdist.y );
  35754. sqdist.y.assign( sqdist.x );
  35755. sqdist.x.assign( dist );
  35756. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35757. sqdist.z.assign( sqdist.y );
  35758. sqdist.y.assign( dist );
  35759. } ).elseif( dist.lessThan( sqdist.z ), () => {
  35760. sqdist.z.assign( dist );
  35761. } );
  35762. } );
  35763. } );
  35764. If( metric.equal( int( 0 ) ), () => {
  35765. sqdist.assign( sqrt( sqdist ) );
  35766. } );
  35767. return sqdist;
  35768. } ).setLayout( {
  35769. name: 'mx_worley_noise_vec3_0',
  35770. type: 'vec3',
  35771. inputs: [
  35772. { name: 'p', type: 'vec2' },
  35773. { name: 'jitter', type: 'float' },
  35774. { name: 'metric', type: 'int' }
  35775. ]
  35776. } );
  35777. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35778. const metric = int( metric_immutable ).toVar();
  35779. const jitter = float( jitter_immutable ).toVar();
  35780. const p = vec3( p_immutable ).toVar();
  35781. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35782. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35783. const sqdist = float( 1e6 ).toVar();
  35784. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35785. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35786. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35787. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35788. sqdist.assign( min$1( sqdist, dist ) );
  35789. } );
  35790. } );
  35791. } );
  35792. If( metric.equal( int( 0 ) ), () => {
  35793. sqdist.assign( sqrt( sqdist ) );
  35794. } );
  35795. return sqdist;
  35796. } ).setLayout( {
  35797. name: 'mx_worley_noise_float_1',
  35798. type: 'float',
  35799. inputs: [
  35800. { name: 'p', type: 'vec3' },
  35801. { name: 'jitter', type: 'float' },
  35802. { name: 'metric', type: 'int' }
  35803. ]
  35804. } );
  35805. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  35806. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35807. const metric = int( metric_immutable ).toVar();
  35808. const jitter = float( jitter_immutable ).toVar();
  35809. const p = vec3( p_immutable ).toVar();
  35810. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35811. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35812. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35813. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35814. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35815. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35816. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35817. If( dist.lessThan( sqdist.x ), () => {
  35818. sqdist.y.assign( sqdist.x );
  35819. sqdist.x.assign( dist );
  35820. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35821. sqdist.y.assign( dist );
  35822. } );
  35823. } );
  35824. } );
  35825. } );
  35826. If( metric.equal( int( 0 ) ), () => {
  35827. sqdist.assign( sqrt( sqdist ) );
  35828. } );
  35829. return sqdist;
  35830. } ).setLayout( {
  35831. name: 'mx_worley_noise_vec2_1',
  35832. type: 'vec2',
  35833. inputs: [
  35834. { name: 'p', type: 'vec3' },
  35835. { name: 'jitter', type: 'float' },
  35836. { name: 'metric', type: 'int' }
  35837. ]
  35838. } );
  35839. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  35840. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35841. const metric = int( metric_immutable ).toVar();
  35842. const jitter = float( jitter_immutable ).toVar();
  35843. const p = vec3( p_immutable ).toVar();
  35844. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35845. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35846. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35847. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35848. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35849. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35850. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35851. If( dist.lessThan( sqdist.x ), () => {
  35852. sqdist.z.assign( sqdist.y );
  35853. sqdist.y.assign( sqdist.x );
  35854. sqdist.x.assign( dist );
  35855. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35856. sqdist.z.assign( sqdist.y );
  35857. sqdist.y.assign( dist );
  35858. } ).elseif( dist.lessThan( sqdist.z ), () => {
  35859. sqdist.z.assign( dist );
  35860. } );
  35861. } );
  35862. } );
  35863. } );
  35864. If( metric.equal( int( 0 ) ), () => {
  35865. sqdist.assign( sqrt( sqdist ) );
  35866. } );
  35867. return sqdist;
  35868. } ).setLayout( {
  35869. name: 'mx_worley_noise_vec3_1',
  35870. type: 'vec3',
  35871. inputs: [
  35872. { name: 'p', type: 'vec3' },
  35873. { name: 'jitter', type: 'float' },
  35874. { name: 'metric', type: 'int' }
  35875. ]
  35876. } );
  35877. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  35878. // Three.js Transpiler
  35879. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  35880. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  35881. const hsv = vec3( hsv_immutable ).toVar();
  35882. const h = float( hsv.x ).toVar();
  35883. const s = float( hsv.y ).toVar();
  35884. const v = float( hsv.z ).toVar();
  35885. If( s.lessThan( 0.0001 ), () => {
  35886. return vec3( v, v, v );
  35887. } ).else( () => {
  35888. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  35889. const hi = int( trunc( h ) ).toVar();
  35890. const f = float( h.sub( float( hi ) ) ).toVar();
  35891. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  35892. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  35893. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  35894. If( hi.equal( int( 0 ) ), () => {
  35895. return vec3( v, t, p );
  35896. } ).elseif( hi.equal( int( 1 ) ), () => {
  35897. return vec3( q, v, p );
  35898. } ).elseif( hi.equal( int( 2 ) ), () => {
  35899. return vec3( p, v, t );
  35900. } ).elseif( hi.equal( int( 3 ) ), () => {
  35901. return vec3( p, q, v );
  35902. } ).elseif( hi.equal( int( 4 ) ), () => {
  35903. return vec3( t, p, v );
  35904. } );
  35905. return vec3( v, p, q );
  35906. } );
  35907. } ).setLayout( {
  35908. name: 'mx_hsvtorgb',
  35909. type: 'vec3',
  35910. inputs: [
  35911. { name: 'hsv', type: 'vec3' }
  35912. ]
  35913. } );
  35914. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  35915. const c = vec3( c_immutable ).toVar();
  35916. const r = float( c.x ).toVar();
  35917. const g = float( c.y ).toVar();
  35918. const b = float( c.z ).toVar();
  35919. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  35920. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  35921. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  35922. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  35923. v.assign( maxcomp );
  35924. If( maxcomp.greaterThan( 0.0 ), () => {
  35925. s.assign( delta.div( maxcomp ) );
  35926. } ).else( () => {
  35927. s.assign( 0.0 );
  35928. } );
  35929. If( s.lessThanEqual( 0.0 ), () => {
  35930. h.assign( 0.0 );
  35931. } ).else( () => {
  35932. If( r.greaterThanEqual( maxcomp ), () => {
  35933. h.assign( g.sub( b ).div( delta ) );
  35934. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  35935. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  35936. } ).else( () => {
  35937. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  35938. } );
  35939. h.mulAssign( 1.0 / 6.0 );
  35940. If( h.lessThan( 0.0 ), () => {
  35941. h.addAssign( 1.0 );
  35942. } );
  35943. } );
  35944. return vec3( h, s, v );
  35945. } ).setLayout( {
  35946. name: 'mx_rgbtohsv',
  35947. type: 'vec3',
  35948. inputs: [
  35949. { name: 'c', type: 'vec3' }
  35950. ]
  35951. } );
  35952. // Three.js Transpiler
  35953. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  35954. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  35955. const color = vec3( color_immutable ).toVar();
  35956. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  35957. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  35958. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  35959. return mix( linSeg, powSeg, isAbove );
  35960. } ).setLayout( {
  35961. name: 'mx_srgb_texture_to_lin_rec709',
  35962. type: 'vec3',
  35963. inputs: [
  35964. { name: 'color', type: 'vec3' }
  35965. ]
  35966. } );
  35967. const mx_aastep = ( threshold, value ) => {
  35968. threshold = float( threshold );
  35969. value = float( value );
  35970. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  35971. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  35972. };
  35973. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  35974. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  35975. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  35976. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  35977. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  35978. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  35979. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  35980. const mx_safepower = ( in1, in2 = 1 ) => {
  35981. in1 = float( in1 );
  35982. return in1.abs().pow( in2 ).mul( in1.sign() );
  35983. };
  35984. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  35985. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35986. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35987. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35988. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  35989. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  35990. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  35991. return noise_vec4.mul( amplitude ).add( pivot );
  35992. };
  35993. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35994. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35995. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35996. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  35997. 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 );
  35998. 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 );
  35999. 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 );
  36000. 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 );
  36001. function painterSortStable( a, b ) {
  36002. if ( a.groupOrder !== b.groupOrder ) {
  36003. return a.groupOrder - b.groupOrder;
  36004. } else if ( a.renderOrder !== b.renderOrder ) {
  36005. return a.renderOrder - b.renderOrder;
  36006. } else if ( a.material.id !== b.material.id ) {
  36007. return a.material.id - b.material.id;
  36008. } else if ( a.z !== b.z ) {
  36009. return a.z - b.z;
  36010. } else {
  36011. return a.id - b.id;
  36012. }
  36013. }
  36014. function reversePainterSortStable( a, b ) {
  36015. if ( a.groupOrder !== b.groupOrder ) {
  36016. return a.groupOrder - b.groupOrder;
  36017. } else if ( a.renderOrder !== b.renderOrder ) {
  36018. return a.renderOrder - b.renderOrder;
  36019. } else if ( a.z !== b.z ) {
  36020. return b.z - a.z;
  36021. } else {
  36022. return a.id - b.id;
  36023. }
  36024. }
  36025. class RenderList {
  36026. constructor() {
  36027. this.renderItems = [];
  36028. this.renderItemsIndex = 0;
  36029. this.opaque = [];
  36030. this.transparent = [];
  36031. this.bundles = [];
  36032. this.lightsNode = new LightsNode( [] );
  36033. this.lightsArray = [];
  36034. this.occlusionQueryCount = 0;
  36035. }
  36036. begin() {
  36037. this.renderItemsIndex = 0;
  36038. this.opaque.length = 0;
  36039. this.transparent.length = 0;
  36040. this.bundles.length = 0;
  36041. this.lightsArray.length = 0;
  36042. this.occlusionQueryCount = 0;
  36043. return this;
  36044. }
  36045. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  36046. let renderItem = this.renderItems[ this.renderItemsIndex ];
  36047. if ( renderItem === undefined ) {
  36048. renderItem = {
  36049. id: object.id,
  36050. object: object,
  36051. geometry: geometry,
  36052. material: material,
  36053. groupOrder: groupOrder,
  36054. renderOrder: object.renderOrder,
  36055. z: z,
  36056. group: group
  36057. };
  36058. this.renderItems[ this.renderItemsIndex ] = renderItem;
  36059. } else {
  36060. renderItem.id = object.id;
  36061. renderItem.object = object;
  36062. renderItem.geometry = geometry;
  36063. renderItem.material = material;
  36064. renderItem.groupOrder = groupOrder;
  36065. renderItem.renderOrder = object.renderOrder;
  36066. renderItem.z = z;
  36067. renderItem.group = group;
  36068. }
  36069. this.renderItemsIndex ++;
  36070. return renderItem;
  36071. }
  36072. push( object, geometry, material, groupOrder, z, group ) {
  36073. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36074. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  36075. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  36076. }
  36077. unshift( object, geometry, material, groupOrder, z, group ) {
  36078. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36079. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  36080. }
  36081. pushBundle( group ) {
  36082. this.bundles.push( group );
  36083. }
  36084. pushLight( light ) {
  36085. this.lightsArray.push( light );
  36086. }
  36087. getLightsNode() {
  36088. return this.lightsNode.fromLights( this.lightsArray );
  36089. }
  36090. sort( customOpaqueSort, customTransparentSort ) {
  36091. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  36092. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  36093. }
  36094. finish() {
  36095. // update lights
  36096. this.lightsNode.fromLights( this.lightsArray );
  36097. // Clear references from inactive renderItems in the list
  36098. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  36099. const renderItem = this.renderItems[ i ];
  36100. if ( renderItem.id === null ) break;
  36101. renderItem.id = null;
  36102. renderItem.object = null;
  36103. renderItem.geometry = null;
  36104. renderItem.material = null;
  36105. renderItem.groupOrder = null;
  36106. renderItem.renderOrder = null;
  36107. renderItem.z = null;
  36108. renderItem.group = null;
  36109. }
  36110. }
  36111. }
  36112. class RenderLists {
  36113. constructor() {
  36114. this.lists = new ChainMap();
  36115. }
  36116. get( scene, camera ) {
  36117. const lists = this.lists;
  36118. const keys = [ scene, camera ];
  36119. let list = lists.get( keys );
  36120. if ( list === undefined ) {
  36121. list = new RenderList();
  36122. lists.set( keys, list );
  36123. }
  36124. return list;
  36125. }
  36126. dispose() {
  36127. this.lists = new ChainMap();
  36128. }
  36129. }
  36130. let id = 0;
  36131. class RenderContext {
  36132. constructor() {
  36133. this.id = id ++;
  36134. this.color = true;
  36135. this.clearColor = true;
  36136. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  36137. this.depth = true;
  36138. this.clearDepth = true;
  36139. this.clearDepthValue = 1;
  36140. this.stencil = false;
  36141. this.clearStencil = true;
  36142. this.clearStencilValue = 1;
  36143. this.viewport = false;
  36144. this.viewportValue = new Vector4();
  36145. this.scissor = false;
  36146. this.scissorValue = new Vector4();
  36147. this.textures = null;
  36148. this.depthTexture = null;
  36149. this.activeCubeFace = 0;
  36150. this.sampleCount = 1;
  36151. this.width = 0;
  36152. this.height = 0;
  36153. this.isRenderContext = true;
  36154. }
  36155. }
  36156. class RenderContexts {
  36157. constructor() {
  36158. this.chainMaps = {};
  36159. }
  36160. get( scene, camera, renderTarget = null ) {
  36161. const chainKey = [ scene, camera ];
  36162. let attachmentState;
  36163. if ( renderTarget === null ) {
  36164. attachmentState = 'default';
  36165. } else {
  36166. const format = renderTarget.texture.format;
  36167. const count = renderTarget.textures.length;
  36168. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  36169. }
  36170. const chainMap = this.getChainMap( attachmentState );
  36171. let renderState = chainMap.get( chainKey );
  36172. if ( renderState === undefined ) {
  36173. renderState = new RenderContext();
  36174. chainMap.set( chainKey, renderState );
  36175. }
  36176. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36177. return renderState;
  36178. }
  36179. getChainMap( attachmentState ) {
  36180. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  36181. }
  36182. dispose() {
  36183. this.chainMaps = {};
  36184. }
  36185. }
  36186. const _size = /*@__PURE__*/ new Vector3();
  36187. class Textures extends DataMap {
  36188. constructor( renderer, backend, info ) {
  36189. super();
  36190. this.renderer = renderer;
  36191. this.backend = backend;
  36192. this.info = info;
  36193. }
  36194. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  36195. const renderTargetData = this.get( renderTarget );
  36196. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36197. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  36198. const texture = renderTarget.texture;
  36199. const textures = renderTarget.textures;
  36200. const size = this.getSize( texture );
  36201. const mipWidth = size.width >> activeMipmapLevel;
  36202. const mipHeight = size.height >> activeMipmapLevel;
  36203. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  36204. let textureNeedsUpdate = false;
  36205. if ( depthTexture === undefined ) {
  36206. depthTexture = new DepthTexture();
  36207. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  36208. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  36209. depthTexture.image.width = mipWidth;
  36210. depthTexture.image.height = mipHeight;
  36211. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  36212. }
  36213. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  36214. textureNeedsUpdate = true;
  36215. depthTexture.needsUpdate = true;
  36216. depthTexture.image.width = mipWidth;
  36217. depthTexture.image.height = mipHeight;
  36218. }
  36219. renderTargetData.width = size.width;
  36220. renderTargetData.height = size.height;
  36221. renderTargetData.textures = textures;
  36222. renderTargetData.depthTexture = depthTexture;
  36223. renderTargetData.depth = renderTarget.depthBuffer;
  36224. renderTargetData.stencil = renderTarget.stencilBuffer;
  36225. renderTargetData.renderTarget = renderTarget;
  36226. if ( renderTargetData.sampleCount !== sampleCount ) {
  36227. textureNeedsUpdate = true;
  36228. depthTexture.needsUpdate = true;
  36229. renderTargetData.sampleCount = sampleCount;
  36230. }
  36231. //
  36232. const options = { sampleCount };
  36233. for ( let i = 0; i < textures.length; i ++ ) {
  36234. const texture = textures[ i ];
  36235. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  36236. this.updateTexture( texture, options );
  36237. }
  36238. this.updateTexture( depthTexture, options );
  36239. // dispose handler
  36240. if ( renderTargetData.initialized !== true ) {
  36241. renderTargetData.initialized = true;
  36242. // dispose
  36243. const onDispose = () => {
  36244. renderTarget.removeEventListener( 'dispose', onDispose );
  36245. if ( textures !== undefined ) {
  36246. for ( let i = 0; i < textures.length; i ++ ) {
  36247. this._destroyTexture( textures[ i ] );
  36248. }
  36249. } else {
  36250. this._destroyTexture( texture );
  36251. }
  36252. this._destroyTexture( depthTexture );
  36253. this.delete( renderTarget );
  36254. };
  36255. renderTarget.addEventListener( 'dispose', onDispose );
  36256. }
  36257. }
  36258. updateTexture( texture, options = {} ) {
  36259. const textureData = this.get( texture );
  36260. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  36261. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  36262. const backend = this.backend;
  36263. if ( isRenderTarget && textureData.initialized === true ) {
  36264. // it's an update
  36265. backend.destroySampler( texture );
  36266. backend.destroyTexture( texture );
  36267. }
  36268. //
  36269. if ( texture.isFramebufferTexture ) {
  36270. const renderer = this.renderer;
  36271. const renderTarget = renderer.getRenderTarget();
  36272. if ( renderTarget ) {
  36273. texture.type = renderTarget.texture.type;
  36274. } else {
  36275. texture.type = UnsignedByteType;
  36276. }
  36277. }
  36278. //
  36279. const { width, height, depth } = this.getSize( texture );
  36280. options.width = width;
  36281. options.height = height;
  36282. options.depth = depth;
  36283. options.needsMipmaps = this.needsMipmaps( texture );
  36284. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  36285. //
  36286. if ( isRenderTarget || texture.isStorageTexture === true ) {
  36287. backend.createSampler( texture );
  36288. backend.createTexture( texture, options );
  36289. } else {
  36290. const needsCreate = textureData.initialized !== true;
  36291. if ( needsCreate ) backend.createSampler( texture );
  36292. if ( texture.version > 0 ) {
  36293. const image = texture.image;
  36294. if ( image === undefined ) {
  36295. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  36296. } else if ( image.complete === false ) {
  36297. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  36298. } else {
  36299. if ( texture.images ) {
  36300. const images = [];
  36301. for ( const image of texture.images ) {
  36302. images.push( image );
  36303. }
  36304. options.images = images;
  36305. } else {
  36306. options.image = image;
  36307. }
  36308. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  36309. backend.createTexture( texture, options );
  36310. textureData.isDefaultTexture = false;
  36311. }
  36312. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  36313. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  36314. }
  36315. } else {
  36316. // async update
  36317. backend.createDefaultTexture( texture );
  36318. textureData.isDefaultTexture = true;
  36319. }
  36320. }
  36321. // dispose handler
  36322. if ( textureData.initialized !== true ) {
  36323. textureData.initialized = true;
  36324. //
  36325. this.info.memory.textures ++;
  36326. // dispose
  36327. const onDispose = () => {
  36328. texture.removeEventListener( 'dispose', onDispose );
  36329. this._destroyTexture( texture );
  36330. this.info.memory.textures --;
  36331. };
  36332. texture.addEventListener( 'dispose', onDispose );
  36333. }
  36334. //
  36335. textureData.version = texture.version;
  36336. }
  36337. getSize( texture, target = _size ) {
  36338. let image = texture.images ? texture.images[ 0 ] : texture.image;
  36339. if ( image ) {
  36340. if ( image.image !== undefined ) image = image.image;
  36341. target.width = image.width;
  36342. target.height = image.height;
  36343. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  36344. } else {
  36345. target.width = target.height = target.depth = 1;
  36346. }
  36347. return target;
  36348. }
  36349. getMipLevels( texture, width, height ) {
  36350. let mipLevelCount;
  36351. if ( texture.isCompressedTexture ) {
  36352. mipLevelCount = texture.mipmaps.length;
  36353. } else {
  36354. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  36355. }
  36356. return mipLevelCount;
  36357. }
  36358. needsMipmaps( texture ) {
  36359. if ( this.isEnvironmentTexture( texture ) ) return true;
  36360. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  36361. }
  36362. isEnvironmentTexture( texture ) {
  36363. const mapping = texture.mapping;
  36364. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  36365. }
  36366. _destroyTexture( texture ) {
  36367. this.backend.destroySampler( texture );
  36368. this.backend.destroyTexture( texture );
  36369. this.delete( texture );
  36370. }
  36371. }
  36372. class Color4 extends Color {
  36373. constructor( r, g, b, a = 1 ) {
  36374. super( r, g, b );
  36375. this.a = a;
  36376. }
  36377. set( r, g, b, a = 1 ) {
  36378. this.a = a;
  36379. return super.set( r, g, b );
  36380. }
  36381. copy( color ) {
  36382. if ( color.a !== undefined ) this.a = color.a;
  36383. return super.copy( color );
  36384. }
  36385. clone() {
  36386. return new this.constructor( this.r, this.g, this.b, this.a );
  36387. }
  36388. }
  36389. const _clearColor = /*@__PURE__*/ new Color4();
  36390. class Background extends DataMap {
  36391. constructor( renderer, nodes ) {
  36392. super();
  36393. this.renderer = renderer;
  36394. this.nodes = nodes;
  36395. }
  36396. update( scene, renderList, renderContext ) {
  36397. const renderer = this.renderer;
  36398. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  36399. let forceClear = false;
  36400. if ( background === null ) {
  36401. // no background settings, use clear color configuration from the renderer
  36402. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  36403. _clearColor.a = renderer._clearColor.a;
  36404. } else if ( background.isColor === true ) {
  36405. // background is an opaque color
  36406. background.getRGB( _clearColor, LinearSRGBColorSpace );
  36407. _clearColor.a = 1;
  36408. forceClear = true;
  36409. } else if ( background.isNode === true ) {
  36410. const sceneData = this.get( scene );
  36411. const backgroundNode = background;
  36412. _clearColor.copy( renderer._clearColor );
  36413. let backgroundMesh = sceneData.backgroundMesh;
  36414. if ( backgroundMesh === undefined ) {
  36415. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  36416. // @TODO: Add Texture2D support using node context
  36417. getUV: () => normalWorld,
  36418. getTextureLevel: () => backgroundBlurriness
  36419. } );
  36420. let viewProj = modelViewProjection();
  36421. viewProj = viewProj.setZ( viewProj.w );
  36422. const nodeMaterial = new NodeMaterial();
  36423. nodeMaterial.name = 'Background.material';
  36424. nodeMaterial.side = BackSide;
  36425. nodeMaterial.depthTest = false;
  36426. nodeMaterial.depthWrite = false;
  36427. nodeMaterial.fog = false;
  36428. nodeMaterial.lights = false;
  36429. nodeMaterial.vertexNode = viewProj;
  36430. nodeMaterial.colorNode = backgroundMeshNode;
  36431. sceneData.backgroundMeshNode = backgroundMeshNode;
  36432. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  36433. backgroundMesh.frustumCulled = false;
  36434. backgroundMesh.name = 'Background.mesh';
  36435. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  36436. this.matrixWorld.copyPosition( camera.matrixWorld );
  36437. };
  36438. }
  36439. const backgroundCacheKey = backgroundNode.getCacheKey();
  36440. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  36441. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  36442. backgroundMesh.material.needsUpdate = true;
  36443. sceneData.backgroundCacheKey = backgroundCacheKey;
  36444. }
  36445. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  36446. } else {
  36447. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  36448. }
  36449. //
  36450. if ( renderer.autoClear === true || forceClear === true ) {
  36451. _clearColor.multiplyScalar( _clearColor.a );
  36452. const clearColorValue = renderContext.clearColorValue;
  36453. clearColorValue.r = _clearColor.r;
  36454. clearColorValue.g = _clearColor.g;
  36455. clearColorValue.b = _clearColor.b;
  36456. clearColorValue.a = _clearColor.a;
  36457. renderContext.depthClearValue = renderer._clearDepth;
  36458. renderContext.stencilClearValue = renderer._clearStencil;
  36459. renderContext.clearColor = renderer.autoClearColor === true;
  36460. renderContext.clearDepth = renderer.autoClearDepth === true;
  36461. renderContext.clearStencil = renderer.autoClearStencil === true;
  36462. } else {
  36463. renderContext.clearColor = false;
  36464. renderContext.clearDepth = false;
  36465. renderContext.clearStencil = false;
  36466. }
  36467. }
  36468. }
  36469. class NodeBuilderState {
  36470. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  36471. this.vertexShader = vertexShader;
  36472. this.fragmentShader = fragmentShader;
  36473. this.computeShader = computeShader;
  36474. this.transforms = transforms;
  36475. this.nodeAttributes = nodeAttributes;
  36476. this.bindings = bindings;
  36477. this.updateNodes = updateNodes;
  36478. this.updateBeforeNodes = updateBeforeNodes;
  36479. this.updateAfterNodes = updateAfterNodes;
  36480. this.instanceBindGroups = instanceBindGroups;
  36481. this.usedTimes = 0;
  36482. }
  36483. createBindings() {
  36484. const bindings = [];
  36485. for ( const instanceGroup of this.bindings ) {
  36486. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  36487. if ( shared !== true ) {
  36488. const bindingsGroup = new BindGroup( instanceGroup.name );
  36489. bindings.push( bindingsGroup );
  36490. for ( const instanceBinding of instanceGroup.bindings ) {
  36491. bindingsGroup.bindings.push( instanceBinding.clone() );
  36492. }
  36493. } else {
  36494. bindings.push( instanceGroup );
  36495. }
  36496. }
  36497. return bindings;
  36498. }
  36499. }
  36500. const outputNodeMap = new WeakMap();
  36501. class Nodes extends DataMap {
  36502. constructor( renderer, backend ) {
  36503. super();
  36504. this.renderer = renderer;
  36505. this.backend = backend;
  36506. this.nodeFrame = new NodeFrame();
  36507. this.nodeBuilderCache = new Map();
  36508. this.callHashCache = new ChainMap();
  36509. this.groupsData = new ChainMap();
  36510. }
  36511. updateGroup( nodeUniformsGroup ) {
  36512. const groupNode = nodeUniformsGroup.groupNode;
  36513. const name = groupNode.name;
  36514. // objectGroup is every updated
  36515. if ( name === objectGroup.name ) return true;
  36516. // renderGroup is updated once per render/compute call
  36517. if ( name === renderGroup.name ) {
  36518. const uniformsGroupData = this.get( nodeUniformsGroup );
  36519. const renderId = this.nodeFrame.renderId;
  36520. if ( uniformsGroupData.renderId !== renderId ) {
  36521. uniformsGroupData.renderId = renderId;
  36522. return true;
  36523. }
  36524. return false;
  36525. }
  36526. // frameGroup is updated once per frame
  36527. if ( name === frameGroup.name ) {
  36528. const uniformsGroupData = this.get( nodeUniformsGroup );
  36529. const frameId = this.nodeFrame.frameId;
  36530. if ( uniformsGroupData.frameId !== frameId ) {
  36531. uniformsGroupData.frameId = frameId;
  36532. return true;
  36533. }
  36534. return false;
  36535. }
  36536. // other groups are updated just when groupNode.needsUpdate is true
  36537. const groupChain = [ groupNode, nodeUniformsGroup ];
  36538. let groupData = this.groupsData.get( groupChain );
  36539. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  36540. if ( groupData.version !== groupNode.version ) {
  36541. groupData.version = groupNode.version;
  36542. return true;
  36543. }
  36544. return false;
  36545. }
  36546. getForRenderCacheKey( renderObject ) {
  36547. return renderObject.initialCacheKey;
  36548. }
  36549. getForRender( renderObject ) {
  36550. const renderObjectData = this.get( renderObject );
  36551. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36552. if ( nodeBuilderState === undefined ) {
  36553. const { nodeBuilderCache } = this;
  36554. const cacheKey = this.getForRenderCacheKey( renderObject );
  36555. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36556. if ( nodeBuilderState === undefined ) {
  36557. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36558. nodeBuilder.scene = renderObject.scene;
  36559. nodeBuilder.material = renderObject.material;
  36560. nodeBuilder.camera = renderObject.camera;
  36561. nodeBuilder.context.material = renderObject.material;
  36562. nodeBuilder.lightsNode = renderObject.lightsNode;
  36563. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36564. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36565. nodeBuilder.clippingContext = renderObject.clippingContext;
  36566. nodeBuilder.build();
  36567. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36568. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36569. }
  36570. nodeBuilderState.usedTimes ++;
  36571. renderObjectData.nodeBuilderState = nodeBuilderState;
  36572. }
  36573. return nodeBuilderState;
  36574. }
  36575. delete( object ) {
  36576. if ( object.isRenderObject ) {
  36577. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36578. nodeBuilderState.usedTimes --;
  36579. if ( nodeBuilderState.usedTimes === 0 ) {
  36580. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36581. }
  36582. }
  36583. return super.delete( object );
  36584. }
  36585. getForCompute( computeNode ) {
  36586. const computeData = this.get( computeNode );
  36587. let nodeBuilderState = computeData.nodeBuilderState;
  36588. if ( nodeBuilderState === undefined ) {
  36589. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36590. nodeBuilder.build();
  36591. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36592. computeData.nodeBuilderState = nodeBuilderState;
  36593. }
  36594. return nodeBuilderState;
  36595. }
  36596. _createNodeBuilderState( nodeBuilder ) {
  36597. return new NodeBuilderState(
  36598. nodeBuilder.vertexShader,
  36599. nodeBuilder.fragmentShader,
  36600. nodeBuilder.computeShader,
  36601. nodeBuilder.getAttributesArray(),
  36602. nodeBuilder.getBindings(),
  36603. nodeBuilder.updateNodes,
  36604. nodeBuilder.updateBeforeNodes,
  36605. nodeBuilder.updateAfterNodes,
  36606. nodeBuilder.instanceBindGroups,
  36607. nodeBuilder.transforms
  36608. );
  36609. }
  36610. getEnvironmentNode( scene ) {
  36611. return scene.environmentNode || this.get( scene ).environmentNode || null;
  36612. }
  36613. getBackgroundNode( scene ) {
  36614. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  36615. }
  36616. getFogNode( scene ) {
  36617. return scene.fogNode || this.get( scene ).fogNode || null;
  36618. }
  36619. getCacheKey( scene, lightsNode ) {
  36620. const chain = [ scene, lightsNode ];
  36621. const callId = this.renderer.info.calls;
  36622. let cacheKeyData = this.callHashCache.get( chain );
  36623. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  36624. const environmentNode = this.getEnvironmentNode( scene );
  36625. const fogNode = this.getFogNode( scene );
  36626. const cacheKey = [];
  36627. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey() );
  36628. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  36629. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  36630. cacheKeyData = {
  36631. callId,
  36632. cacheKey: cacheKey.join( ',' )
  36633. };
  36634. this.callHashCache.set( chain, cacheKeyData );
  36635. }
  36636. return cacheKeyData.cacheKey;
  36637. }
  36638. updateScene( scene ) {
  36639. this.updateEnvironment( scene );
  36640. this.updateFog( scene );
  36641. this.updateBackground( scene );
  36642. }
  36643. get isToneMappingState() {
  36644. return this.renderer.getRenderTarget() ? false : true;
  36645. }
  36646. updateBackground( scene ) {
  36647. const sceneData = this.get( scene );
  36648. const background = scene.background;
  36649. if ( background ) {
  36650. if ( sceneData.background !== background ) {
  36651. let backgroundNode = null;
  36652. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  36653. backgroundNode = pmremTexture( background, normalWorld );
  36654. } else if ( background.isTexture === true ) {
  36655. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  36656. } else if ( background.isColor !== true ) {
  36657. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  36658. }
  36659. sceneData.backgroundNode = backgroundNode;
  36660. sceneData.background = background;
  36661. }
  36662. } else if ( sceneData.backgroundNode ) {
  36663. delete sceneData.backgroundNode;
  36664. delete sceneData.background;
  36665. }
  36666. }
  36667. updateFog( scene ) {
  36668. const sceneData = this.get( scene );
  36669. const fog = scene.fog;
  36670. if ( fog ) {
  36671. if ( sceneData.fog !== fog ) {
  36672. let fogNode = null;
  36673. if ( fog.isFogExp2 ) {
  36674. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  36675. } else if ( fog.isFog ) {
  36676. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  36677. } else {
  36678. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  36679. }
  36680. sceneData.fogNode = fogNode;
  36681. sceneData.fog = fog;
  36682. }
  36683. } else {
  36684. delete sceneData.fogNode;
  36685. delete sceneData.fog;
  36686. }
  36687. }
  36688. updateEnvironment( scene ) {
  36689. const sceneData = this.get( scene );
  36690. const environment = scene.environment;
  36691. if ( environment ) {
  36692. if ( sceneData.environment !== environment ) {
  36693. let environmentNode = null;
  36694. if ( environment.isCubeTexture === true ) {
  36695. environmentNode = cubeTexture( environment );
  36696. } else if ( environment.isTexture === true ) {
  36697. environmentNode = texture( environment );
  36698. } else {
  36699. console.error( 'Nodes: Unsupported environment configuration.', environment );
  36700. }
  36701. sceneData.environmentNode = environmentNode;
  36702. sceneData.environment = environment;
  36703. }
  36704. } else if ( sceneData.environmentNode ) {
  36705. delete sceneData.environmentNode;
  36706. delete sceneData.environment;
  36707. }
  36708. }
  36709. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  36710. const nodeFrame = this.nodeFrame;
  36711. nodeFrame.renderer = renderer;
  36712. nodeFrame.scene = scene;
  36713. nodeFrame.object = object;
  36714. nodeFrame.camera = camera;
  36715. nodeFrame.material = material;
  36716. return nodeFrame;
  36717. }
  36718. getNodeFrameForRender( renderObject ) {
  36719. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  36720. }
  36721. getOutputCacheKey() {
  36722. const renderer = this.renderer;
  36723. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  36724. }
  36725. hasOutputChange( outputTarget ) {
  36726. const cacheKey = outputNodeMap.get( outputTarget );
  36727. return cacheKey !== this.getOutputCacheKey();
  36728. }
  36729. getOutputNode( outputTexture ) {
  36730. const renderer = this.renderer;
  36731. const cacheKey = this.getOutputCacheKey();
  36732. const output = texture( outputTexture, viewportTopLeft ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  36733. outputNodeMap.set( outputTexture, cacheKey );
  36734. return output;
  36735. }
  36736. updateBefore( renderObject ) {
  36737. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36738. const nodeBuilder = renderObject.getNodeBuilderState();
  36739. for ( const node of nodeBuilder.updateBeforeNodes ) {
  36740. nodeFrame.updateBeforeNode( node );
  36741. }
  36742. }
  36743. updateAfter( renderObject ) {
  36744. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36745. const nodeBuilder = renderObject.getNodeBuilderState();
  36746. for ( const node of nodeBuilder.updateAfterNodes ) {
  36747. nodeFrame.updateAfterNode( node );
  36748. }
  36749. }
  36750. updateForCompute( computeNode ) {
  36751. const nodeFrame = this.getNodeFrame();
  36752. const nodeBuilder = this.getForCompute( computeNode );
  36753. for ( const node of nodeBuilder.updateNodes ) {
  36754. nodeFrame.updateNode( node );
  36755. }
  36756. }
  36757. updateForRender( renderObject ) {
  36758. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36759. const nodeBuilder = renderObject.getNodeBuilderState();
  36760. for ( const node of nodeBuilder.updateNodes ) {
  36761. nodeFrame.updateNode( node );
  36762. }
  36763. }
  36764. dispose() {
  36765. super.dispose();
  36766. this.nodeFrame = new NodeFrame();
  36767. this.nodeBuilderCache = new Map();
  36768. }
  36769. }
  36770. class RenderBundle {
  36771. constructor( scene, camera ) {
  36772. this.scene = scene;
  36773. this.camera = camera;
  36774. }
  36775. clone() {
  36776. return Object.assign( new this.constructor(), this );
  36777. }
  36778. }
  36779. class RenderBundles {
  36780. constructor() {
  36781. this.lists = new ChainMap();
  36782. }
  36783. get( scene, camera ) {
  36784. const lists = this.lists;
  36785. const keys = [ scene, camera ];
  36786. let list = lists.get( keys );
  36787. if ( list === undefined ) {
  36788. list = new RenderBundle( scene, camera );
  36789. lists.set( keys, list );
  36790. }
  36791. return list;
  36792. }
  36793. dispose() {
  36794. this.lists = new ChainMap();
  36795. }
  36796. }
  36797. const _scene = /*@__PURE__*/ new Scene();
  36798. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  36799. const _screen = /*@__PURE__*/ new Vector4();
  36800. const _frustum = /*@__PURE__*/ new Frustum();
  36801. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36802. const _vector3 = /*@__PURE__*/ new Vector3();
  36803. class Renderer {
  36804. constructor( backend, parameters = {} ) {
  36805. this.isRenderer = true;
  36806. //
  36807. const {
  36808. logarithmicDepthBuffer = false,
  36809. alpha = true,
  36810. antialias = false,
  36811. samples = 0
  36812. } = parameters;
  36813. // public
  36814. this.domElement = backend.getDomElement();
  36815. this.backend = backend;
  36816. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36817. this.autoClear = true;
  36818. this.autoClearColor = true;
  36819. this.autoClearDepth = true;
  36820. this.autoClearStencil = true;
  36821. this.alpha = alpha;
  36822. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36823. this.outputColorSpace = SRGBColorSpace;
  36824. this.toneMapping = NoToneMapping;
  36825. this.toneMappingExposure = 1.0;
  36826. this.sortObjects = true;
  36827. this.depth = true;
  36828. this.stencil = false;
  36829. this.clippingPlanes = [];
  36830. this.info = new Info();
  36831. // internals
  36832. this._pixelRatio = 1;
  36833. this._width = this.domElement.width;
  36834. this._height = this.domElement.height;
  36835. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36836. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36837. this._scissorTest = false;
  36838. this._attributes = null;
  36839. this._geometries = null;
  36840. this._nodes = null;
  36841. this._animation = null;
  36842. this._bindings = null;
  36843. this._objects = null;
  36844. this._pipelines = null;
  36845. this._bundles = null;
  36846. this._renderLists = null;
  36847. this._renderContexts = null;
  36848. this._textures = null;
  36849. this._background = null;
  36850. this._quad = new QuadMesh( new NodeMaterial() );
  36851. this._currentRenderContext = null;
  36852. this._opaqueSort = null;
  36853. this._transparentSort = null;
  36854. this._frameBufferTarget = null;
  36855. const alphaClear = this.alpha === true ? 0 : 1;
  36856. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  36857. this._clearDepth = 1;
  36858. this._clearStencil = 0;
  36859. this._renderTarget = null;
  36860. this._activeCubeFace = 0;
  36861. this._activeMipmapLevel = 0;
  36862. this._mrt = null;
  36863. this._renderObjectFunction = null;
  36864. this._currentRenderObjectFunction = null;
  36865. this._currentRenderBundle = null;
  36866. this._handleObjectFunction = this._renderObjectDirect;
  36867. this._initialized = false;
  36868. this._initPromise = null;
  36869. this._compilationPromises = null;
  36870. this.transparent = true;
  36871. this.opaque = true;
  36872. this.shadowMap = {
  36873. enabled: false,
  36874. type: null
  36875. };
  36876. this.xr = {
  36877. enabled: false
  36878. };
  36879. this.debug = {
  36880. checkShaderErrors: true,
  36881. onShaderError: null
  36882. };
  36883. }
  36884. async init() {
  36885. if ( this._initialized ) {
  36886. throw new Error( 'Renderer: Backend has already been initialized.' );
  36887. }
  36888. if ( this._initPromise !== null ) {
  36889. return this._initPromise;
  36890. }
  36891. this._initPromise = new Promise( async ( resolve, reject ) => {
  36892. const backend = this.backend;
  36893. try {
  36894. await backend.init( this );
  36895. } catch ( error ) {
  36896. reject( error );
  36897. return;
  36898. }
  36899. this._nodes = new Nodes( this, backend );
  36900. this._animation = new Animation( this._nodes, this.info );
  36901. this._attributes = new Attributes( backend );
  36902. this._background = new Background( this, this._nodes );
  36903. this._geometries = new Geometries( this._attributes, this.info );
  36904. this._textures = new Textures( this, backend, this.info );
  36905. this._pipelines = new Pipelines( backend, this._nodes );
  36906. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  36907. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  36908. this._renderLists = new RenderLists();
  36909. this._bundles = new RenderBundles();
  36910. this._renderContexts = new RenderContexts();
  36911. //
  36912. this._initialized = true;
  36913. resolve();
  36914. } );
  36915. return this._initPromise;
  36916. }
  36917. get coordinateSystem() {
  36918. return this.backend.coordinateSystem;
  36919. }
  36920. async compileAsync( scene, camera, targetScene = null ) {
  36921. if ( this._initialized === false ) await this.init();
  36922. // preserve render tree
  36923. const nodeFrame = this._nodes.nodeFrame;
  36924. const previousRenderId = nodeFrame.renderId;
  36925. const previousRenderContext = this._currentRenderContext;
  36926. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36927. const previousCompilationPromises = this._compilationPromises;
  36928. //
  36929. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36930. if ( targetScene === null ) targetScene = scene;
  36931. const renderTarget = this._renderTarget;
  36932. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  36933. const activeMipmapLevel = this._activeMipmapLevel;
  36934. const compilationPromises = [];
  36935. this._currentRenderContext = renderContext;
  36936. this._currentRenderObjectFunction = this.renderObject;
  36937. this._handleObjectFunction = this._createObjectPipeline;
  36938. this._compilationPromises = compilationPromises;
  36939. nodeFrame.renderId ++;
  36940. //
  36941. nodeFrame.update();
  36942. //
  36943. renderContext.depth = this.depth;
  36944. renderContext.stencil = this.stencil;
  36945. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36946. renderContext.clippingContext.updateGlobal( this, camera );
  36947. //
  36948. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36949. //
  36950. const renderList = this._renderLists.get( scene, camera );
  36951. renderList.begin();
  36952. this._projectObject( scene, camera, 0, renderList );
  36953. // include lights from target scene
  36954. if ( targetScene !== scene ) {
  36955. targetScene.traverseVisible( function ( object ) {
  36956. if ( object.isLight && object.layers.test( camera.layers ) ) {
  36957. renderList.pushLight( object );
  36958. }
  36959. } );
  36960. }
  36961. renderList.finish();
  36962. //
  36963. if ( renderTarget !== null ) {
  36964. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36965. const renderTargetData = this._textures.get( renderTarget );
  36966. renderContext.textures = renderTargetData.textures;
  36967. renderContext.depthTexture = renderTargetData.depthTexture;
  36968. } else {
  36969. renderContext.textures = null;
  36970. renderContext.depthTexture = null;
  36971. }
  36972. //
  36973. this._nodes.updateScene( sceneRef );
  36974. //
  36975. this._background.update( sceneRef, renderList, renderContext );
  36976. // process render lists
  36977. const opaqueObjects = renderList.opaque;
  36978. const transparentObjects = renderList.transparent;
  36979. const lightsNode = renderList.lightsNode;
  36980. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36981. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  36982. // restore render tree
  36983. nodeFrame.renderId = previousRenderId;
  36984. this._currentRenderContext = previousRenderContext;
  36985. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36986. this._compilationPromises = previousCompilationPromises;
  36987. this._handleObjectFunction = this._renderObjectDirect;
  36988. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  36989. await Promise.all( compilationPromises );
  36990. }
  36991. async renderAsync( scene, camera ) {
  36992. if ( this._initialized === false ) await this.init();
  36993. const renderContext = this._renderScene( scene, camera );
  36994. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  36995. }
  36996. setMRT( mrt ) {
  36997. this._mrt = mrt;
  36998. return this;
  36999. }
  37000. getMRT() {
  37001. return this._mrt;
  37002. }
  37003. _renderBundle( bundle, sceneRef, lightsNode ) {
  37004. const { object, camera, renderList } = bundle;
  37005. const renderContext = this._currentRenderContext;
  37006. const renderContextData = this.backend.get( renderContext );
  37007. //
  37008. const renderBundle = this._bundles.get( object, camera );
  37009. const renderBundleData = this.backend.get( renderBundle );
  37010. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37011. //
  37012. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  37013. renderBundleData.renderContexts.add( renderContext );
  37014. if ( renderBundleNeedsUpdate ) {
  37015. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  37016. const nodeFrame = this._nodes.nodeFrame;
  37017. renderContextData.renderObjects = [];
  37018. renderContextData.renderBundles = [];
  37019. renderContextData.scene = sceneRef;
  37020. renderContextData.camera = camera;
  37021. renderContextData.renderId = nodeFrame.renderId;
  37022. renderContextData.registerBundlesPhase = true;
  37023. }
  37024. this._currentRenderBundle = renderBundle;
  37025. const opaqueObjects = renderList.opaque;
  37026. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37027. this._currentRenderBundle = null;
  37028. //
  37029. object.needsUpdate = false;
  37030. } else {
  37031. const renderContext = this._currentRenderContext;
  37032. const renderContextData = this.backend.get( renderContext );
  37033. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  37034. const renderObject = renderContextData.renderObjects[ i ];
  37035. this._nodes.updateBefore( renderObject );
  37036. //
  37037. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  37038. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  37039. this._nodes.updateForRender( renderObject );
  37040. this._bindings.updateForRender( renderObject );
  37041. this.backend.draw( renderObject, this.info );
  37042. this._nodes.updateAfter( renderObject );
  37043. }
  37044. }
  37045. }
  37046. render( scene, camera ) {
  37047. if ( this._initialized === false ) {
  37048. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37049. return this.renderAsync( scene, camera );
  37050. }
  37051. this._renderScene( scene, camera );
  37052. }
  37053. _getFrameBufferTarget() {
  37054. const { currentColorSpace } = this;
  37055. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping );
  37056. const useColorSpace = this._renderTarget === null && ( currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace );
  37057. if ( useToneMapping === false && useColorSpace === false ) return null;
  37058. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37059. const { depth, stencil } = this;
  37060. let frameBufferTarget = this._frameBufferTarget;
  37061. if ( frameBufferTarget === null ) {
  37062. frameBufferTarget = new RenderTarget( width, height, {
  37063. depthBuffer: depth,
  37064. stencilBuffer: stencil,
  37065. type: HalfFloatType, // FloatType
  37066. format: RGBAFormat,
  37067. colorSpace: LinearSRGBColorSpace,
  37068. generateMipmaps: false,
  37069. minFilter: LinearFilter,
  37070. magFilter: LinearFilter,
  37071. samples: this.samples
  37072. } );
  37073. frameBufferTarget.isPostProcessingRenderTarget = true;
  37074. this._frameBufferTarget = frameBufferTarget;
  37075. }
  37076. frameBufferTarget.depthBuffer = depth;
  37077. frameBufferTarget.stencilBuffer = stencil;
  37078. frameBufferTarget.setSize( width, height );
  37079. frameBufferTarget.viewport.copy( this._viewport );
  37080. frameBufferTarget.scissor.copy( this._scissor );
  37081. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37082. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37083. frameBufferTarget.scissorTest = this._scissorTest;
  37084. return frameBufferTarget;
  37085. }
  37086. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37087. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37088. // preserve render tree
  37089. const nodeFrame = this._nodes.nodeFrame;
  37090. const previousRenderId = nodeFrame.renderId;
  37091. const previousRenderContext = this._currentRenderContext;
  37092. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37093. //
  37094. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37095. const outputRenderTarget = this._renderTarget;
  37096. const activeCubeFace = this._activeCubeFace;
  37097. const activeMipmapLevel = this._activeMipmapLevel;
  37098. //
  37099. let renderTarget;
  37100. if ( frameBufferTarget !== null ) {
  37101. renderTarget = frameBufferTarget;
  37102. this.setRenderTarget( renderTarget );
  37103. } else {
  37104. renderTarget = outputRenderTarget;
  37105. }
  37106. //
  37107. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37108. this._currentRenderContext = renderContext;
  37109. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37110. //
  37111. this.info.calls ++;
  37112. this.info.render.calls ++;
  37113. this.info.render.frameCalls ++;
  37114. nodeFrame.renderId = this.info.calls;
  37115. //
  37116. const coordinateSystem = this.coordinateSystem;
  37117. if ( camera.coordinateSystem !== coordinateSystem ) {
  37118. camera.coordinateSystem = coordinateSystem;
  37119. camera.updateProjectionMatrix();
  37120. }
  37121. //
  37122. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37123. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37124. //
  37125. let viewport = this._viewport;
  37126. let scissor = this._scissor;
  37127. let pixelRatio = this._pixelRatio;
  37128. if ( renderTarget !== null ) {
  37129. viewport = renderTarget.viewport;
  37130. scissor = renderTarget.scissor;
  37131. pixelRatio = 1;
  37132. }
  37133. this.getDrawingBufferSize( _drawingBufferSize );
  37134. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37135. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37136. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37137. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37138. renderContext.viewportValue.width >>= activeMipmapLevel;
  37139. renderContext.viewportValue.height >>= activeMipmapLevel;
  37140. renderContext.viewportValue.minDepth = minDepth;
  37141. renderContext.viewportValue.maxDepth = maxDepth;
  37142. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37143. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37144. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37145. renderContext.scissorValue.width >>= activeMipmapLevel;
  37146. renderContext.scissorValue.height >>= activeMipmapLevel;
  37147. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37148. renderContext.clippingContext.updateGlobal( this, camera );
  37149. //
  37150. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37151. //
  37152. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37153. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37154. const renderList = this._renderLists.get( scene, camera );
  37155. renderList.begin();
  37156. this._projectObject( scene, camera, 0, renderList );
  37157. renderList.finish();
  37158. if ( this.sortObjects === true ) {
  37159. renderList.sort( this._opaqueSort, this._transparentSort );
  37160. }
  37161. //
  37162. if ( renderTarget !== null ) {
  37163. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37164. const renderTargetData = this._textures.get( renderTarget );
  37165. renderContext.textures = renderTargetData.textures;
  37166. renderContext.depthTexture = renderTargetData.depthTexture;
  37167. renderContext.width = renderTargetData.width;
  37168. renderContext.height = renderTargetData.height;
  37169. renderContext.renderTarget = renderTarget;
  37170. renderContext.depth = renderTarget.depthBuffer;
  37171. renderContext.stencil = renderTarget.stencilBuffer;
  37172. } else {
  37173. renderContext.textures = null;
  37174. renderContext.depthTexture = null;
  37175. renderContext.width = this.domElement.width;
  37176. renderContext.height = this.domElement.height;
  37177. renderContext.depth = this.depth;
  37178. renderContext.stencil = this.stencil;
  37179. }
  37180. renderContext.width >>= activeMipmapLevel;
  37181. renderContext.height >>= activeMipmapLevel;
  37182. renderContext.activeCubeFace = activeCubeFace;
  37183. renderContext.activeMipmapLevel = activeMipmapLevel;
  37184. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37185. //
  37186. this._nodes.updateScene( sceneRef );
  37187. //
  37188. this._background.update( sceneRef, renderList, renderContext );
  37189. //
  37190. this.backend.beginRender( renderContext );
  37191. // process render lists
  37192. const opaqueObjects = renderList.opaque;
  37193. const transparentObjects = renderList.transparent;
  37194. const bundles = renderList.bundles;
  37195. const lightsNode = renderList.lightsNode;
  37196. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37197. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37198. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37199. // finish render pass
  37200. this.backend.finishRender( renderContext );
  37201. // restore render tree
  37202. nodeFrame.renderId = previousRenderId;
  37203. this._currentRenderContext = previousRenderContext;
  37204. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37205. //
  37206. if ( frameBufferTarget !== null ) {
  37207. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37208. const quad = this._quad;
  37209. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37210. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37211. quad.material.needsUpdate = true;
  37212. }
  37213. this._renderScene( quad, quad.camera, false );
  37214. }
  37215. //
  37216. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37217. //
  37218. return renderContext;
  37219. }
  37220. getMaxAnisotropy() {
  37221. return this.backend.getMaxAnisotropy();
  37222. }
  37223. getActiveCubeFace() {
  37224. return this._activeCubeFace;
  37225. }
  37226. getActiveMipmapLevel() {
  37227. return this._activeMipmapLevel;
  37228. }
  37229. async setAnimationLoop( callback ) {
  37230. if ( this._initialized === false ) await this.init();
  37231. this._animation.setAnimationLoop( callback );
  37232. }
  37233. async getArrayBufferAsync( attribute ) {
  37234. return await this.backend.getArrayBufferAsync( attribute );
  37235. }
  37236. getContext() {
  37237. return this.backend.getContext();
  37238. }
  37239. getPixelRatio() {
  37240. return this._pixelRatio;
  37241. }
  37242. getDrawingBufferSize( target ) {
  37243. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37244. }
  37245. getSize( target ) {
  37246. return target.set( this._width, this._height );
  37247. }
  37248. setPixelRatio( value = 1 ) {
  37249. this._pixelRatio = value;
  37250. this.setSize( this._width, this._height, false );
  37251. }
  37252. setDrawingBufferSize( width, height, pixelRatio ) {
  37253. this._width = width;
  37254. this._height = height;
  37255. this._pixelRatio = pixelRatio;
  37256. this.domElement.width = Math.floor( width * pixelRatio );
  37257. this.domElement.height = Math.floor( height * pixelRatio );
  37258. this.setViewport( 0, 0, width, height );
  37259. if ( this._initialized ) this.backend.updateSize();
  37260. }
  37261. setSize( width, height, updateStyle = true ) {
  37262. this._width = width;
  37263. this._height = height;
  37264. this.domElement.width = Math.floor( width * this._pixelRatio );
  37265. this.domElement.height = Math.floor( height * this._pixelRatio );
  37266. if ( updateStyle === true ) {
  37267. this.domElement.style.width = width + 'px';
  37268. this.domElement.style.height = height + 'px';
  37269. }
  37270. this.setViewport( 0, 0, width, height );
  37271. if ( this._initialized ) this.backend.updateSize();
  37272. }
  37273. setOpaqueSort( method ) {
  37274. this._opaqueSort = method;
  37275. }
  37276. setTransparentSort( method ) {
  37277. this._transparentSort = method;
  37278. }
  37279. getScissor( target ) {
  37280. const scissor = this._scissor;
  37281. target.x = scissor.x;
  37282. target.y = scissor.y;
  37283. target.width = scissor.width;
  37284. target.height = scissor.height;
  37285. return target;
  37286. }
  37287. setScissor( x, y, width, height ) {
  37288. const scissor = this._scissor;
  37289. if ( x.isVector4 ) {
  37290. scissor.copy( x );
  37291. } else {
  37292. scissor.set( x, y, width, height );
  37293. }
  37294. }
  37295. getScissorTest() {
  37296. return this._scissorTest;
  37297. }
  37298. setScissorTest( boolean ) {
  37299. this._scissorTest = boolean;
  37300. this.backend.setScissorTest( boolean );
  37301. }
  37302. getViewport( target ) {
  37303. return target.copy( this._viewport );
  37304. }
  37305. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37306. const viewport = this._viewport;
  37307. if ( x.isVector4 ) {
  37308. viewport.copy( x );
  37309. } else {
  37310. viewport.set( x, y, width, height );
  37311. }
  37312. viewport.minDepth = minDepth;
  37313. viewport.maxDepth = maxDepth;
  37314. }
  37315. getClearColor( target ) {
  37316. return target.copy( this._clearColor );
  37317. }
  37318. setClearColor( color, alpha = 1 ) {
  37319. this._clearColor.set( color );
  37320. this._clearColor.a = alpha;
  37321. }
  37322. getClearAlpha() {
  37323. return this._clearColor.a;
  37324. }
  37325. setClearAlpha( alpha ) {
  37326. this._clearColor.a = alpha;
  37327. }
  37328. getClearDepth() {
  37329. return this._clearDepth;
  37330. }
  37331. setClearDepth( depth ) {
  37332. this._clearDepth = depth;
  37333. }
  37334. getClearStencil() {
  37335. return this._clearStencil;
  37336. }
  37337. setClearStencil( stencil ) {
  37338. this._clearStencil = stencil;
  37339. }
  37340. isOccluded( object ) {
  37341. const renderContext = this._currentRenderContext;
  37342. return renderContext && this.backend.isOccluded( renderContext, object );
  37343. }
  37344. clear( color = true, depth = true, stencil = true ) {
  37345. if ( this._initialized === false ) {
  37346. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37347. return this.clearAsync( color, depth, stencil );
  37348. }
  37349. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37350. let renderTargetData = null;
  37351. if ( renderTarget !== null ) {
  37352. this._textures.updateRenderTarget( renderTarget );
  37353. renderTargetData = this._textures.get( renderTarget );
  37354. }
  37355. this.backend.clear( color, depth, stencil, renderTargetData );
  37356. if ( renderTarget !== null && this._renderTarget === null ) {
  37357. // If a color space transform or tone mapping is required,
  37358. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  37359. const quad = this._quad;
  37360. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37361. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37362. quad.material.needsUpdate = true;
  37363. }
  37364. this._renderScene( quad, quad.camera, false );
  37365. }
  37366. }
  37367. clearColor() {
  37368. return this.clear( true, false, false );
  37369. }
  37370. clearDepth() {
  37371. return this.clear( false, true, false );
  37372. }
  37373. clearStencil() {
  37374. return this.clear( false, false, true );
  37375. }
  37376. async clearAsync( color = true, depth = true, stencil = true ) {
  37377. if ( this._initialized === false ) await this.init();
  37378. this.clear( color, depth, stencil );
  37379. }
  37380. clearColorAsync() {
  37381. return this.clearAsync( true, false, false );
  37382. }
  37383. clearDepthAsync() {
  37384. return this.clearAsync( false, true, false );
  37385. }
  37386. clearStencilAsync() {
  37387. return this.clearAsync( false, false, true );
  37388. }
  37389. get currentColorSpace() {
  37390. const renderTarget = this._renderTarget;
  37391. if ( renderTarget !== null ) {
  37392. const texture = renderTarget.texture;
  37393. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  37394. }
  37395. return this.outputColorSpace;
  37396. }
  37397. dispose() {
  37398. this.info.dispose();
  37399. this._animation.dispose();
  37400. this._objects.dispose();
  37401. this._pipelines.dispose();
  37402. this._nodes.dispose();
  37403. this._bindings.dispose();
  37404. this._renderLists.dispose();
  37405. this._renderContexts.dispose();
  37406. this._textures.dispose();
  37407. this.setRenderTarget( null );
  37408. this.setAnimationLoop( null );
  37409. }
  37410. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37411. this._renderTarget = renderTarget;
  37412. this._activeCubeFace = activeCubeFace;
  37413. this._activeMipmapLevel = activeMipmapLevel;
  37414. }
  37415. getRenderTarget() {
  37416. return this._renderTarget;
  37417. }
  37418. setRenderObjectFunction( renderObjectFunction ) {
  37419. this._renderObjectFunction = renderObjectFunction;
  37420. }
  37421. getRenderObjectFunction() {
  37422. return this._renderObjectFunction;
  37423. }
  37424. async computeAsync( computeNodes ) {
  37425. if ( this._initialized === false ) await this.init();
  37426. const nodeFrame = this._nodes.nodeFrame;
  37427. const previousRenderId = nodeFrame.renderId;
  37428. //
  37429. this.info.calls ++;
  37430. this.info.compute.calls ++;
  37431. this.info.compute.frameCalls ++;
  37432. nodeFrame.renderId = this.info.calls;
  37433. //
  37434. const backend = this.backend;
  37435. const pipelines = this._pipelines;
  37436. const bindings = this._bindings;
  37437. const nodes = this._nodes;
  37438. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  37439. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  37440. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  37441. }
  37442. backend.beginCompute( computeNodes );
  37443. for ( const computeNode of computeList ) {
  37444. // onInit
  37445. if ( pipelines.has( computeNode ) === false ) {
  37446. const dispose = () => {
  37447. computeNode.removeEventListener( 'dispose', dispose );
  37448. pipelines.delete( computeNode );
  37449. bindings.delete( computeNode );
  37450. nodes.delete( computeNode );
  37451. };
  37452. computeNode.addEventListener( 'dispose', dispose );
  37453. //
  37454. computeNode.onInit( { renderer: this } );
  37455. }
  37456. nodes.updateForCompute( computeNode );
  37457. bindings.updateForCompute( computeNode );
  37458. const computeBindings = bindings.getForCompute( computeNode );
  37459. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37460. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37461. }
  37462. backend.finishCompute( computeNodes );
  37463. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  37464. //
  37465. nodeFrame.renderId = previousRenderId;
  37466. }
  37467. async hasFeatureAsync( name ) {
  37468. if ( this._initialized === false ) await this.init();
  37469. return this.backend.hasFeature( name );
  37470. }
  37471. hasFeature( name ) {
  37472. if ( this._initialized === false ) {
  37473. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37474. return false;
  37475. }
  37476. return this.backend.hasFeature( name );
  37477. }
  37478. copyFramebufferToTexture( framebufferTexture ) {
  37479. const renderContext = this._currentRenderContext;
  37480. this._textures.updateTexture( framebufferTexture );
  37481. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  37482. }
  37483. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  37484. this._textures.updateTexture( srcTexture );
  37485. this._textures.updateTexture( dstTexture );
  37486. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  37487. }
  37488. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  37489. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  37490. }
  37491. _projectObject( object, camera, groupOrder, renderList ) {
  37492. if ( object.visible === false ) return;
  37493. const visible = object.layers.test( camera.layers );
  37494. if ( visible ) {
  37495. if ( object.isGroup ) {
  37496. groupOrder = object.renderOrder;
  37497. } else if ( object.isLOD ) {
  37498. if ( object.autoUpdate === true ) object.update( camera );
  37499. } else if ( object.isLight ) {
  37500. renderList.pushLight( object );
  37501. } else if ( object.isSprite ) {
  37502. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  37503. if ( this.sortObjects === true ) {
  37504. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  37505. }
  37506. const geometry = object.geometry;
  37507. const material = object.material;
  37508. if ( material.visible ) {
  37509. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  37510. }
  37511. }
  37512. } else if ( object.isLineLoop ) {
  37513. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  37514. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  37515. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  37516. const geometry = object.geometry;
  37517. const material = object.material;
  37518. if ( this.sortObjects === true ) {
  37519. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  37520. _vector3
  37521. .copy( geometry.boundingSphere.center )
  37522. .applyMatrix4( object.matrixWorld )
  37523. .applyMatrix4( _projScreenMatrix );
  37524. }
  37525. if ( Array.isArray( material ) ) {
  37526. const groups = geometry.groups;
  37527. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  37528. const group = groups[ i ];
  37529. const groupMaterial = material[ group.materialIndex ];
  37530. if ( groupMaterial && groupMaterial.visible ) {
  37531. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  37532. }
  37533. }
  37534. } else if ( material.visible ) {
  37535. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  37536. }
  37537. }
  37538. }
  37539. }
  37540. if ( object.static === true ) {
  37541. const baseRenderList = renderList;
  37542. // replace render list
  37543. renderList = this._renderLists.get( object, camera );
  37544. renderList.begin();
  37545. baseRenderList.pushBundle( {
  37546. object,
  37547. camera,
  37548. renderList,
  37549. } );
  37550. renderList.finish();
  37551. }
  37552. const children = object.children;
  37553. for ( let i = 0, l = children.length; i < l; i ++ ) {
  37554. this._projectObject( children[ i ], camera, groupOrder, renderList );
  37555. }
  37556. }
  37557. _renderBundles( bundles, sceneRef, lightsNode ) {
  37558. for ( const bundle of bundles ) {
  37559. this._renderBundle( bundle, sceneRef, lightsNode );
  37560. }
  37561. }
  37562. _renderObjects( renderList, camera, scene, lightsNode ) {
  37563. // process renderable objects
  37564. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  37565. const renderItem = renderList[ i ];
  37566. // @TODO: Add support for multiple materials per object. This will require to extract
  37567. // the material from the renderItem object and pass it with its group data to renderObject().
  37568. const { object, geometry, material, group } = renderItem;
  37569. if ( camera.isArrayCamera ) {
  37570. const cameras = camera.cameras;
  37571. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  37572. const camera2 = cameras[ j ];
  37573. if ( object.layers.test( camera2.layers ) ) {
  37574. const vp = camera2.viewport;
  37575. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  37576. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  37577. const viewportValue = this._currentRenderContext.viewportValue;
  37578. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  37579. viewportValue.minDepth = minDepth;
  37580. viewportValue.maxDepth = maxDepth;
  37581. this.backend.updateViewport( this._currentRenderContext );
  37582. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  37583. }
  37584. }
  37585. } else {
  37586. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  37587. }
  37588. }
  37589. }
  37590. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  37591. let overridePositionNode;
  37592. let overrideFragmentNode;
  37593. let overrideDepthNode;
  37594. //
  37595. object.onBeforeRender( this, scene, camera, geometry, material, group );
  37596. //
  37597. if ( scene.overrideMaterial !== null ) {
  37598. const overrideMaterial = scene.overrideMaterial;
  37599. if ( material.positionNode && material.positionNode.isNode ) {
  37600. overridePositionNode = overrideMaterial.positionNode;
  37601. overrideMaterial.positionNode = material.positionNode;
  37602. }
  37603. if ( overrideMaterial.isShadowNodeMaterial ) {
  37604. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  37605. if ( material.depthNode && material.depthNode.isNode ) {
  37606. overrideDepthNode = overrideMaterial.depthNode;
  37607. overrideMaterial.depthNode = material.depthNode;
  37608. }
  37609. if ( material.shadowNode && material.shadowNode.isNode ) {
  37610. overrideFragmentNode = overrideMaterial.fragmentNode;
  37611. overrideMaterial.fragmentNode = material.shadowNode;
  37612. }
  37613. if ( this.localClippingEnabled ) {
  37614. if ( material.clipShadows ) {
  37615. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  37616. overrideMaterial.clippingPlanes = material.clippingPlanes;
  37617. overrideMaterial.needsUpdate = true;
  37618. }
  37619. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  37620. overrideMaterial.clipIntersection = material.clipIntersection;
  37621. }
  37622. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  37623. overrideMaterial.clippingPlanes = null;
  37624. overrideMaterial.needsUpdate = true;
  37625. }
  37626. }
  37627. }
  37628. material = overrideMaterial;
  37629. }
  37630. //
  37631. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  37632. material.side = BackSide;
  37633. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  37634. material.side = FrontSide;
  37635. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  37636. material.side = DoubleSide;
  37637. } else {
  37638. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  37639. }
  37640. //
  37641. if ( overridePositionNode !== undefined ) {
  37642. scene.overrideMaterial.positionNode = overridePositionNode;
  37643. }
  37644. if ( overrideDepthNode !== undefined ) {
  37645. scene.overrideMaterial.depthNode = overrideDepthNode;
  37646. }
  37647. if ( overrideFragmentNode !== undefined ) {
  37648. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  37649. }
  37650. //
  37651. object.onAfterRender( this, scene, camera, geometry, material, group );
  37652. }
  37653. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  37654. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  37655. renderObject.drawRange = group || object.geometry.drawRange;
  37656. //
  37657. this._nodes.updateBefore( renderObject );
  37658. //
  37659. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  37660. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  37661. //
  37662. this._nodes.updateForRender( renderObject );
  37663. this._geometries.updateForRender( renderObject );
  37664. this._bindings.updateForRender( renderObject );
  37665. this._pipelines.updateForRender( renderObject );
  37666. //
  37667. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  37668. const renderObjectData = this.backend.get( renderObject );
  37669. renderObjectData.bundleEncoder = undefined;
  37670. renderObjectData.lastPipelineGPU = undefined;
  37671. }
  37672. this.backend.draw( renderObject, this.info );
  37673. if ( this._currentRenderBundle !== null ) {
  37674. const renderContextData = this.backend.get( this._currentRenderContext );
  37675. renderContextData.renderObjects.push( renderObject );
  37676. }
  37677. this._nodes.updateAfter( renderObject );
  37678. }
  37679. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  37680. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  37681. //
  37682. this._nodes.updateBefore( renderObject );
  37683. //
  37684. this._nodes.updateForRender( renderObject );
  37685. this._geometries.updateForRender( renderObject );
  37686. this._bindings.updateForRender( renderObject );
  37687. this._pipelines.getForRender( renderObject, this._compilationPromises );
  37688. this._nodes.updateAfter( renderObject );
  37689. }
  37690. get compute() {
  37691. return this.computeAsync;
  37692. }
  37693. get compile() {
  37694. return this.compileAsync;
  37695. }
  37696. }
  37697. class Binding {
  37698. constructor( name = '' ) {
  37699. this.name = name;
  37700. this.visibility = 0;
  37701. }
  37702. setVisibility( visibility ) {
  37703. this.visibility |= visibility;
  37704. }
  37705. clone() {
  37706. return Object.assign( new this.constructor(), this );
  37707. }
  37708. }
  37709. function getFloatLength( floatLength ) {
  37710. // ensure chunk size alignment (STD140 layout)
  37711. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  37712. }
  37713. class Buffer extends Binding {
  37714. constructor( name, buffer = null ) {
  37715. super( name );
  37716. this.isBuffer = true;
  37717. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  37718. this._buffer = buffer;
  37719. }
  37720. get byteLength() {
  37721. return getFloatLength( this._buffer.byteLength );
  37722. }
  37723. get buffer() {
  37724. return this._buffer;
  37725. }
  37726. update() {
  37727. return true;
  37728. }
  37729. }
  37730. class UniformBuffer extends Buffer {
  37731. constructor( name, buffer = null ) {
  37732. super( name, buffer );
  37733. this.isUniformBuffer = true;
  37734. }
  37735. }
  37736. let _id$4 = 0;
  37737. class NodeUniformBuffer extends UniformBuffer {
  37738. constructor( nodeUniform, groupNode ) {
  37739. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  37740. this.nodeUniform = nodeUniform;
  37741. this.groupNode = groupNode;
  37742. }
  37743. get buffer() {
  37744. return this.nodeUniform.value;
  37745. }
  37746. }
  37747. class UniformsGroup extends UniformBuffer {
  37748. constructor( name ) {
  37749. super( name );
  37750. this.isUniformsGroup = true;
  37751. this._values = null;
  37752. // the order of uniforms in this array must match the order of uniforms in the shader
  37753. this.uniforms = [];
  37754. }
  37755. addUniform( uniform ) {
  37756. this.uniforms.push( uniform );
  37757. return this;
  37758. }
  37759. removeUniform( uniform ) {
  37760. const index = this.uniforms.indexOf( uniform );
  37761. if ( index !== - 1 ) {
  37762. this.uniforms.splice( index, 1 );
  37763. }
  37764. return this;
  37765. }
  37766. get values() {
  37767. if ( this._values === null ) {
  37768. this._values = Array.from( this.buffer );
  37769. }
  37770. return this._values;
  37771. }
  37772. get buffer() {
  37773. let buffer = this._buffer;
  37774. if ( buffer === null ) {
  37775. const byteLength = this.byteLength;
  37776. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  37777. this._buffer = buffer;
  37778. }
  37779. return buffer;
  37780. }
  37781. get byteLength() {
  37782. let offset = 0; // global buffer offset in bytes
  37783. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  37784. const uniform = this.uniforms[ i ];
  37785. const { boundary, itemSize } = uniform;
  37786. // offset within a single chunk in bytes
  37787. const chunkOffset = offset % GPU_CHUNK_BYTES;
  37788. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  37789. // conformance tests
  37790. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  37791. // check for chunk overflow
  37792. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  37793. } else if ( chunkOffset % boundary !== 0 ) {
  37794. // check for correct alignment
  37795. offset += ( chunkOffset % boundary );
  37796. }
  37797. uniform.offset = ( offset / this.bytesPerElement );
  37798. offset += ( itemSize * this.bytesPerElement );
  37799. }
  37800. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  37801. }
  37802. update() {
  37803. let updated = false;
  37804. for ( const uniform of this.uniforms ) {
  37805. if ( this.updateByType( uniform ) === true ) {
  37806. updated = true;
  37807. }
  37808. }
  37809. return updated;
  37810. }
  37811. updateByType( uniform ) {
  37812. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  37813. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  37814. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  37815. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  37816. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  37817. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  37818. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  37819. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  37820. }
  37821. updateNumber( uniform ) {
  37822. let updated = false;
  37823. const a = this.values;
  37824. const v = uniform.getValue();
  37825. const offset = uniform.offset;
  37826. if ( a[ offset ] !== v ) {
  37827. const b = this.buffer;
  37828. b[ offset ] = a[ offset ] = v;
  37829. updated = true;
  37830. }
  37831. return updated;
  37832. }
  37833. updateVector2( uniform ) {
  37834. let updated = false;
  37835. const a = this.values;
  37836. const v = uniform.getValue();
  37837. const offset = uniform.offset;
  37838. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  37839. const b = this.buffer;
  37840. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37841. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37842. updated = true;
  37843. }
  37844. return updated;
  37845. }
  37846. updateVector3( uniform ) {
  37847. let updated = false;
  37848. const a = this.values;
  37849. const v = uniform.getValue();
  37850. const offset = uniform.offset;
  37851. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  37852. const b = this.buffer;
  37853. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37854. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37855. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37856. updated = true;
  37857. }
  37858. return updated;
  37859. }
  37860. updateVector4( uniform ) {
  37861. let updated = false;
  37862. const a = this.values;
  37863. const v = uniform.getValue();
  37864. const offset = uniform.offset;
  37865. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  37866. const b = this.buffer;
  37867. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37868. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37869. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37870. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  37871. updated = true;
  37872. }
  37873. return updated;
  37874. }
  37875. updateColor( uniform ) {
  37876. let updated = false;
  37877. const a = this.values;
  37878. const c = uniform.getValue();
  37879. const offset = uniform.offset;
  37880. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  37881. const b = this.buffer;
  37882. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  37883. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  37884. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  37885. updated = true;
  37886. }
  37887. return updated;
  37888. }
  37889. updateMatrix3( uniform ) {
  37890. let updated = false;
  37891. const a = this.values;
  37892. const e = uniform.getValue().elements;
  37893. const offset = uniform.offset;
  37894. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  37895. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  37896. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  37897. const b = this.buffer;
  37898. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  37899. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  37900. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  37901. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  37902. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  37903. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  37904. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  37905. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  37906. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  37907. updated = true;
  37908. }
  37909. return updated;
  37910. }
  37911. updateMatrix4( uniform ) {
  37912. let updated = false;
  37913. const a = this.values;
  37914. const e = uniform.getValue().elements;
  37915. const offset = uniform.offset;
  37916. if ( arraysEqual( a, e, offset ) === false ) {
  37917. const b = this.buffer;
  37918. b.set( e, offset );
  37919. setArray( a, e, offset );
  37920. updated = true;
  37921. }
  37922. return updated;
  37923. }
  37924. }
  37925. function setArray( a, b, offset ) {
  37926. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37927. a[ offset + i ] = b[ i ];
  37928. }
  37929. }
  37930. function arraysEqual( a, b, offset ) {
  37931. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37932. if ( a[ offset + i ] !== b[ i ] ) return false;
  37933. }
  37934. return true;
  37935. }
  37936. let _id$3 = 0;
  37937. class NodeUniformsGroup extends UniformsGroup {
  37938. constructor( name, groupNode ) {
  37939. super( name );
  37940. this.id = _id$3 ++;
  37941. this.groupNode = groupNode;
  37942. this.isNodeUniformsGroup = true;
  37943. }
  37944. getNodes() {
  37945. const nodes = [];
  37946. for ( const uniform of this.uniforms ) {
  37947. const node = uniform.nodeUniform.node;
  37948. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  37949. nodes.push( node );
  37950. }
  37951. return nodes;
  37952. }
  37953. }
  37954. let _id$2 = 0;
  37955. class SampledTexture extends Binding {
  37956. constructor( name, texture ) {
  37957. super( name );
  37958. this.id = _id$2 ++;
  37959. this.texture = texture;
  37960. this.version = texture ? texture.version : 0;
  37961. this.store = false;
  37962. this.isSampledTexture = true;
  37963. }
  37964. get needsBindingsUpdate() {
  37965. const { texture, version } = this;
  37966. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  37967. }
  37968. update() {
  37969. const { texture, version } = this;
  37970. if ( version !== texture.version ) {
  37971. this.version = texture.version;
  37972. return true;
  37973. }
  37974. return false;
  37975. }
  37976. }
  37977. class NodeSampledTexture extends SampledTexture {
  37978. constructor( name, textureNode, groupNode, access = null ) {
  37979. super( name, textureNode ? textureNode.value : null );
  37980. this.textureNode = textureNode;
  37981. this.groupNode = groupNode;
  37982. this.access = access;
  37983. }
  37984. get needsBindingsUpdate() {
  37985. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  37986. }
  37987. update() {
  37988. const { textureNode } = this;
  37989. if ( this.texture !== textureNode.value ) {
  37990. this.texture = textureNode.value;
  37991. return true;
  37992. }
  37993. return super.update();
  37994. }
  37995. }
  37996. class NodeSampledCubeTexture extends NodeSampledTexture {
  37997. constructor( name, textureNode, groupNode, access ) {
  37998. super( name, textureNode, groupNode, access );
  37999. this.isSampledCubeTexture = true;
  38000. }
  38001. }
  38002. class NodeSampledTexture3D extends NodeSampledTexture {
  38003. constructor( name, textureNode, groupNode, access ) {
  38004. super( name, textureNode, groupNode, access );
  38005. this.isSampledTexture3D = true;
  38006. }
  38007. }
  38008. const glslMethods = {
  38009. [ MathNode.ATAN2 ]: 'atan',
  38010. textureDimensions: 'textureSize',
  38011. equals: 'equal'
  38012. };
  38013. const precisionLib = {
  38014. low: 'lowp',
  38015. medium: 'mediump',
  38016. high: 'highp'
  38017. };
  38018. const supports$1 = {
  38019. swizzleAssign: true,
  38020. storageBuffer: false
  38021. };
  38022. const defaultPrecisions = `
  38023. precision highp float;
  38024. precision highp int;
  38025. precision highp sampler2D;
  38026. precision highp sampler3D;
  38027. precision highp samplerCube;
  38028. precision highp sampler2DArray;
  38029. precision highp usampler2D;
  38030. precision highp usampler3D;
  38031. precision highp usamplerCube;
  38032. precision highp usampler2DArray;
  38033. precision highp isampler2D;
  38034. precision highp isampler3D;
  38035. precision highp isamplerCube;
  38036. precision highp isampler2DArray;
  38037. precision lowp sampler2DShadow;
  38038. `;
  38039. class GLSLNodeBuilder extends NodeBuilder {
  38040. constructor( object, renderer ) {
  38041. super( object, renderer, new GLSLNodeParser() );
  38042. this.uniformGroups = {};
  38043. this.transforms = [];
  38044. this.instanceBindGroups = false;
  38045. }
  38046. getMethod( method ) {
  38047. return glslMethods[ method ] || method;
  38048. }
  38049. getOutputStructName() {
  38050. return '';
  38051. }
  38052. buildFunctionCode( shaderNode ) {
  38053. const layout = shaderNode.layout;
  38054. const flowData = this.flowShaderNode( shaderNode );
  38055. const parameters = [];
  38056. for ( const input of layout.inputs ) {
  38057. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38058. }
  38059. //
  38060. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38061. ${ flowData.vars }
  38062. ${ flowData.code }
  38063. return ${ flowData.result };
  38064. }`;
  38065. //
  38066. return code;
  38067. }
  38068. setupPBO( storageBufferNode ) {
  38069. const attribute = storageBufferNode.value;
  38070. if ( attribute.pbo === undefined ) {
  38071. const originalArray = attribute.array;
  38072. const numElements = attribute.count * attribute.itemSize;
  38073. const { itemSize } = attribute;
  38074. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38075. let format = isInteger ? RedIntegerFormat : RedFormat;
  38076. if ( itemSize === 2 ) {
  38077. format = isInteger ? RGIntegerFormat : RGFormat;
  38078. } else if ( itemSize === 3 ) {
  38079. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38080. } else if ( itemSize === 4 ) {
  38081. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38082. }
  38083. const typeMap = {
  38084. Float32Array: FloatType,
  38085. Uint8Array: UnsignedByteType,
  38086. Uint16Array: UnsignedShortType,
  38087. Uint32Array: UnsignedIntType,
  38088. Int8Array: ByteType,
  38089. Int16Array: ShortType,
  38090. Int32Array: IntType,
  38091. Uint8ClampedArray: UnsignedByteType,
  38092. };
  38093. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38094. let height = Math.ceil( ( numElements / itemSize ) / width );
  38095. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38096. const newSize = width * height * itemSize;
  38097. const newArray = new originalArray.constructor( newSize );
  38098. newArray.set( originalArray, 0 );
  38099. attribute.array = newArray;
  38100. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38101. pboTexture.needsUpdate = true;
  38102. pboTexture.isPBOTexture = true;
  38103. const pbo = new TextureNode( pboTexture, null, null );
  38104. pbo.setPrecision( 'high' );
  38105. attribute.pboNode = pbo;
  38106. attribute.pbo = pbo.value;
  38107. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38108. }
  38109. }
  38110. getPropertyName( node, shaderStage = this.shaderStage ) {
  38111. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38112. return shaderStage.charAt( 0 ) + '_' + node.name;
  38113. }
  38114. return super.getPropertyName( node, shaderStage );
  38115. }
  38116. generatePBO( storageArrayElementNode ) {
  38117. const { node, indexNode } = storageArrayElementNode;
  38118. const attribute = node.value;
  38119. if ( this.renderer.backend.has( attribute ) ) {
  38120. const attributeData = this.renderer.backend.get( attribute );
  38121. attributeData.pbo = attribute.pbo;
  38122. }
  38123. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38124. const textureName = this.getPropertyName( nodeUniform );
  38125. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  38126. const indexSnippet = indexNode.build( this, 'uint' );
  38127. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38128. let propertyName = elementNodeData.propertyName;
  38129. if ( propertyName === undefined ) {
  38130. // property element
  38131. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38132. propertyName = this.getPropertyName( nodeVar );
  38133. // property size
  38134. const bufferNodeData = this.getDataFromNode( node );
  38135. let propertySizeName = bufferNodeData.propertySizeName;
  38136. if ( propertySizeName === undefined ) {
  38137. propertySizeName = propertyName + 'Size';
  38138. this.getVarFromNode( node, propertySizeName, 'uint' );
  38139. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  38140. bufferNodeData.propertySizeName = propertySizeName;
  38141. }
  38142. //
  38143. const { itemSize } = attribute;
  38144. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38145. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38146. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38147. //
  38148. let prefix = 'vec4';
  38149. if ( attribute.pbo.type === UnsignedIntType ) {
  38150. prefix = 'uvec4';
  38151. } else if ( attribute.pbo.type === IntType ) {
  38152. prefix = 'ivec4';
  38153. }
  38154. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  38155. elementNodeData.propertyName = propertyName;
  38156. }
  38157. return propertyName;
  38158. }
  38159. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38160. if ( depthSnippet ) {
  38161. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38162. } else {
  38163. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38164. }
  38165. }
  38166. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38167. if ( texture.isDepthTexture ) {
  38168. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38169. } else {
  38170. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38171. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38172. }
  38173. }
  38174. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38175. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38176. }
  38177. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38178. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38179. }
  38180. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38181. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38182. }
  38183. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38184. if ( shaderStage === 'fragment' ) {
  38185. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38186. } else {
  38187. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38188. }
  38189. }
  38190. getVars( shaderStage ) {
  38191. const snippets = [];
  38192. const vars = this.vars[ shaderStage ];
  38193. if ( vars !== undefined ) {
  38194. for ( const variable of vars ) {
  38195. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38196. }
  38197. }
  38198. return snippets.join( '\n\t' );
  38199. }
  38200. getUniforms( shaderStage ) {
  38201. const uniforms = this.uniforms[ shaderStage ];
  38202. const bindingSnippets = [];
  38203. const uniformGroups = {};
  38204. for ( const uniform of uniforms ) {
  38205. let snippet = null;
  38206. let group = false;
  38207. if ( uniform.type === 'texture' ) {
  38208. const texture = uniform.node.value;
  38209. let typePrefix = '';
  38210. if ( texture.isDataTexture === true ) {
  38211. if ( texture.type === UnsignedIntType ) {
  38212. typePrefix = 'u';
  38213. } else if ( texture.type === IntType ) {
  38214. typePrefix = 'i';
  38215. }
  38216. }
  38217. if ( texture.compareFunction ) {
  38218. snippet = `sampler2DShadow ${ uniform.name };`;
  38219. } else if ( texture.isDataArrayTexture === true ) {
  38220. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38221. } else {
  38222. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38223. }
  38224. } else if ( uniform.type === 'cubeTexture' ) {
  38225. snippet = `samplerCube ${ uniform.name };`;
  38226. } else if ( uniform.type === 'texture3D' ) {
  38227. snippet = `sampler3D ${ uniform.name };`;
  38228. } else if ( uniform.type === 'buffer' ) {
  38229. const bufferNode = uniform.node;
  38230. const bufferType = this.getType( bufferNode.bufferType );
  38231. const bufferCount = bufferNode.bufferCount;
  38232. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38233. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38234. } else {
  38235. const vectorType = this.getVectorType( uniform.type );
  38236. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38237. group = true;
  38238. }
  38239. const precision = uniform.node.precision;
  38240. if ( precision !== null ) {
  38241. snippet = precisionLib[ precision ] + ' ' + snippet;
  38242. }
  38243. if ( group ) {
  38244. snippet = '\t' + snippet;
  38245. const groupName = uniform.groupNode.name;
  38246. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38247. groupSnippets.push( snippet );
  38248. } else {
  38249. snippet = 'uniform ' + snippet;
  38250. bindingSnippets.push( snippet );
  38251. }
  38252. }
  38253. let output = '';
  38254. for ( const name in uniformGroups ) {
  38255. const groupSnippets = uniformGroups[ name ];
  38256. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38257. }
  38258. output += bindingSnippets.join( '\n' );
  38259. return output;
  38260. }
  38261. getTypeFromAttribute( attribute ) {
  38262. let nodeType = super.getTypeFromAttribute( attribute );
  38263. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38264. let dataAttribute = attribute;
  38265. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38266. const array = dataAttribute.array;
  38267. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38268. nodeType = nodeType.slice( 1 );
  38269. }
  38270. }
  38271. return nodeType;
  38272. }
  38273. getAttributes( shaderStage ) {
  38274. let snippet = '';
  38275. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38276. const attributes = this.getAttributesArray();
  38277. let location = 0;
  38278. for ( const attribute of attributes ) {
  38279. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38280. }
  38281. }
  38282. return snippet;
  38283. }
  38284. getStructMembers( struct ) {
  38285. const snippets = [];
  38286. const members = struct.getMemberTypes();
  38287. for ( let i = 0; i < members.length; i ++ ) {
  38288. const member = members[ i ];
  38289. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  38290. }
  38291. return snippets.join( '\n' );
  38292. }
  38293. getStructs( shaderStage ) {
  38294. const snippets = [];
  38295. const structs = this.structs[ shaderStage ];
  38296. if ( structs.length === 0 ) {
  38297. return 'layout( location = 0 ) out vec4 fragColor;\n';
  38298. }
  38299. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  38300. const struct = structs[ index ];
  38301. let snippet = '\n';
  38302. snippet += this.getStructMembers( struct );
  38303. snippet += '\n';
  38304. snippets.push( snippet );
  38305. }
  38306. return snippets.join( '\n\n' );
  38307. }
  38308. getVaryings( shaderStage ) {
  38309. let snippet = '';
  38310. const varyings = this.varyings;
  38311. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38312. for ( const varying of varyings ) {
  38313. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38314. const type = varying.type;
  38315. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38316. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  38317. }
  38318. } else if ( shaderStage === 'fragment' ) {
  38319. for ( const varying of varyings ) {
  38320. if ( varying.needsInterpolation ) {
  38321. const type = varying.type;
  38322. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38323. snippet += `${flat}in ${type} ${varying.name};\n`;
  38324. }
  38325. }
  38326. }
  38327. return snippet;
  38328. }
  38329. getVertexIndex() {
  38330. return 'uint( gl_VertexID )';
  38331. }
  38332. getInstanceIndex() {
  38333. return 'uint( gl_InstanceID )';
  38334. }
  38335. getDrawIndex() {
  38336. const extensions = this.renderer.backend.extensions;
  38337. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38338. return 'uint( gl_DrawID )';
  38339. }
  38340. return null;
  38341. }
  38342. getFrontFacing() {
  38343. return 'gl_FrontFacing';
  38344. }
  38345. getFragCoord() {
  38346. return 'gl_FragCoord';
  38347. }
  38348. getFragDepth() {
  38349. return 'gl_FragDepth';
  38350. }
  38351. getExtensions( shaderStage ) {
  38352. let extensions = '';
  38353. if ( shaderStage === 'vertex' ) {
  38354. const ext = this.renderer.backend.extensions;
  38355. const isBatchedMesh = this.object.isBatchedMesh;
  38356. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38357. extensions += '#extension GL_ANGLE_multi_draw : require\n';
  38358. }
  38359. }
  38360. return extensions;
  38361. }
  38362. isAvailable( name ) {
  38363. let result = supports$1[ name ];
  38364. if ( result === undefined ) {
  38365. if ( name === 'float32Filterable' ) {
  38366. const extensions = this.renderer.backend.extensions;
  38367. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  38368. extensions.get( 'OES_texture_float_linear' );
  38369. result = true;
  38370. } else {
  38371. result = false;
  38372. }
  38373. }
  38374. supports$1[ name ] = result;
  38375. }
  38376. return result;
  38377. }
  38378. isFlipY() {
  38379. return true;
  38380. }
  38381. registerTransform( varyingName, attributeNode ) {
  38382. this.transforms.push( { varyingName, attributeNode } );
  38383. }
  38384. getTransforms( /* shaderStage */ ) {
  38385. const transforms = this.transforms;
  38386. let snippet = '';
  38387. for ( let i = 0; i < transforms.length; i ++ ) {
  38388. const transform = transforms[ i ];
  38389. const attributeName = this.getPropertyName( transform.attributeNode );
  38390. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38391. }
  38392. return snippet;
  38393. }
  38394. _getGLSLUniformStruct( name, vars ) {
  38395. return `
  38396. layout( std140 ) uniform ${name} {
  38397. ${vars}
  38398. };`;
  38399. }
  38400. _getGLSLVertexCode( shaderData ) {
  38401. return `#version 300 es
  38402. // extensions
  38403. ${shaderData.extensions}
  38404. // precision
  38405. ${ defaultPrecisions }
  38406. // uniforms
  38407. ${shaderData.uniforms}
  38408. // varyings
  38409. ${shaderData.varyings}
  38410. // attributes
  38411. ${shaderData.attributes}
  38412. // codes
  38413. ${shaderData.codes}
  38414. void main() {
  38415. // vars
  38416. ${shaderData.vars}
  38417. // transforms
  38418. ${shaderData.transforms}
  38419. // flow
  38420. ${shaderData.flow}
  38421. gl_PointSize = 1.0;
  38422. }
  38423. `;
  38424. }
  38425. _getGLSLFragmentCode( shaderData ) {
  38426. return `#version 300 es
  38427. ${ this.getSignature() }
  38428. // precision
  38429. ${ defaultPrecisions }
  38430. // uniforms
  38431. ${shaderData.uniforms}
  38432. // varyings
  38433. ${shaderData.varyings}
  38434. // codes
  38435. ${shaderData.codes}
  38436. ${shaderData.structs}
  38437. void main() {
  38438. // vars
  38439. ${shaderData.vars}
  38440. // flow
  38441. ${shaderData.flow}
  38442. }
  38443. `;
  38444. }
  38445. buildCode() {
  38446. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38447. for ( const shaderStage in shadersData ) {
  38448. let flow = '// code\n\n';
  38449. flow += this.flowCode[ shaderStage ];
  38450. const flowNodes = this.flowNodes[ shaderStage ];
  38451. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38452. for ( const node of flowNodes ) {
  38453. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38454. const slotName = node.name;
  38455. if ( slotName ) {
  38456. if ( flow.length > 0 ) flow += '\n';
  38457. flow += `\t// flow -> ${ slotName }\n\t`;
  38458. }
  38459. flow += `${ flowSlotData.code }\n\t`;
  38460. if ( node === mainNode && shaderStage !== 'compute' ) {
  38461. flow += '// result\n\t';
  38462. if ( shaderStage === 'vertex' ) {
  38463. flow += 'gl_Position = ';
  38464. flow += `${ flowSlotData.result };`;
  38465. } else if ( shaderStage === 'fragment' ) {
  38466. if ( ! node.outputNode.isOutputStructNode ) {
  38467. flow += 'fragColor = ';
  38468. flow += `${ flowSlotData.result };`;
  38469. }
  38470. }
  38471. }
  38472. }
  38473. const stageData = shadersData[ shaderStage ];
  38474. stageData.extensions = this.getExtensions( shaderStage );
  38475. stageData.uniforms = this.getUniforms( shaderStage );
  38476. stageData.attributes = this.getAttributes( shaderStage );
  38477. stageData.varyings = this.getVaryings( shaderStage );
  38478. stageData.vars = this.getVars( shaderStage );
  38479. stageData.structs = this.getStructs( shaderStage );
  38480. stageData.codes = this.getCodes( shaderStage );
  38481. stageData.transforms = this.getTransforms( shaderStage );
  38482. stageData.flow = flow;
  38483. }
  38484. if ( this.material !== null ) {
  38485. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  38486. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  38487. } else {
  38488. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  38489. }
  38490. }
  38491. getUniformFromNode( node, type, shaderStage, name = null ) {
  38492. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  38493. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  38494. let uniformGPU = nodeData.uniformGPU;
  38495. if ( uniformGPU === undefined ) {
  38496. const group = node.groupNode;
  38497. const groupName = group.name;
  38498. const bindings = this.getBindGroupArray( groupName, shaderStage );
  38499. if ( type === 'texture' ) {
  38500. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  38501. bindings.push( uniformGPU );
  38502. } else if ( type === 'cubeTexture' ) {
  38503. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  38504. bindings.push( uniformGPU );
  38505. } else if ( type === 'texture3D' ) {
  38506. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  38507. bindings.push( uniformGPU );
  38508. } else if ( type === 'buffer' ) {
  38509. node.name = `NodeBuffer_${ node.id }`;
  38510. uniformNode.name = `buffer${ node.id }`;
  38511. const buffer = new NodeUniformBuffer( node, group );
  38512. buffer.name = node.name;
  38513. bindings.push( buffer );
  38514. uniformGPU = buffer;
  38515. } else {
  38516. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  38517. let uniformsGroup = uniformsStage[ groupName ];
  38518. if ( uniformsGroup === undefined ) {
  38519. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  38520. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  38521. uniformsStage[ groupName ] = uniformsGroup;
  38522. bindings.push( uniformsGroup );
  38523. }
  38524. uniformGPU = this.getNodeUniform( uniformNode, type );
  38525. uniformsGroup.addUniform( uniformGPU );
  38526. }
  38527. nodeData.uniformGPU = uniformGPU;
  38528. }
  38529. return uniformNode;
  38530. }
  38531. }
  38532. let vector2 = null;
  38533. let vector4 = null;
  38534. let color4 = null;
  38535. class Backend {
  38536. constructor( parameters = {} ) {
  38537. this.parameters = Object.assign( {}, parameters );
  38538. this.data = new WeakMap();
  38539. this.renderer = null;
  38540. this.domElement = null;
  38541. }
  38542. async init( renderer ) {
  38543. this.renderer = renderer;
  38544. }
  38545. // render context
  38546. begin( /*renderContext*/ ) { }
  38547. finish( /*renderContext*/ ) { }
  38548. // render object
  38549. draw( /*renderObject, info*/ ) { }
  38550. // program
  38551. createProgram( /*program*/ ) { }
  38552. destroyProgram( /*program*/ ) { }
  38553. // bindings
  38554. createBindings( /*renderObject*/ ) { }
  38555. updateBindings( /*renderObject*/ ) { }
  38556. // pipeline
  38557. createRenderPipeline( /*renderObject*/ ) { }
  38558. createComputePipeline( /*computeNode, pipeline*/ ) { }
  38559. destroyPipeline( /*pipeline*/ ) { }
  38560. // cache key
  38561. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  38562. getRenderCacheKey( /*renderObject*/ ) { } // return String
  38563. // node builder
  38564. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  38565. // textures
  38566. createSampler( /*texture*/ ) { }
  38567. createDefaultTexture( /*texture*/ ) { }
  38568. createTexture( /*texture*/ ) { }
  38569. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  38570. // attributes
  38571. createAttribute( /*attribute*/ ) { }
  38572. createIndexAttribute( /*attribute*/ ) { }
  38573. updateAttribute( /*attribute*/ ) { }
  38574. destroyAttribute( /*attribute*/ ) { }
  38575. // canvas
  38576. getContext() { }
  38577. updateSize() { }
  38578. // utils
  38579. resolveTimestampAsync( /*renderContext, type*/ ) { }
  38580. hasFeatureAsync( /*name*/ ) { } // return Boolean
  38581. hasFeature( /*name*/ ) { } // return Boolean
  38582. getInstanceCount( renderObject ) {
  38583. const { object, geometry } = renderObject;
  38584. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  38585. }
  38586. getDrawingBufferSize() {
  38587. vector2 = vector2 || new Vector2();
  38588. return this.renderer.getDrawingBufferSize( vector2 );
  38589. }
  38590. getScissor() {
  38591. vector4 = vector4 || new Vector4();
  38592. return this.renderer.getScissor( vector4 );
  38593. }
  38594. setScissorTest( /*boolean*/ ) { }
  38595. getClearColor() {
  38596. const renderer = this.renderer;
  38597. color4 = color4 || new Color4();
  38598. renderer.getClearColor( color4 );
  38599. color4.getRGB( color4, this.renderer.currentColorSpace );
  38600. return color4;
  38601. }
  38602. getDomElement() {
  38603. let domElement = this.domElement;
  38604. if ( domElement === null ) {
  38605. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  38606. // OffscreenCanvas does not have setAttribute, see #22811
  38607. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  38608. this.domElement = domElement;
  38609. }
  38610. return domElement;
  38611. }
  38612. // resource properties
  38613. set( object, value ) {
  38614. this.data.set( object, value );
  38615. }
  38616. get( object ) {
  38617. let map = this.data.get( object );
  38618. if ( map === undefined ) {
  38619. map = {};
  38620. this.data.set( object, map );
  38621. }
  38622. return map;
  38623. }
  38624. has( object ) {
  38625. return this.data.has( object );
  38626. }
  38627. delete( object ) {
  38628. this.data.delete( object );
  38629. }
  38630. }
  38631. let _id$1 = 0;
  38632. class DualAttributeData {
  38633. constructor( attributeData, dualBuffer ) {
  38634. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38635. this.type = attributeData.type;
  38636. this.bufferType = attributeData.bufferType;
  38637. this.pbo = attributeData.pbo;
  38638. this.byteLength = attributeData.byteLength;
  38639. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38640. this.version = attributeData.version;
  38641. this.isInteger = attributeData.isInteger;
  38642. this.activeBufferIndex = 0;
  38643. this.baseId = attributeData.id;
  38644. }
  38645. get id() {
  38646. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38647. }
  38648. get bufferGPU() {
  38649. return this.buffers[ this.activeBufferIndex ];
  38650. }
  38651. get transformBuffer() {
  38652. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38653. }
  38654. switchBuffers() {
  38655. this.activeBufferIndex ^= 1;
  38656. }
  38657. }
  38658. class WebGLAttributeUtils {
  38659. constructor( backend ) {
  38660. this.backend = backend;
  38661. }
  38662. createAttribute( attribute, bufferType ) {
  38663. const backend = this.backend;
  38664. const { gl } = backend;
  38665. const array = attribute.array;
  38666. const usage = attribute.usage || gl.STATIC_DRAW;
  38667. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38668. const bufferData = backend.get( bufferAttribute );
  38669. let bufferGPU = bufferData.bufferGPU;
  38670. if ( bufferGPU === undefined ) {
  38671. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38672. bufferData.bufferGPU = bufferGPU;
  38673. bufferData.bufferType = bufferType;
  38674. bufferData.version = bufferAttribute.version;
  38675. }
  38676. //attribute.onUploadCallback();
  38677. let type;
  38678. if ( array instanceof Float32Array ) {
  38679. type = gl.FLOAT;
  38680. } else if ( array instanceof Uint16Array ) {
  38681. if ( attribute.isFloat16BufferAttribute ) {
  38682. type = gl.HALF_FLOAT;
  38683. } else {
  38684. type = gl.UNSIGNED_SHORT;
  38685. }
  38686. } else if ( array instanceof Int16Array ) {
  38687. type = gl.SHORT;
  38688. } else if ( array instanceof Uint32Array ) {
  38689. type = gl.UNSIGNED_INT;
  38690. } else if ( array instanceof Int32Array ) {
  38691. type = gl.INT;
  38692. } else if ( array instanceof Int8Array ) {
  38693. type = gl.BYTE;
  38694. } else if ( array instanceof Uint8Array ) {
  38695. type = gl.UNSIGNED_BYTE;
  38696. } else if ( array instanceof Uint8ClampedArray ) {
  38697. type = gl.UNSIGNED_BYTE;
  38698. } else {
  38699. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38700. }
  38701. let attributeData = {
  38702. bufferGPU,
  38703. bufferType,
  38704. type,
  38705. byteLength: array.byteLength,
  38706. bytesPerElement: array.BYTES_PER_ELEMENT,
  38707. version: attribute.version,
  38708. pbo: attribute.pbo,
  38709. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38710. id: _id$1 ++
  38711. };
  38712. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38713. // create buffer for tranform feedback use
  38714. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38715. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38716. }
  38717. backend.set( attribute, attributeData );
  38718. }
  38719. updateAttribute( attribute ) {
  38720. const backend = this.backend;
  38721. const { gl } = backend;
  38722. const array = attribute.array;
  38723. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38724. const bufferData = backend.get( bufferAttribute );
  38725. const bufferType = bufferData.bufferType;
  38726. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38727. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38728. if ( updateRanges.length === 0 ) {
  38729. // Not using update ranges
  38730. gl.bufferSubData( bufferType, 0, array );
  38731. } else {
  38732. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38733. const range = updateRanges[ i ];
  38734. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38735. array, range.start, range.count );
  38736. }
  38737. bufferAttribute.clearUpdateRanges();
  38738. }
  38739. gl.bindBuffer( bufferType, null );
  38740. bufferData.version = bufferAttribute.version;
  38741. }
  38742. destroyAttribute( attribute ) {
  38743. const backend = this.backend;
  38744. const { gl } = backend;
  38745. if ( attribute.isInterleavedBufferAttribute ) {
  38746. backend.delete( attribute.data );
  38747. }
  38748. const attributeData = backend.get( attribute );
  38749. gl.deleteBuffer( attributeData.bufferGPU );
  38750. backend.delete( attribute );
  38751. }
  38752. async getArrayBufferAsync( attribute ) {
  38753. const backend = this.backend;
  38754. const { gl } = backend;
  38755. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38756. const { bufferGPU } = backend.get( bufferAttribute );
  38757. const array = attribute.array;
  38758. const byteLength = array.byteLength;
  38759. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38760. const writeBuffer = gl.createBuffer();
  38761. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38762. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38763. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38764. await backend.utils._clientWaitAsync();
  38765. const dstBuffer = new attribute.array.constructor( array.length );
  38766. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38767. gl.deleteBuffer( writeBuffer );
  38768. return dstBuffer.buffer;
  38769. }
  38770. _createBuffer( gl, bufferType, array, usage ) {
  38771. const bufferGPU = gl.createBuffer();
  38772. gl.bindBuffer( bufferType, bufferGPU );
  38773. gl.bufferData( bufferType, array, usage );
  38774. gl.bindBuffer( bufferType, null );
  38775. return bufferGPU;
  38776. }
  38777. }
  38778. let initialized$1 = false, equationToGL, factorToGL;
  38779. class WebGLState {
  38780. constructor( backend ) {
  38781. this.backend = backend;
  38782. this.gl = this.backend.gl;
  38783. this.enabled = {};
  38784. this.currentFlipSided = null;
  38785. this.currentCullFace = null;
  38786. this.currentProgram = null;
  38787. this.currentBlendingEnabled = false;
  38788. this.currentBlending = null;
  38789. this.currentBlendSrc = null;
  38790. this.currentBlendDst = null;
  38791. this.currentBlendSrcAlpha = null;
  38792. this.currentBlendDstAlpha = null;
  38793. this.currentPremultipledAlpha = null;
  38794. this.currentPolygonOffsetFactor = null;
  38795. this.currentPolygonOffsetUnits = null;
  38796. this.currentColorMask = null;
  38797. this.currentDepthFunc = null;
  38798. this.currentDepthMask = null;
  38799. this.currentStencilFunc = null;
  38800. this.currentStencilRef = null;
  38801. this.currentStencilFuncMask = null;
  38802. this.currentStencilFail = null;
  38803. this.currentStencilZFail = null;
  38804. this.currentStencilZPass = null;
  38805. this.currentStencilMask = null;
  38806. this.currentLineWidth = null;
  38807. this.currentBoundFramebuffers = {};
  38808. this.currentDrawbuffers = new WeakMap();
  38809. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38810. this.currentTextureSlot = null;
  38811. this.currentBoundTextures = {};
  38812. if ( initialized$1 === false ) {
  38813. this._init( this.gl );
  38814. initialized$1 = true;
  38815. }
  38816. }
  38817. _init( gl ) {
  38818. // Store only WebGL constants here.
  38819. equationToGL = {
  38820. [ AddEquation ]: gl.FUNC_ADD,
  38821. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38822. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38823. };
  38824. factorToGL = {
  38825. [ ZeroFactor ]: gl.ZERO,
  38826. [ OneFactor ]: gl.ONE,
  38827. [ SrcColorFactor ]: gl.SRC_COLOR,
  38828. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38829. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38830. [ DstColorFactor ]: gl.DST_COLOR,
  38831. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38832. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38833. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38834. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38835. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38836. };
  38837. }
  38838. enable( id ) {
  38839. const { enabled } = this;
  38840. if ( enabled[ id ] !== true ) {
  38841. this.gl.enable( id );
  38842. enabled[ id ] = true;
  38843. }
  38844. }
  38845. disable( id ) {
  38846. const { enabled } = this;
  38847. if ( enabled[ id ] !== false ) {
  38848. this.gl.disable( id );
  38849. enabled[ id ] = false;
  38850. }
  38851. }
  38852. setFlipSided( flipSided ) {
  38853. if ( this.currentFlipSided !== flipSided ) {
  38854. const { gl } = this;
  38855. if ( flipSided ) {
  38856. gl.frontFace( gl.CW );
  38857. } else {
  38858. gl.frontFace( gl.CCW );
  38859. }
  38860. this.currentFlipSided = flipSided;
  38861. }
  38862. }
  38863. setCullFace( cullFace ) {
  38864. const { gl } = this;
  38865. if ( cullFace !== CullFaceNone ) {
  38866. this.enable( gl.CULL_FACE );
  38867. if ( cullFace !== this.currentCullFace ) {
  38868. if ( cullFace === CullFaceBack ) {
  38869. gl.cullFace( gl.BACK );
  38870. } else if ( cullFace === CullFaceFront ) {
  38871. gl.cullFace( gl.FRONT );
  38872. } else {
  38873. gl.cullFace( gl.FRONT_AND_BACK );
  38874. }
  38875. }
  38876. } else {
  38877. this.disable( gl.CULL_FACE );
  38878. }
  38879. this.currentCullFace = cullFace;
  38880. }
  38881. setLineWidth( width ) {
  38882. const { currentLineWidth, gl } = this;
  38883. if ( width !== currentLineWidth ) {
  38884. gl.lineWidth( width );
  38885. this.currentLineWidth = width;
  38886. }
  38887. }
  38888. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  38889. const { gl } = this;
  38890. if ( blending === NoBlending ) {
  38891. if ( this.currentBlendingEnabled === true ) {
  38892. this.disable( gl.BLEND );
  38893. this.currentBlendingEnabled = false;
  38894. }
  38895. return;
  38896. }
  38897. if ( this.currentBlendingEnabled === false ) {
  38898. this.enable( gl.BLEND );
  38899. this.currentBlendingEnabled = true;
  38900. }
  38901. if ( blending !== CustomBlending ) {
  38902. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  38903. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  38904. gl.blendEquation( gl.FUNC_ADD );
  38905. this.currentBlendEquation = AddEquation;
  38906. this.currentBlendEquationAlpha = AddEquation;
  38907. }
  38908. if ( premultipliedAlpha ) {
  38909. switch ( blending ) {
  38910. case NormalBlending:
  38911. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38912. break;
  38913. case AdditiveBlending:
  38914. gl.blendFunc( gl.ONE, gl.ONE );
  38915. break;
  38916. case SubtractiveBlending:
  38917. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38918. break;
  38919. case MultiplyBlending:
  38920. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  38921. break;
  38922. default:
  38923. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38924. break;
  38925. }
  38926. } else {
  38927. switch ( blending ) {
  38928. case NormalBlending:
  38929. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38930. break;
  38931. case AdditiveBlending:
  38932. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  38933. break;
  38934. case SubtractiveBlending:
  38935. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38936. break;
  38937. case MultiplyBlending:
  38938. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  38939. break;
  38940. default:
  38941. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38942. break;
  38943. }
  38944. }
  38945. this.currentBlendSrc = null;
  38946. this.currentBlendDst = null;
  38947. this.currentBlendSrcAlpha = null;
  38948. this.currentBlendDstAlpha = null;
  38949. this.currentBlending = blending;
  38950. this.currentPremultipledAlpha = premultipliedAlpha;
  38951. }
  38952. return;
  38953. }
  38954. // custom blending
  38955. blendEquationAlpha = blendEquationAlpha || blendEquation;
  38956. blendSrcAlpha = blendSrcAlpha || blendSrc;
  38957. blendDstAlpha = blendDstAlpha || blendDst;
  38958. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  38959. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  38960. this.currentBlendEquation = blendEquation;
  38961. this.currentBlendEquationAlpha = blendEquationAlpha;
  38962. }
  38963. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  38964. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  38965. this.currentBlendSrc = blendSrc;
  38966. this.currentBlendDst = blendDst;
  38967. this.currentBlendSrcAlpha = blendSrcAlpha;
  38968. this.currentBlendDstAlpha = blendDstAlpha;
  38969. }
  38970. this.currentBlending = blending;
  38971. this.currentPremultipledAlpha = false;
  38972. }
  38973. setColorMask( colorMask ) {
  38974. if ( this.currentColorMask !== colorMask ) {
  38975. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38976. this.currentColorMask = colorMask;
  38977. }
  38978. }
  38979. setDepthTest( depthTest ) {
  38980. const { gl } = this;
  38981. if ( depthTest ) {
  38982. this.enable( gl.DEPTH_TEST );
  38983. } else {
  38984. this.disable( gl.DEPTH_TEST );
  38985. }
  38986. }
  38987. setDepthMask( depthMask ) {
  38988. if ( this.currentDepthMask !== depthMask ) {
  38989. this.gl.depthMask( depthMask );
  38990. this.currentDepthMask = depthMask;
  38991. }
  38992. }
  38993. setDepthFunc( depthFunc ) {
  38994. if ( this.currentDepthFunc !== depthFunc ) {
  38995. const { gl } = this;
  38996. switch ( depthFunc ) {
  38997. case NeverDepth:
  38998. gl.depthFunc( gl.NEVER );
  38999. break;
  39000. case AlwaysDepth:
  39001. gl.depthFunc( gl.ALWAYS );
  39002. break;
  39003. case LessDepth:
  39004. gl.depthFunc( gl.LESS );
  39005. break;
  39006. case LessEqualDepth:
  39007. gl.depthFunc( gl.LEQUAL );
  39008. break;
  39009. case EqualDepth:
  39010. gl.depthFunc( gl.EQUAL );
  39011. break;
  39012. case GreaterEqualDepth:
  39013. gl.depthFunc( gl.GEQUAL );
  39014. break;
  39015. case GreaterDepth:
  39016. gl.depthFunc( gl.GREATER );
  39017. break;
  39018. case NotEqualDepth:
  39019. gl.depthFunc( gl.NOTEQUAL );
  39020. break;
  39021. default:
  39022. gl.depthFunc( gl.LEQUAL );
  39023. }
  39024. this.currentDepthFunc = depthFunc;
  39025. }
  39026. }
  39027. setStencilTest( stencilTest ) {
  39028. const { gl } = this;
  39029. if ( stencilTest ) {
  39030. this.enable( gl.STENCIL_TEST );
  39031. } else {
  39032. this.disable( gl.STENCIL_TEST );
  39033. }
  39034. }
  39035. setStencilMask( stencilMask ) {
  39036. if ( this.currentStencilMask !== stencilMask ) {
  39037. this.gl.stencilMask( stencilMask );
  39038. this.currentStencilMask = stencilMask;
  39039. }
  39040. }
  39041. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39042. if ( this.currentStencilFunc !== stencilFunc ||
  39043. this.currentStencilRef !== stencilRef ||
  39044. this.currentStencilFuncMask !== stencilMask ) {
  39045. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39046. this.currentStencilFunc = stencilFunc;
  39047. this.currentStencilRef = stencilRef;
  39048. this.currentStencilFuncMask = stencilMask;
  39049. }
  39050. }
  39051. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39052. if ( this.currentStencilFail !== stencilFail ||
  39053. this.currentStencilZFail !== stencilZFail ||
  39054. this.currentStencilZPass !== stencilZPass ) {
  39055. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39056. this.currentStencilFail = stencilFail;
  39057. this.currentStencilZFail = stencilZFail;
  39058. this.currentStencilZPass = stencilZPass;
  39059. }
  39060. }
  39061. setMaterial( material, frontFaceCW ) {
  39062. const { gl } = this;
  39063. material.side === DoubleSide
  39064. ? this.disable( gl.CULL_FACE )
  39065. : this.enable( gl.CULL_FACE );
  39066. let flipSided = ( material.side === BackSide );
  39067. if ( frontFaceCW ) flipSided = ! flipSided;
  39068. this.setFlipSided( flipSided );
  39069. ( material.blending === NormalBlending && material.transparent === false )
  39070. ? this.setBlending( NoBlending )
  39071. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39072. this.setDepthFunc( material.depthFunc );
  39073. this.setDepthTest( material.depthTest );
  39074. this.setDepthMask( material.depthWrite );
  39075. this.setColorMask( material.colorWrite );
  39076. const stencilWrite = material.stencilWrite;
  39077. this.setStencilTest( stencilWrite );
  39078. if ( stencilWrite ) {
  39079. this.setStencilMask( material.stencilWriteMask );
  39080. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39081. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39082. }
  39083. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39084. material.alphaToCoverage === true
  39085. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39086. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39087. }
  39088. setPolygonOffset( polygonOffset, factor, units ) {
  39089. const { gl } = this;
  39090. if ( polygonOffset ) {
  39091. this.enable( gl.POLYGON_OFFSET_FILL );
  39092. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39093. gl.polygonOffset( factor, units );
  39094. this.currentPolygonOffsetFactor = factor;
  39095. this.currentPolygonOffsetUnits = units;
  39096. }
  39097. } else {
  39098. this.disable( gl.POLYGON_OFFSET_FILL );
  39099. }
  39100. }
  39101. useProgram( program ) {
  39102. if ( this.currentProgram !== program ) {
  39103. this.gl.useProgram( program );
  39104. this.currentProgram = program;
  39105. return true;
  39106. }
  39107. return false;
  39108. }
  39109. // framebuffer
  39110. bindFramebuffer( target, framebuffer ) {
  39111. const { gl, currentBoundFramebuffers } = this;
  39112. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39113. gl.bindFramebuffer( target, framebuffer );
  39114. currentBoundFramebuffers[ target ] = framebuffer;
  39115. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39116. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39117. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39118. }
  39119. if ( target === gl.FRAMEBUFFER ) {
  39120. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39121. }
  39122. return true;
  39123. }
  39124. return false;
  39125. }
  39126. drawBuffers( renderContext, framebuffer ) {
  39127. const { gl } = this;
  39128. let drawBuffers = [];
  39129. let needsUpdate = false;
  39130. if ( renderContext.textures !== null ) {
  39131. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39132. if ( drawBuffers === undefined ) {
  39133. drawBuffers = [];
  39134. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39135. }
  39136. const textures = renderContext.textures;
  39137. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39138. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39139. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39140. }
  39141. drawBuffers.length = textures.length;
  39142. needsUpdate = true;
  39143. }
  39144. } else {
  39145. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39146. drawBuffers[ 0 ] = gl.BACK;
  39147. needsUpdate = true;
  39148. }
  39149. }
  39150. if ( needsUpdate ) {
  39151. gl.drawBuffers( drawBuffers );
  39152. }
  39153. }
  39154. // texture
  39155. activeTexture( webglSlot ) {
  39156. const { gl, currentTextureSlot, maxTextures } = this;
  39157. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39158. if ( currentTextureSlot !== webglSlot ) {
  39159. gl.activeTexture( webglSlot );
  39160. this.currentTextureSlot = webglSlot;
  39161. }
  39162. }
  39163. bindTexture( webglType, webglTexture, webglSlot ) {
  39164. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39165. if ( webglSlot === undefined ) {
  39166. if ( currentTextureSlot === null ) {
  39167. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39168. } else {
  39169. webglSlot = currentTextureSlot;
  39170. }
  39171. }
  39172. let boundTexture = currentBoundTextures[ webglSlot ];
  39173. if ( boundTexture === undefined ) {
  39174. boundTexture = { type: undefined, texture: undefined };
  39175. currentBoundTextures[ webglSlot ] = boundTexture;
  39176. }
  39177. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39178. if ( currentTextureSlot !== webglSlot ) {
  39179. gl.activeTexture( webglSlot );
  39180. this.currentTextureSlot = webglSlot;
  39181. }
  39182. gl.bindTexture( webglType, webglTexture );
  39183. boundTexture.type = webglType;
  39184. boundTexture.texture = webglTexture;
  39185. }
  39186. }
  39187. unbindTexture() {
  39188. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39189. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39190. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39191. gl.bindTexture( boundTexture.type, null );
  39192. boundTexture.type = undefined;
  39193. boundTexture.texture = undefined;
  39194. }
  39195. }
  39196. }
  39197. class WebGLUtils {
  39198. constructor( backend ) {
  39199. this.backend = backend;
  39200. this.gl = this.backend.gl;
  39201. this.extensions = backend.extensions;
  39202. }
  39203. convert( p, colorSpace = NoColorSpace ) {
  39204. const { gl, extensions } = this;
  39205. let extension;
  39206. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39207. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39208. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39209. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39210. if ( p === ByteType ) return gl.BYTE;
  39211. if ( p === ShortType ) return gl.SHORT;
  39212. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39213. if ( p === IntType ) return gl.INT;
  39214. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39215. if ( p === FloatType ) return gl.FLOAT;
  39216. if ( p === HalfFloatType ) {
  39217. return gl.HALF_FLOAT;
  39218. }
  39219. if ( p === AlphaFormat ) return gl.ALPHA;
  39220. if ( p === RGBFormat ) return gl.RGB;
  39221. if ( p === RGBAFormat ) return gl.RGBA;
  39222. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39223. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39224. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39225. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39226. // WebGL2 formats.
  39227. if ( p === RedFormat ) return gl.RED;
  39228. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39229. if ( p === RGFormat ) return gl.RG;
  39230. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39231. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39232. // S3TC
  39233. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39234. if ( colorSpace === SRGBColorSpace ) {
  39235. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39236. if ( extension !== null ) {
  39237. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39238. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39239. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39240. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39241. } else {
  39242. return null;
  39243. }
  39244. } else {
  39245. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39246. if ( extension !== null ) {
  39247. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39248. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39249. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39250. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39251. } else {
  39252. return null;
  39253. }
  39254. }
  39255. }
  39256. // PVRTC
  39257. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39258. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39259. if ( extension !== null ) {
  39260. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39261. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39262. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39263. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39264. } else {
  39265. return null;
  39266. }
  39267. }
  39268. // ETC
  39269. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39270. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39271. if ( extension !== null ) {
  39272. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39273. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39274. } else {
  39275. return null;
  39276. }
  39277. }
  39278. // ASTC
  39279. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39280. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39281. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39282. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39283. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39284. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39285. if ( extension !== null ) {
  39286. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39287. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39288. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39289. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39290. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39291. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39292. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39293. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39294. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39295. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39296. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39297. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39298. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39299. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39300. } else {
  39301. return null;
  39302. }
  39303. }
  39304. // BPTC
  39305. if ( p === RGBA_BPTC_Format ) {
  39306. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39307. if ( extension !== null ) {
  39308. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39309. } else {
  39310. return null;
  39311. }
  39312. }
  39313. // RGTC
  39314. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39315. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39316. if ( extension !== null ) {
  39317. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39318. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39319. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39320. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39321. } else {
  39322. return null;
  39323. }
  39324. }
  39325. //
  39326. if ( p === UnsignedInt248Type ) {
  39327. return gl.UNSIGNED_INT_24_8;
  39328. }
  39329. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39330. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39331. }
  39332. _clientWaitAsync() {
  39333. const { gl } = this;
  39334. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39335. gl.flush();
  39336. return new Promise( ( resolve, reject ) => {
  39337. function test() {
  39338. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39339. if ( res === gl.WAIT_FAILED ) {
  39340. gl.deleteSync( sync );
  39341. reject();
  39342. return;
  39343. }
  39344. if ( res === gl.TIMEOUT_EXPIRED ) {
  39345. requestAnimationFrame( test );
  39346. return;
  39347. }
  39348. gl.deleteSync( sync );
  39349. resolve();
  39350. }
  39351. test();
  39352. } );
  39353. }
  39354. }
  39355. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39356. class WebGLTextureUtils {
  39357. constructor( backend ) {
  39358. this.backend = backend;
  39359. this.gl = backend.gl;
  39360. this.extensions = backend.extensions;
  39361. this.defaultTextures = {};
  39362. if ( initialized === false ) {
  39363. this._init( this.gl );
  39364. initialized = true;
  39365. }
  39366. }
  39367. _init( gl ) {
  39368. // Store only WebGL constants here.
  39369. wrappingToGL = {
  39370. [ RepeatWrapping ]: gl.REPEAT,
  39371. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39372. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39373. };
  39374. filterToGL = {
  39375. [ NearestFilter ]: gl.NEAREST,
  39376. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39377. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39378. [ LinearFilter ]: gl.LINEAR,
  39379. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39380. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39381. };
  39382. compareToGL = {
  39383. [ NeverCompare ]: gl.NEVER,
  39384. [ AlwaysCompare ]: gl.ALWAYS,
  39385. [ LessCompare ]: gl.LESS,
  39386. [ LessEqualCompare ]: gl.LEQUAL,
  39387. [ EqualCompare ]: gl.EQUAL,
  39388. [ GreaterEqualCompare ]: gl.GEQUAL,
  39389. [ GreaterCompare ]: gl.GREATER,
  39390. [ NotEqualCompare ]: gl.NOTEQUAL
  39391. };
  39392. }
  39393. filterFallback( f ) {
  39394. const { gl } = this;
  39395. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  39396. return gl.NEAREST;
  39397. }
  39398. return gl.LINEAR;
  39399. }
  39400. getGLTextureType( texture ) {
  39401. const { gl } = this;
  39402. let glTextureType;
  39403. if ( texture.isCubeTexture === true ) {
  39404. glTextureType = gl.TEXTURE_CUBE_MAP;
  39405. } else if ( texture.isDataArrayTexture === true ) {
  39406. glTextureType = gl.TEXTURE_2D_ARRAY;
  39407. } else if ( texture.isData3DTexture === true ) {
  39408. glTextureType = gl.TEXTURE_3D;
  39409. } else {
  39410. glTextureType = gl.TEXTURE_2D;
  39411. }
  39412. return glTextureType;
  39413. }
  39414. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39415. const { gl, extensions } = this;
  39416. if ( internalFormatName !== null ) {
  39417. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39418. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39419. }
  39420. let internalFormat = glFormat;
  39421. if ( glFormat === gl.RED ) {
  39422. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39423. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39424. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39425. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39426. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39427. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39428. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39429. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39430. }
  39431. if ( glFormat === gl.RED_INTEGER ) {
  39432. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39433. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39434. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39435. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39436. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39437. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39438. }
  39439. if ( glFormat === gl.RG ) {
  39440. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39441. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39442. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39443. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39444. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39445. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39446. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39447. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39448. }
  39449. if ( glFormat === gl.RG_INTEGER ) {
  39450. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39451. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39452. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39453. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39454. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39455. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39456. }
  39457. if ( glFormat === gl.RGB ) {
  39458. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39459. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39460. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39461. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39462. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39463. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39464. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39465. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39466. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39467. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39468. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39469. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39470. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39471. }
  39472. if ( glFormat === gl.RGB_INTEGER ) {
  39473. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39474. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39475. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39476. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39477. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39478. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39479. }
  39480. if ( glFormat === gl.RGBA ) {
  39481. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39482. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39483. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39484. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39485. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39486. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39487. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39488. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39489. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39490. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39491. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39492. }
  39493. if ( glFormat === gl.RGBA_INTEGER ) {
  39494. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39495. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39496. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39497. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39498. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39499. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39500. }
  39501. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39502. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39503. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39504. }
  39505. if ( glFormat === gl.DEPTH_STENCIL ) {
  39506. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39507. }
  39508. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39509. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39510. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39511. extensions.get( 'EXT_color_buffer_float' );
  39512. }
  39513. return internalFormat;
  39514. }
  39515. setTextureParameters( textureType, texture ) {
  39516. const { gl, extensions, backend } = this;
  39517. const { currentAnisotropy } = backend.get( texture );
  39518. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39519. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39520. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39521. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39522. }
  39523. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39524. // follow WebGPU backend mapping for texture filtering
  39525. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  39526. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39527. if ( texture.compareFunction ) {
  39528. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39529. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39530. }
  39531. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39532. if ( texture.magFilter === NearestFilter ) return;
  39533. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39534. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39535. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  39536. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39537. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39538. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  39539. }
  39540. }
  39541. }
  39542. createDefaultTexture( texture ) {
  39543. const { gl, backend, defaultTextures } = this;
  39544. const glTextureType = this.getGLTextureType( texture );
  39545. let textureGPU = defaultTextures[ glTextureType ];
  39546. if ( textureGPU === undefined ) {
  39547. textureGPU = gl.createTexture();
  39548. backend.state.bindTexture( glTextureType, textureGPU );
  39549. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39550. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39551. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39552. defaultTextures[ glTextureType ] = textureGPU;
  39553. }
  39554. backend.set( texture, {
  39555. textureGPU,
  39556. glTextureType,
  39557. isDefault: true
  39558. } );
  39559. }
  39560. createTexture( texture, options ) {
  39561. const { gl, backend } = this;
  39562. const { levels, width, height, depth } = options;
  39563. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39564. const glType = backend.utils.convert( texture.type );
  39565. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39566. const textureGPU = gl.createTexture();
  39567. const glTextureType = this.getGLTextureType( texture );
  39568. backend.state.bindTexture( glTextureType, textureGPU );
  39569. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39570. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39571. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39572. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39573. this.setTextureParameters( glTextureType, texture );
  39574. if ( texture.isDataArrayTexture ) {
  39575. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39576. } else if ( texture.isData3DTexture ) {
  39577. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39578. } else if ( ! texture.isVideoTexture ) {
  39579. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39580. }
  39581. backend.set( texture, {
  39582. textureGPU,
  39583. glTextureType,
  39584. glFormat,
  39585. glType,
  39586. glInternalFormat
  39587. } );
  39588. }
  39589. copyBufferToTexture( buffer, texture ) {
  39590. const { gl, backend } = this;
  39591. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39592. const { width, height } = texture.source.data;
  39593. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39594. backend.state.bindTexture( glTextureType, textureGPU );
  39595. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39596. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39597. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39598. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39599. backend.state.unbindTexture();
  39600. // debug
  39601. // const framebuffer = gl.createFramebuffer();
  39602. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39603. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39604. // const readout = new Float32Array( width * height * 4 );
  39605. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39606. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39607. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39608. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39609. // console.log( readout );
  39610. }
  39611. updateTexture( texture, options ) {
  39612. const { gl } = this;
  39613. const { width, height } = options;
  39614. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39615. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39616. return;
  39617. const getImage = ( source ) => {
  39618. if ( source.isDataTexture ) {
  39619. return source.image.data;
  39620. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  39621. return source;
  39622. }
  39623. return source.data;
  39624. };
  39625. this.backend.state.bindTexture( glTextureType, textureGPU );
  39626. if ( texture.isCompressedTexture ) {
  39627. const mipmaps = texture.mipmaps;
  39628. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39629. const mipmap = mipmaps[ i ];
  39630. if ( texture.isCompressedArrayTexture ) {
  39631. const image = options.image;
  39632. if ( texture.format !== gl.RGBA ) {
  39633. if ( glFormat !== null ) {
  39634. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  39635. } else {
  39636. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39637. }
  39638. } else {
  39639. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39640. }
  39641. } else {
  39642. if ( glFormat !== null ) {
  39643. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39644. } else {
  39645. console.warn( 'Unsupported compressed texture format' );
  39646. }
  39647. }
  39648. }
  39649. } else if ( texture.isCubeTexture ) {
  39650. const images = options.images;
  39651. for ( let i = 0; i < 6; i ++ ) {
  39652. const image = getImage( images[ i ] );
  39653. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39654. }
  39655. } else if ( texture.isDataArrayTexture ) {
  39656. const image = options.image;
  39657. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39658. } else if ( texture.isData3DTexture ) {
  39659. const image = options.image;
  39660. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39661. } else if ( texture.isVideoTexture ) {
  39662. texture.update();
  39663. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39664. } else {
  39665. const image = getImage( options.image );
  39666. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39667. }
  39668. }
  39669. generateMipmaps( texture ) {
  39670. const { gl, backend } = this;
  39671. const { textureGPU, glTextureType } = backend.get( texture );
  39672. backend.state.bindTexture( glTextureType, textureGPU );
  39673. gl.generateMipmap( glTextureType );
  39674. }
  39675. deallocateRenderBuffers( renderTarget ) {
  39676. const { gl, backend } = this;
  39677. // remove framebuffer reference
  39678. if ( renderTarget ) {
  39679. const renderContextData = backend.get( renderTarget );
  39680. renderContextData.renderBufferStorageSetup = undefined;
  39681. if ( renderContextData.framebuffer ) {
  39682. gl.deleteFramebuffer( renderContextData.framebuffer );
  39683. renderContextData.framebuffer = undefined;
  39684. }
  39685. if ( renderContextData.depthRenderbuffer ) {
  39686. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39687. renderContextData.depthRenderbuffer = undefined;
  39688. }
  39689. if ( renderContextData.stencilRenderbuffer ) {
  39690. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39691. renderContextData.stencilRenderbuffer = undefined;
  39692. }
  39693. if ( renderContextData.msaaFrameBuffer ) {
  39694. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39695. renderContextData.msaaFrameBuffer = undefined;
  39696. }
  39697. if ( renderContextData.msaaRenderbuffers ) {
  39698. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39699. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39700. }
  39701. renderContextData.msaaRenderbuffers = undefined;
  39702. }
  39703. }
  39704. }
  39705. destroyTexture( texture ) {
  39706. const { gl, backend } = this;
  39707. const { textureGPU, renderTarget } = backend.get( texture );
  39708. this.deallocateRenderBuffers( renderTarget );
  39709. gl.deleteTexture( textureGPU );
  39710. backend.delete( texture );
  39711. }
  39712. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39713. const { gl, backend } = this;
  39714. const { state } = this.backend;
  39715. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  39716. let width, height, minX, minY;
  39717. let dstX, dstY;
  39718. if ( srcRegion !== null ) {
  39719. width = srcRegion.max.x - srcRegion.min.x;
  39720. height = srcRegion.max.y - srcRegion.min.y;
  39721. minX = srcRegion.min.x;
  39722. minY = srcRegion.min.y;
  39723. } else {
  39724. width = srcTexture.image.width;
  39725. height = srcTexture.image.height;
  39726. minX = 0;
  39727. minY = 0;
  39728. }
  39729. if ( dstPosition !== null ) {
  39730. dstX = dstPosition.x;
  39731. dstY = dstPosition.y;
  39732. } else {
  39733. dstX = 0;
  39734. dstY = 0;
  39735. }
  39736. state.bindTexture( glTextureType, dstTextureGPU );
  39737. // As another texture upload may have changed pixelStorei
  39738. // parameters, make sure they are correct for the dstTexture
  39739. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39740. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  39741. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  39742. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39743. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  39744. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  39745. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  39746. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  39747. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  39748. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  39749. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  39750. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  39751. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  39752. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  39753. if ( srcTexture.isDataTexture ) {
  39754. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  39755. } else {
  39756. if ( srcTexture.isCompressedTexture ) {
  39757. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  39758. } else {
  39759. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  39760. }
  39761. }
  39762. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  39763. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  39764. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  39765. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  39766. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  39767. // Generate mipmaps only when copying level 0
  39768. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  39769. state.unbindTexture();
  39770. }
  39771. copyFramebufferToTexture( texture, renderContext ) {
  39772. const { gl } = this;
  39773. const { state } = this.backend;
  39774. const { textureGPU } = this.backend.get( texture );
  39775. const width = texture.image.width;
  39776. const height = texture.image.height;
  39777. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  39778. if ( requireDrawFrameBuffer ) {
  39779. let mask;
  39780. let attachment;
  39781. if ( texture.isDepthTexture === true ) {
  39782. mask = gl.DEPTH_BUFFER_BIT;
  39783. attachment = gl.DEPTH_ATTACHMENT;
  39784. if ( renderContext.stencil ) {
  39785. mask |= gl.STENCIL_BUFFER_BIT;
  39786. }
  39787. } else {
  39788. mask = gl.COLOR_BUFFER_BIT;
  39789. attachment = gl.COLOR_ATTACHMENT0;
  39790. }
  39791. const fb = gl.createFramebuffer();
  39792. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39793. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  39794. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  39795. gl.deleteFramebuffer( fb );
  39796. } else {
  39797. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39798. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  39799. state.unbindTexture();
  39800. }
  39801. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  39802. this.backend._setFramebuffer( renderContext );
  39803. }
  39804. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  39805. setupRenderBufferStorage( renderbuffer, renderContext ) {
  39806. const { gl } = this;
  39807. const renderTarget = renderContext.renderTarget;
  39808. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  39809. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  39810. if ( depthBuffer && ! stencilBuffer ) {
  39811. let glInternalFormat = gl.DEPTH_COMPONENT24;
  39812. if ( samples > 0 ) {
  39813. if ( depthTexture && depthTexture.isDepthTexture ) {
  39814. if ( depthTexture.type === gl.FLOAT ) {
  39815. glInternalFormat = gl.DEPTH_COMPONENT32F;
  39816. }
  39817. }
  39818. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  39819. } else {
  39820. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  39821. }
  39822. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39823. } else if ( depthBuffer && stencilBuffer ) {
  39824. if ( samples > 0 ) {
  39825. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  39826. } else {
  39827. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  39828. }
  39829. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39830. }
  39831. }
  39832. async copyTextureToBuffer( texture, x, y, width, height ) {
  39833. const { backend, gl } = this;
  39834. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  39835. const fb = gl.createFramebuffer();
  39836. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39837. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  39838. const typedArrayType = this._getTypedArrayType( glType );
  39839. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  39840. const elementCount = width * height;
  39841. const byteLength = elementCount * bytesPerTexel;
  39842. const buffer = gl.createBuffer();
  39843. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39844. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  39845. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  39846. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39847. await backend.utils._clientWaitAsync();
  39848. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  39849. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39850. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  39851. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39852. gl.deleteFramebuffer( fb );
  39853. return dstBuffer;
  39854. }
  39855. _getTypedArrayType( glType ) {
  39856. const { gl } = this;
  39857. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  39858. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  39859. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  39860. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  39861. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  39862. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  39863. if ( glType === gl.FLOAT ) return Float32Array;
  39864. throw new Error( `Unsupported WebGL type: ${glType}` );
  39865. }
  39866. _getBytesPerTexel( glFormat ) {
  39867. const { gl } = this;
  39868. if ( glFormat === gl.RGBA ) return 4;
  39869. if ( glFormat === gl.RGB ) return 3;
  39870. if ( glFormat === gl.ALPHA ) return 1;
  39871. }
  39872. }
  39873. class WebGLExtensions {
  39874. constructor( backend ) {
  39875. this.backend = backend;
  39876. this.gl = this.backend.gl;
  39877. this.availableExtensions = this.gl.getSupportedExtensions();
  39878. this.extensions = {};
  39879. }
  39880. get( name ) {
  39881. let extension = this.extensions[ name ];
  39882. if ( extension === undefined ) {
  39883. extension = this.gl.getExtension( name );
  39884. this.extensions[ name ] = extension;
  39885. }
  39886. return extension;
  39887. }
  39888. has( name ) {
  39889. return this.availableExtensions.includes( name );
  39890. }
  39891. }
  39892. class WebGLCapabilities {
  39893. constructor( backend ) {
  39894. this.backend = backend;
  39895. this.maxAnisotropy = null;
  39896. }
  39897. getMaxAnisotropy() {
  39898. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  39899. const gl = this.backend.gl;
  39900. const extensions = this.backend.extensions;
  39901. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39902. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39903. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  39904. } else {
  39905. this.maxAnisotropy = 0;
  39906. }
  39907. return this.maxAnisotropy;
  39908. }
  39909. }
  39910. const GLFeatureName = {
  39911. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  39912. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  39913. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  39914. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  39915. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39916. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39917. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  39918. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  39919. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  39920. };
  39921. class WebGLBufferRenderer {
  39922. constructor( backend ) {
  39923. this.gl = backend.gl;
  39924. this.extensions = backend.extensions;
  39925. this.info = backend.renderer.info;
  39926. this.mode = null;
  39927. this.index = 0;
  39928. this.type = null;
  39929. this.object = null;
  39930. }
  39931. render( start, count ) {
  39932. const { gl, mode, object, type, info, index } = this;
  39933. if ( index !== 0 ) {
  39934. gl.drawElements( mode, count, type, start );
  39935. } else {
  39936. gl.drawArrays( mode, start, count );
  39937. }
  39938. info.update( object, count, mode, 1 );
  39939. }
  39940. renderInstances( start, count, primcount ) {
  39941. const { gl, mode, type, index, object, info } = this;
  39942. if ( primcount === 0 ) return;
  39943. if ( index !== 0 ) {
  39944. gl.drawElementsInstanced( mode, count, type, start, primcount );
  39945. } else {
  39946. gl.drawArraysInstanced( mode, start, count, primcount );
  39947. }
  39948. info.update( object, count, mode, primcount );
  39949. }
  39950. renderMultiDraw( starts, counts, drawCount ) {
  39951. const { extensions, mode, object, info } = this;
  39952. if ( drawCount === 0 ) return;
  39953. const extension = extensions.get( 'WEBGL_multi_draw' );
  39954. if ( extension === null ) {
  39955. for ( let i = 0; i < drawCount; i ++ ) {
  39956. this.render( starts[ i ], counts[ i ] );
  39957. }
  39958. } else {
  39959. if ( this.index !== 0 ) {
  39960. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  39961. } else {
  39962. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  39963. }
  39964. let elementCount = 0;
  39965. for ( let i = 0; i < drawCount; i ++ ) {
  39966. elementCount += counts[ i ];
  39967. }
  39968. info.update( object, elementCount, mode, 1 );
  39969. }
  39970. }
  39971. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  39972. const { extensions, mode, object, info } = this;
  39973. if ( drawCount === 0 ) return;
  39974. const extension = extensions.get( 'WEBGL_multi_draw' );
  39975. if ( extension === null ) {
  39976. for ( let i = 0; i < drawCount; i ++ ) {
  39977. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  39978. }
  39979. } else {
  39980. if ( this.index !== 0 ) {
  39981. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  39982. } else {
  39983. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  39984. }
  39985. let elementCount = 0;
  39986. for ( let i = 0; i < drawCount; i ++ ) {
  39987. elementCount += counts[ i ];
  39988. }
  39989. for ( let i = 0; i < primcount.length; i ++ ) {
  39990. info.update( object, elementCount, mode, primcount[ i ] );
  39991. }
  39992. }
  39993. }
  39994. //
  39995. }
  39996. //
  39997. class WebGLBackend extends Backend {
  39998. constructor( parameters = {} ) {
  39999. super( parameters );
  40000. this.isWebGLBackend = true;
  40001. }
  40002. init( renderer ) {
  40003. super.init( renderer );
  40004. //
  40005. const parameters = this.parameters;
  40006. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40007. this.gl = glContext;
  40008. this.extensions = new WebGLExtensions( this );
  40009. this.capabilities = new WebGLCapabilities( this );
  40010. this.attributeUtils = new WebGLAttributeUtils( this );
  40011. this.textureUtils = new WebGLTextureUtils( this );
  40012. this.bufferRenderer = new WebGLBufferRenderer( this );
  40013. this.state = new WebGLState( this );
  40014. this.utils = new WebGLUtils( this );
  40015. this.vaoCache = {};
  40016. this.transformFeedbackCache = {};
  40017. this.discard = false;
  40018. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40019. this.extensions.get( 'EXT_color_buffer_float' );
  40020. this.extensions.get( 'WEBGL_multi_draw' );
  40021. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40022. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40023. this._currentContext = null;
  40024. }
  40025. get coordinateSystem() {
  40026. return WebGLCoordinateSystem;
  40027. }
  40028. async getArrayBufferAsync( attribute ) {
  40029. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40030. }
  40031. initTimestampQuery( renderContext ) {
  40032. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40033. const renderContextData = this.get( renderContext );
  40034. if ( this.queryRunning ) {
  40035. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40036. renderContextData.queryQueue.push( renderContext );
  40037. return;
  40038. }
  40039. if ( renderContextData.activeQuery ) {
  40040. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40041. renderContextData.activeQuery = null;
  40042. }
  40043. renderContextData.activeQuery = this.gl.createQuery();
  40044. if ( renderContextData.activeQuery !== null ) {
  40045. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40046. this.queryRunning = true;
  40047. }
  40048. }
  40049. // timestamp utils
  40050. prepareTimestampBuffer( renderContext ) {
  40051. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40052. const renderContextData = this.get( renderContext );
  40053. if ( renderContextData.activeQuery ) {
  40054. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40055. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40056. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40057. renderContextData.activeQuery = null;
  40058. this.queryRunning = false;
  40059. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40060. const nextRenderContext = renderContextData.queryQueue.shift();
  40061. this.initTimestampQuery( nextRenderContext );
  40062. }
  40063. }
  40064. }
  40065. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40066. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40067. const renderContextData = this.get( renderContext );
  40068. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40069. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40070. const queryInfo = renderContextData.gpuQueries[ i ];
  40071. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40072. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40073. if ( available && ! disjoint ) {
  40074. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40075. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40076. this.gl.deleteQuery( queryInfo.query );
  40077. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40078. i --;
  40079. this.renderer.info.updateTimestamp( type, duration );
  40080. }
  40081. }
  40082. }
  40083. getContext() {
  40084. return this.gl;
  40085. }
  40086. beginRender( renderContext ) {
  40087. const { gl } = this;
  40088. const renderContextData = this.get( renderContext );
  40089. //
  40090. //
  40091. this.initTimestampQuery( renderContext );
  40092. renderContextData.previousContext = this._currentContext;
  40093. this._currentContext = renderContext;
  40094. this._setFramebuffer( renderContext );
  40095. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40096. //
  40097. if ( renderContext.viewport ) {
  40098. this.updateViewport( renderContext );
  40099. } else {
  40100. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40101. }
  40102. if ( renderContext.scissor ) {
  40103. const { x, y, width, height } = renderContext.scissorValue;
  40104. gl.scissor( x, y, width, height );
  40105. }
  40106. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40107. if ( occlusionQueryCount > 0 ) {
  40108. // Get a reference to the array of objects with queries. The renderContextData property
  40109. // can be changed by another render pass before the async reading of all previous queries complete
  40110. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40111. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40112. renderContextData.lastOcclusionObject = null;
  40113. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40114. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40115. renderContextData.occlusionQueryIndex = 0;
  40116. }
  40117. }
  40118. finishRender( renderContext ) {
  40119. const { gl, state } = this;
  40120. const renderContextData = this.get( renderContext );
  40121. const previousContext = renderContextData.previousContext;
  40122. const textures = renderContext.textures;
  40123. if ( textures !== null ) {
  40124. for ( let i = 0; i < textures.length; i ++ ) {
  40125. const texture = textures[ i ];
  40126. if ( texture.generateMipmaps ) {
  40127. this.generateMipmaps( texture );
  40128. }
  40129. }
  40130. }
  40131. this._currentContext = previousContext;
  40132. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40133. const renderTargetContextData = this.get( renderContext.renderTarget );
  40134. const { samples } = renderContext.renderTarget;
  40135. const fb = renderTargetContextData.framebuffer;
  40136. const mask = gl.COLOR_BUFFER_BIT;
  40137. if ( samples > 0 ) {
  40138. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40139. const textures = renderContext.textures;
  40140. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40141. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40142. for ( let i = 0; i < textures.length; i ++ ) {
  40143. // TODO Add support for MRT
  40144. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40145. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40146. }
  40147. }
  40148. }
  40149. if ( previousContext !== null ) {
  40150. this._setFramebuffer( previousContext );
  40151. if ( previousContext.viewport ) {
  40152. this.updateViewport( previousContext );
  40153. } else {
  40154. const gl = this.gl;
  40155. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40156. }
  40157. }
  40158. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40159. if ( occlusionQueryCount > 0 ) {
  40160. const renderContextData = this.get( renderContext );
  40161. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40162. const { gl } = this;
  40163. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40164. }
  40165. this.resolveOccludedAsync( renderContext );
  40166. }
  40167. this.prepareTimestampBuffer( renderContext );
  40168. }
  40169. resolveOccludedAsync( renderContext ) {
  40170. const renderContextData = this.get( renderContext );
  40171. // handle occlusion query results
  40172. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40173. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40174. const occluded = new WeakSet();
  40175. const { gl } = this;
  40176. renderContextData.currentOcclusionQueryObjects = null;
  40177. renderContextData.currentOcclusionQueries = null;
  40178. const check = () => {
  40179. let completed = 0;
  40180. // check all queries and requeue as appropriate
  40181. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40182. const query = currentOcclusionQueries[ i ];
  40183. if ( query === null ) continue;
  40184. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40185. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40186. currentOcclusionQueries[ i ] = null;
  40187. gl.deleteQuery( query );
  40188. completed ++;
  40189. }
  40190. }
  40191. if ( completed < currentOcclusionQueries.length ) {
  40192. requestAnimationFrame( check );
  40193. } else {
  40194. renderContextData.occluded = occluded;
  40195. }
  40196. };
  40197. check();
  40198. }
  40199. }
  40200. isOccluded( renderContext, object ) {
  40201. const renderContextData = this.get( renderContext );
  40202. return renderContextData.occluded && renderContextData.occluded.has( object );
  40203. }
  40204. updateViewport( renderContext ) {
  40205. const gl = this.gl;
  40206. const { x, y, width, height } = renderContext.viewportValue;
  40207. gl.viewport( x, y, width, height );
  40208. }
  40209. setScissorTest( boolean ) {
  40210. const gl = this.gl;
  40211. if ( boolean ) {
  40212. gl.enable( gl.SCISSOR_TEST );
  40213. } else {
  40214. gl.disable( gl.SCISSOR_TEST );
  40215. }
  40216. }
  40217. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40218. const { gl } = this;
  40219. if ( descriptor === null ) {
  40220. descriptor = {
  40221. textures: null,
  40222. clearColorValue: this.getClearColor()
  40223. };
  40224. }
  40225. //
  40226. let clear = 0;
  40227. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40228. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40229. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40230. if ( clear !== 0 ) {
  40231. const clearColor = descriptor.clearColorValue || this.getClearColor();
  40232. if ( depth ) this.state.setDepthMask( true );
  40233. if ( descriptor.textures === null ) {
  40234. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40235. gl.clear( clear );
  40236. } else {
  40237. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40238. if ( color ) {
  40239. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40240. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40241. }
  40242. }
  40243. if ( depth && stencil ) {
  40244. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40245. } else if ( depth ) {
  40246. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40247. } else if ( stencil ) {
  40248. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40249. }
  40250. }
  40251. }
  40252. }
  40253. beginCompute( computeGroup ) {
  40254. const gl = this.gl;
  40255. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40256. this.initTimestampQuery( computeGroup );
  40257. }
  40258. compute( computeGroup, computeNode, bindings, pipeline ) {
  40259. const gl = this.gl;
  40260. if ( ! this.discard ) {
  40261. // required here to handle async behaviour of render.compute()
  40262. gl.enable( gl.RASTERIZER_DISCARD );
  40263. this.discard = true;
  40264. }
  40265. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40266. const vaoKey = this._getVaoKey( null, attributes );
  40267. const vaoGPU = this.vaoCache[ vaoKey ];
  40268. if ( vaoGPU === undefined ) {
  40269. this._createVao( null, attributes );
  40270. } else {
  40271. gl.bindVertexArray( vaoGPU );
  40272. }
  40273. gl.useProgram( programGPU );
  40274. this._bindUniforms( bindings );
  40275. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40276. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40277. gl.beginTransformFeedback( gl.POINTS );
  40278. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40279. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40280. } else {
  40281. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40282. }
  40283. gl.endTransformFeedback();
  40284. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40285. // switch active buffers
  40286. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40287. const dualAttributeData = transformBuffers[ i ];
  40288. if ( dualAttributeData.pbo ) {
  40289. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40290. }
  40291. dualAttributeData.switchBuffers();
  40292. }
  40293. }
  40294. finishCompute( computeGroup ) {
  40295. const gl = this.gl;
  40296. this.discard = false;
  40297. gl.disable( gl.RASTERIZER_DISCARD );
  40298. this.prepareTimestampBuffer( computeGroup );
  40299. }
  40300. draw( renderObject/*, info*/ ) {
  40301. const { object, pipeline, material, context } = renderObject;
  40302. const { programGPU } = this.get( pipeline );
  40303. const { gl, state } = this;
  40304. const contextData = this.get( context );
  40305. //
  40306. this._bindUniforms( renderObject.getBindings() );
  40307. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40308. state.setMaterial( material, frontFaceCW );
  40309. gl.useProgram( programGPU );
  40310. //
  40311. let vaoGPU = renderObject.staticVao;
  40312. if ( vaoGPU === undefined ) {
  40313. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40314. vaoGPU = this.vaoCache[ vaoKey ];
  40315. if ( vaoGPU === undefined ) {
  40316. let staticVao;
  40317. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40318. if ( staticVao ) renderObject.staticVao = vaoGPU;
  40319. }
  40320. }
  40321. gl.bindVertexArray( vaoGPU );
  40322. //
  40323. const index = renderObject.getIndex();
  40324. const geometry = renderObject.geometry;
  40325. const drawRange = renderObject.drawRange;
  40326. const firstVertex = drawRange.start;
  40327. //
  40328. const lastObject = contextData.lastOcclusionObject;
  40329. if ( lastObject !== object && lastObject !== undefined ) {
  40330. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40331. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40332. contextData.occlusionQueryIndex ++;
  40333. }
  40334. if ( object.occlusionTest === true ) {
  40335. const query = gl.createQuery();
  40336. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40337. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40338. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40339. }
  40340. contextData.lastOcclusionObject = object;
  40341. }
  40342. //
  40343. const renderer = this.bufferRenderer;
  40344. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40345. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40346. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40347. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40348. else {
  40349. if ( material.wireframe === true ) {
  40350. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40351. renderer.mode = gl.LINES;
  40352. } else {
  40353. renderer.mode = gl.TRIANGLES;
  40354. }
  40355. }
  40356. //
  40357. let count;
  40358. renderer.object = object;
  40359. if ( index !== null ) {
  40360. const indexData = this.get( index );
  40361. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  40362. renderer.index = index.count;
  40363. renderer.type = indexData.type;
  40364. count = indexCount;
  40365. } else {
  40366. renderer.index = 0;
  40367. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  40368. count = vertexCount;
  40369. }
  40370. const instanceCount = this.getInstanceCount( renderObject );
  40371. if ( object.isBatchedMesh ) {
  40372. if ( object._multiDrawInstances !== null ) {
  40373. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  40374. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  40375. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  40376. } else {
  40377. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  40378. }
  40379. } else if ( instanceCount > 1 ) {
  40380. renderer.renderInstances( firstVertex, count, instanceCount );
  40381. } else {
  40382. renderer.render( firstVertex, count );
  40383. }
  40384. //
  40385. gl.bindVertexArray( null );
  40386. }
  40387. needsRenderUpdate( /*renderObject*/ ) {
  40388. return false;
  40389. }
  40390. getRenderCacheKey( renderObject ) {
  40391. return renderObject.id;
  40392. }
  40393. // textures
  40394. createDefaultTexture( texture ) {
  40395. this.textureUtils.createDefaultTexture( texture );
  40396. }
  40397. createTexture( texture, options ) {
  40398. this.textureUtils.createTexture( texture, options );
  40399. }
  40400. updateTexture( texture, options ) {
  40401. this.textureUtils.updateTexture( texture, options );
  40402. }
  40403. generateMipmaps( texture ) {
  40404. this.textureUtils.generateMipmaps( texture );
  40405. }
  40406. destroyTexture( texture ) {
  40407. this.textureUtils.destroyTexture( texture );
  40408. }
  40409. copyTextureToBuffer( texture, x, y, width, height ) {
  40410. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  40411. }
  40412. createSampler( /*texture*/ ) {
  40413. //console.warn( 'Abstract class.' );
  40414. }
  40415. destroySampler() {}
  40416. // node builder
  40417. createNodeBuilder( object, renderer ) {
  40418. return new GLSLNodeBuilder( object, renderer );
  40419. }
  40420. // program
  40421. createProgram( program ) {
  40422. const gl = this.gl;
  40423. const { stage, code } = program;
  40424. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  40425. gl.shaderSource( shader, code );
  40426. gl.compileShader( shader );
  40427. this.set( program, {
  40428. shaderGPU: shader
  40429. } );
  40430. }
  40431. destroyProgram( /*program*/ ) {
  40432. console.warn( 'Abstract class.' );
  40433. }
  40434. createRenderPipeline( renderObject, promises ) {
  40435. const gl = this.gl;
  40436. const pipeline = renderObject.pipeline;
  40437. // Program
  40438. const { fragmentProgram, vertexProgram } = pipeline;
  40439. const programGPU = gl.createProgram();
  40440. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40441. const vertexShader = this.get( vertexProgram ).shaderGPU;
  40442. gl.attachShader( programGPU, fragmentShader );
  40443. gl.attachShader( programGPU, vertexShader );
  40444. gl.linkProgram( programGPU );
  40445. this.set( pipeline, {
  40446. programGPU,
  40447. fragmentShader,
  40448. vertexShader
  40449. } );
  40450. if ( promises !== null && this.parallel ) {
  40451. const p = new Promise( ( resolve /*, reject*/ ) => {
  40452. const parallel = this.parallel;
  40453. const checkStatus = () => {
  40454. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  40455. this._completeCompile( renderObject, pipeline );
  40456. resolve();
  40457. } else {
  40458. requestAnimationFrame( checkStatus );
  40459. }
  40460. };
  40461. checkStatus();
  40462. } );
  40463. promises.push( p );
  40464. return;
  40465. }
  40466. this._completeCompile( renderObject, pipeline );
  40467. }
  40468. _handleSource( string, errorLine ) {
  40469. const lines = string.split( '\n' );
  40470. const lines2 = [];
  40471. const from = Math.max( errorLine - 6, 0 );
  40472. const to = Math.min( errorLine + 6, lines.length );
  40473. for ( let i = from; i < to; i ++ ) {
  40474. const line = i + 1;
  40475. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  40476. }
  40477. return lines2.join( '\n' );
  40478. }
  40479. _getShaderErrors( gl, shader, type ) {
  40480. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  40481. const errors = gl.getShaderInfoLog( shader ).trim();
  40482. if ( status && errors === '' ) return '';
  40483. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  40484. if ( errorMatches ) {
  40485. const errorLine = parseInt( errorMatches[ 1 ] );
  40486. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  40487. } else {
  40488. return errors;
  40489. }
  40490. }
  40491. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  40492. if ( this.renderer.debug.checkShaderErrors ) {
  40493. const gl = this.gl;
  40494. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  40495. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40496. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  40497. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  40498. } else {
  40499. // default error reporting
  40500. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  40501. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  40502. console.error(
  40503. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  40504. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  40505. 'Program Info Log: ' + programLog + '\n' +
  40506. vertexErrors + '\n' +
  40507. fragmentErrors
  40508. );
  40509. }
  40510. } else if ( programLog !== '' ) {
  40511. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  40512. }
  40513. }
  40514. }
  40515. _completeCompile( renderObject, pipeline ) {
  40516. const gl = this.gl;
  40517. const pipelineData = this.get( pipeline );
  40518. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  40519. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40520. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40521. }
  40522. gl.useProgram( programGPU );
  40523. // Bindings
  40524. const bindings = renderObject.getBindings();
  40525. this._setupBindings( bindings, programGPU );
  40526. //
  40527. this.set( pipeline, {
  40528. programGPU
  40529. } );
  40530. }
  40531. createComputePipeline( computePipeline, bindings ) {
  40532. const gl = this.gl;
  40533. // Program
  40534. const fragmentProgram = {
  40535. stage: 'fragment',
  40536. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  40537. };
  40538. this.createProgram( fragmentProgram );
  40539. const { computeProgram } = computePipeline;
  40540. const programGPU = gl.createProgram();
  40541. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40542. const vertexShader = this.get( computeProgram ).shaderGPU;
  40543. const transforms = computeProgram.transforms;
  40544. const transformVaryingNames = [];
  40545. const transformAttributeNodes = [];
  40546. for ( let i = 0; i < transforms.length; i ++ ) {
  40547. const transform = transforms[ i ];
  40548. transformVaryingNames.push( transform.varyingName );
  40549. transformAttributeNodes.push( transform.attributeNode );
  40550. }
  40551. gl.attachShader( programGPU, fragmentShader );
  40552. gl.attachShader( programGPU, vertexShader );
  40553. gl.transformFeedbackVaryings(
  40554. programGPU,
  40555. transformVaryingNames,
  40556. gl.SEPARATE_ATTRIBS
  40557. );
  40558. gl.linkProgram( programGPU );
  40559. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40560. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40561. }
  40562. gl.useProgram( programGPU );
  40563. // Bindings
  40564. this.createBindings( null, bindings );
  40565. this._setupBindings( bindings, programGPU );
  40566. const attributeNodes = computeProgram.attributes;
  40567. const attributes = [];
  40568. const transformBuffers = [];
  40569. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  40570. const attribute = attributeNodes[ i ].node.attribute;
  40571. attributes.push( attribute );
  40572. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40573. }
  40574. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  40575. const attribute = transformAttributeNodes[ i ].attribute;
  40576. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40577. const attributeData = this.get( attribute );
  40578. transformBuffers.push( attributeData );
  40579. }
  40580. //
  40581. this.set( computePipeline, {
  40582. programGPU,
  40583. transformBuffers,
  40584. attributes
  40585. } );
  40586. }
  40587. createBindings( bindGroup, bindings ) {
  40588. this.updateBindings( bindGroup, bindings );
  40589. }
  40590. updateBindings( bindGroup, bindings ) {
  40591. const { gl } = this;
  40592. let groupIndex = 0;
  40593. let textureIndex = 0;
  40594. for ( const bindGroup of bindings ) {
  40595. for ( const binding of bindGroup.bindings ) {
  40596. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40597. const bufferGPU = gl.createBuffer();
  40598. const data = binding.buffer;
  40599. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40600. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40601. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  40602. this.set( binding, {
  40603. index: groupIndex ++,
  40604. bufferGPU
  40605. } );
  40606. } else if ( binding.isSampledTexture ) {
  40607. const { textureGPU, glTextureType } = this.get( binding.texture );
  40608. this.set( binding, {
  40609. index: textureIndex ++,
  40610. textureGPU,
  40611. glTextureType
  40612. } );
  40613. }
  40614. }
  40615. }
  40616. }
  40617. updateBinding( binding ) {
  40618. const gl = this.gl;
  40619. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40620. const bindingData = this.get( binding );
  40621. const bufferGPU = bindingData.bufferGPU;
  40622. const data = binding.buffer;
  40623. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40624. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40625. }
  40626. }
  40627. // attributes
  40628. createIndexAttribute( attribute ) {
  40629. const gl = this.gl;
  40630. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  40631. }
  40632. createAttribute( attribute ) {
  40633. if ( this.has( attribute ) ) return;
  40634. const gl = this.gl;
  40635. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40636. }
  40637. createStorageAttribute( attribute ) {
  40638. if ( this.has( attribute ) ) return;
  40639. const gl = this.gl;
  40640. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40641. }
  40642. updateAttribute( attribute ) {
  40643. this.attributeUtils.updateAttribute( attribute );
  40644. }
  40645. destroyAttribute( attribute ) {
  40646. this.attributeUtils.destroyAttribute( attribute );
  40647. }
  40648. updateSize() {
  40649. //console.warn( 'Abstract class.' );
  40650. }
  40651. hasFeature( name ) {
  40652. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  40653. const extensions = this.extensions;
  40654. for ( let i = 0; i < keysMatching.length; i ++ ) {
  40655. if ( extensions.has( keysMatching[ i ] ) ) return true;
  40656. }
  40657. return false;
  40658. }
  40659. getMaxAnisotropy() {
  40660. return this.capabilities.getMaxAnisotropy();
  40661. }
  40662. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  40663. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  40664. }
  40665. copyFramebufferToTexture( texture, renderContext ) {
  40666. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  40667. }
  40668. _setFramebuffer( renderContext ) {
  40669. const { gl, state } = this;
  40670. let currentFrameBuffer = null;
  40671. if ( renderContext.textures !== null ) {
  40672. const renderTarget = renderContext.renderTarget;
  40673. const renderTargetContextData = this.get( renderTarget );
  40674. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  40675. const cubeFace = this.renderer._activeCubeFace;
  40676. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  40677. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  40678. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  40679. let fb;
  40680. if ( isCube ) {
  40681. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  40682. renderTargetContextData.cubeFramebuffers = [];
  40683. }
  40684. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  40685. } else {
  40686. fb = renderTargetContextData.framebuffer;
  40687. }
  40688. if ( fb === undefined ) {
  40689. fb = gl.createFramebuffer();
  40690. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  40691. const textures = renderContext.textures;
  40692. if ( isCube ) {
  40693. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  40694. const { textureGPU } = this.get( textures[ 0 ] );
  40695. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  40696. } else {
  40697. for ( let i = 0; i < textures.length; i ++ ) {
  40698. const texture = textures[ i ];
  40699. const textureData = this.get( texture );
  40700. textureData.renderTarget = renderContext.renderTarget;
  40701. const attachment = gl.COLOR_ATTACHMENT0 + i;
  40702. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40703. }
  40704. renderTargetContextData.framebuffer = fb;
  40705. state.drawBuffers( renderContext, fb );
  40706. }
  40707. if ( renderContext.depthTexture !== null ) {
  40708. const textureData = this.get( renderContext.depthTexture );
  40709. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40710. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40711. }
  40712. }
  40713. if ( samples > 0 ) {
  40714. if ( msaaFb === undefined ) {
  40715. const invalidationArray = [];
  40716. msaaFb = gl.createFramebuffer();
  40717. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  40718. const msaaRenderbuffers = [];
  40719. const textures = renderContext.textures;
  40720. for ( let i = 0; i < textures.length; i ++ ) {
  40721. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  40722. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40723. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  40724. if ( depthBuffer ) {
  40725. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40726. invalidationArray.push( depthStyle );
  40727. }
  40728. const texture = renderContext.textures[ i ];
  40729. const textureData = this.get( texture );
  40730. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  40731. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40732. }
  40733. renderTargetContextData.msaaFrameBuffer = msaaFb;
  40734. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  40735. if ( depthRenderbuffer === undefined ) {
  40736. depthRenderbuffer = gl.createRenderbuffer();
  40737. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  40738. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  40739. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40740. invalidationArray.push( depthStyle );
  40741. }
  40742. renderTargetContextData.invalidationArray = invalidationArray;
  40743. }
  40744. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40745. } else {
  40746. currentFrameBuffer = fb;
  40747. }
  40748. }
  40749. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  40750. }
  40751. _getVaoKey( index, attributes ) {
  40752. let key = [];
  40753. if ( index !== null ) {
  40754. const indexData = this.get( index );
  40755. key += ':' + indexData.id;
  40756. }
  40757. for ( let i = 0; i < attributes.length; i ++ ) {
  40758. const attributeData = this.get( attributes[ i ] );
  40759. key += ':' + attributeData.id;
  40760. }
  40761. return key;
  40762. }
  40763. _createVao( index, attributes ) {
  40764. const { gl } = this;
  40765. const vaoGPU = gl.createVertexArray();
  40766. let key = '';
  40767. let staticVao = true;
  40768. gl.bindVertexArray( vaoGPU );
  40769. if ( index !== null ) {
  40770. const indexData = this.get( index );
  40771. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  40772. key += ':' + indexData.id;
  40773. }
  40774. for ( let i = 0; i < attributes.length; i ++ ) {
  40775. const attribute = attributes[ i ];
  40776. const attributeData = this.get( attribute );
  40777. key += ':' + attributeData.id;
  40778. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  40779. gl.enableVertexAttribArray( i );
  40780. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  40781. let stride, offset;
  40782. if ( attribute.isInterleavedBufferAttribute === true ) {
  40783. stride = attribute.data.stride * attributeData.bytesPerElement;
  40784. offset = attribute.offset * attributeData.bytesPerElement;
  40785. } else {
  40786. stride = 0;
  40787. offset = 0;
  40788. }
  40789. if ( attributeData.isInteger ) {
  40790. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  40791. } else {
  40792. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  40793. }
  40794. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  40795. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  40796. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  40797. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  40798. }
  40799. }
  40800. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  40801. this.vaoCache[ key ] = vaoGPU;
  40802. return { vaoGPU, staticVao };
  40803. }
  40804. _getTransformFeedback( transformBuffers ) {
  40805. let key = '';
  40806. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40807. key += ':' + transformBuffers[ i ].id;
  40808. }
  40809. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  40810. if ( transformFeedbackGPU !== undefined ) {
  40811. return transformFeedbackGPU;
  40812. }
  40813. const gl = this.gl;
  40814. transformFeedbackGPU = gl.createTransformFeedback();
  40815. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40816. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40817. const attributeData = transformBuffers[ i ];
  40818. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  40819. }
  40820. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40821. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  40822. return transformFeedbackGPU;
  40823. }
  40824. _setupBindings( bindings, programGPU ) {
  40825. const gl = this.gl;
  40826. for ( const bindGroup of bindings ) {
  40827. for ( const binding of bindGroup.bindings ) {
  40828. const bindingData = this.get( binding );
  40829. const index = bindingData.index;
  40830. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40831. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  40832. gl.uniformBlockBinding( programGPU, location, index );
  40833. } else if ( binding.isSampledTexture ) {
  40834. const location = gl.getUniformLocation( programGPU, binding.name );
  40835. gl.uniform1i( location, index );
  40836. }
  40837. }
  40838. }
  40839. }
  40840. _bindUniforms( bindings ) {
  40841. const { gl, state } = this;
  40842. for ( const bindGroup of bindings ) {
  40843. for ( const binding of bindGroup.bindings ) {
  40844. const bindingData = this.get( binding );
  40845. const index = bindingData.index;
  40846. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40847. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  40848. } else if ( binding.isSampledTexture ) {
  40849. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  40850. }
  40851. }
  40852. }
  40853. }
  40854. }
  40855. class Sampler extends Binding {
  40856. constructor( name, texture ) {
  40857. super( name );
  40858. this.texture = texture;
  40859. this.version = texture ? texture.version : 0;
  40860. this.isSampler = true;
  40861. }
  40862. }
  40863. class NodeSampler extends Sampler {
  40864. constructor( name, textureNode, groupNode ) {
  40865. super( name, textureNode ? textureNode.value : null );
  40866. this.textureNode = textureNode;
  40867. this.groupNode = groupNode;
  40868. }
  40869. update() {
  40870. this.texture = this.textureNode.value;
  40871. }
  40872. }
  40873. class StorageBuffer extends Buffer {
  40874. constructor( name, attribute ) {
  40875. super( name, attribute ? attribute.array : null );
  40876. this.attribute = attribute;
  40877. this.isStorageBuffer = true;
  40878. }
  40879. }
  40880. let _id = 0;
  40881. class NodeStorageBuffer extends StorageBuffer {
  40882. constructor( nodeUniform, groupNode ) {
  40883. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  40884. this.nodeUniform = nodeUniform;
  40885. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  40886. this.groupNode = groupNode;
  40887. }
  40888. get buffer() {
  40889. return this.nodeUniform.value;
  40890. }
  40891. }
  40892. class WebGPUTexturePassUtils {
  40893. constructor( device ) {
  40894. this.device = device;
  40895. const mipmapVertexSource = `
  40896. struct VarysStruct {
  40897. @builtin( position ) Position: vec4<f32>,
  40898. @location( 0 ) vTex : vec2<f32>
  40899. };
  40900. @vertex
  40901. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  40902. var Varys : VarysStruct;
  40903. var pos = array< vec2<f32>, 4 >(
  40904. vec2<f32>( -1.0, 1.0 ),
  40905. vec2<f32>( 1.0, 1.0 ),
  40906. vec2<f32>( -1.0, -1.0 ),
  40907. vec2<f32>( 1.0, -1.0 )
  40908. );
  40909. var tex = array< vec2<f32>, 4 >(
  40910. vec2<f32>( 0.0, 0.0 ),
  40911. vec2<f32>( 1.0, 0.0 ),
  40912. vec2<f32>( 0.0, 1.0 ),
  40913. vec2<f32>( 1.0, 1.0 )
  40914. );
  40915. Varys.vTex = tex[ vertexIndex ];
  40916. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  40917. return Varys;
  40918. }
  40919. `;
  40920. const mipmapFragmentSource = `
  40921. @group( 0 ) @binding( 0 )
  40922. var imgSampler : sampler;
  40923. @group( 0 ) @binding( 1 )
  40924. var img : texture_2d<f32>;
  40925. @fragment
  40926. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40927. return textureSample( img, imgSampler, vTex );
  40928. }
  40929. `;
  40930. const flipYFragmentSource = `
  40931. @group( 0 ) @binding( 0 )
  40932. var imgSampler : sampler;
  40933. @group( 0 ) @binding( 1 )
  40934. var img : texture_2d<f32>;
  40935. @fragment
  40936. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40937. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  40938. }
  40939. `;
  40940. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  40941. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  40942. // We'll need a new pipeline for every texture format used.
  40943. this.transferPipelines = {};
  40944. this.flipYPipelines = {};
  40945. this.mipmapVertexShaderModule = device.createShaderModule( {
  40946. label: 'mipmapVertex',
  40947. code: mipmapVertexSource
  40948. } );
  40949. this.mipmapFragmentShaderModule = device.createShaderModule( {
  40950. label: 'mipmapFragment',
  40951. code: mipmapFragmentSource
  40952. } );
  40953. this.flipYFragmentShaderModule = device.createShaderModule( {
  40954. label: 'flipYFragment',
  40955. code: flipYFragmentSource
  40956. } );
  40957. }
  40958. getTransferPipeline( format ) {
  40959. let pipeline = this.transferPipelines[ format ];
  40960. if ( pipeline === undefined ) {
  40961. pipeline = this.device.createRenderPipeline( {
  40962. vertex: {
  40963. module: this.mipmapVertexShaderModule,
  40964. entryPoint: 'main'
  40965. },
  40966. fragment: {
  40967. module: this.mipmapFragmentShaderModule,
  40968. entryPoint: 'main',
  40969. targets: [ { format } ]
  40970. },
  40971. primitive: {
  40972. topology: GPUPrimitiveTopology.TriangleStrip,
  40973. stripIndexFormat: GPUIndexFormat.Uint32
  40974. },
  40975. layout: 'auto'
  40976. } );
  40977. this.transferPipelines[ format ] = pipeline;
  40978. }
  40979. return pipeline;
  40980. }
  40981. getFlipYPipeline( format ) {
  40982. let pipeline = this.flipYPipelines[ format ];
  40983. if ( pipeline === undefined ) {
  40984. pipeline = this.device.createRenderPipeline( {
  40985. vertex: {
  40986. module: this.mipmapVertexShaderModule,
  40987. entryPoint: 'main'
  40988. },
  40989. fragment: {
  40990. module: this.flipYFragmentShaderModule,
  40991. entryPoint: 'main',
  40992. targets: [ { format } ]
  40993. },
  40994. primitive: {
  40995. topology: GPUPrimitiveTopology.TriangleStrip,
  40996. stripIndexFormat: GPUIndexFormat.Uint32
  40997. },
  40998. layout: 'auto'
  40999. } );
  41000. this.flipYPipelines[ format ] = pipeline;
  41001. }
  41002. return pipeline;
  41003. }
  41004. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41005. const format = textureGPUDescriptor.format;
  41006. const { width, height } = textureGPUDescriptor.size;
  41007. const transferPipeline = this.getTransferPipeline( format );
  41008. const flipYPipeline = this.getFlipYPipeline( format );
  41009. const tempTexture = this.device.createTexture( {
  41010. size: { width, height, depthOrArrayLayers: 1 },
  41011. format,
  41012. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41013. } );
  41014. const srcView = textureGPU.createView( {
  41015. baseMipLevel: 0,
  41016. mipLevelCount: 1,
  41017. dimension: GPUTextureViewDimension.TwoD,
  41018. baseArrayLayer
  41019. } );
  41020. const dstView = tempTexture.createView( {
  41021. baseMipLevel: 0,
  41022. mipLevelCount: 1,
  41023. dimension: GPUTextureViewDimension.TwoD,
  41024. baseArrayLayer: 0
  41025. } );
  41026. const commandEncoder = this.device.createCommandEncoder( {} );
  41027. const pass = ( pipeline, sourceView, destinationView ) => {
  41028. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41029. const bindGroup = this.device.createBindGroup( {
  41030. layout: bindGroupLayout,
  41031. entries: [ {
  41032. binding: 0,
  41033. resource: this.flipYSampler
  41034. }, {
  41035. binding: 1,
  41036. resource: sourceView
  41037. } ]
  41038. } );
  41039. const passEncoder = commandEncoder.beginRenderPass( {
  41040. colorAttachments: [ {
  41041. view: destinationView,
  41042. loadOp: GPULoadOp.Clear,
  41043. storeOp: GPUStoreOp.Store,
  41044. clearValue: [ 0, 0, 0, 0 ]
  41045. } ]
  41046. } );
  41047. passEncoder.setPipeline( pipeline );
  41048. passEncoder.setBindGroup( 0, bindGroup );
  41049. passEncoder.draw( 4, 1, 0, 0 );
  41050. passEncoder.end();
  41051. };
  41052. pass( transferPipeline, srcView, dstView );
  41053. pass( flipYPipeline, dstView, srcView );
  41054. this.device.queue.submit( [ commandEncoder.finish() ] );
  41055. tempTexture.destroy();
  41056. }
  41057. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41058. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41059. const commandEncoder = this.device.createCommandEncoder( {} );
  41060. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41061. let srcView = textureGPU.createView( {
  41062. baseMipLevel: 0,
  41063. mipLevelCount: 1,
  41064. dimension: GPUTextureViewDimension.TwoD,
  41065. baseArrayLayer
  41066. } );
  41067. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41068. const bindGroup = this.device.createBindGroup( {
  41069. layout: bindGroupLayout,
  41070. entries: [ {
  41071. binding: 0,
  41072. resource: this.mipmapSampler
  41073. }, {
  41074. binding: 1,
  41075. resource: srcView
  41076. } ]
  41077. } );
  41078. const dstView = textureGPU.createView( {
  41079. baseMipLevel: i,
  41080. mipLevelCount: 1,
  41081. dimension: GPUTextureViewDimension.TwoD,
  41082. baseArrayLayer
  41083. } );
  41084. const passEncoder = commandEncoder.beginRenderPass( {
  41085. colorAttachments: [ {
  41086. view: dstView,
  41087. loadOp: GPULoadOp.Clear,
  41088. storeOp: GPUStoreOp.Store,
  41089. clearValue: [ 0, 0, 0, 0 ]
  41090. } ]
  41091. } );
  41092. passEncoder.setPipeline( pipeline );
  41093. passEncoder.setBindGroup( 0, bindGroup );
  41094. passEncoder.draw( 4, 1, 0, 0 );
  41095. passEncoder.end();
  41096. srcView = dstView;
  41097. }
  41098. this.device.queue.submit( [ commandEncoder.finish() ] );
  41099. }
  41100. }
  41101. const _compareToWebGPU = {
  41102. [ NeverCompare ]: 'never',
  41103. [ LessCompare ]: 'less',
  41104. [ EqualCompare ]: 'equal',
  41105. [ LessEqualCompare ]: 'less-equal',
  41106. [ GreaterCompare ]: 'greater',
  41107. [ GreaterEqualCompare ]: 'greater-equal',
  41108. [ AlwaysCompare ]: 'always',
  41109. [ NotEqualCompare ]: 'not-equal'
  41110. };
  41111. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  41112. class WebGPUTextureUtils {
  41113. constructor( backend ) {
  41114. this.backend = backend;
  41115. this._passUtils = null;
  41116. this.defaultTexture = {};
  41117. this.defaultCubeTexture = {};
  41118. this.defaultVideoFrame = null;
  41119. this.colorBuffer = null;
  41120. this.depthTexture = new DepthTexture();
  41121. this.depthTexture.name = 'depthBuffer';
  41122. }
  41123. createSampler( texture ) {
  41124. const backend = this.backend;
  41125. const device = backend.device;
  41126. const textureGPU = backend.get( texture );
  41127. const samplerDescriptorGPU = {
  41128. addressModeU: this._convertAddressMode( texture.wrapS ),
  41129. addressModeV: this._convertAddressMode( texture.wrapT ),
  41130. addressModeW: this._convertAddressMode( texture.wrapR ),
  41131. magFilter: this._convertFilterMode( texture.magFilter ),
  41132. minFilter: this._convertFilterMode( texture.minFilter ),
  41133. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41134. maxAnisotropy: texture.anisotropy
  41135. };
  41136. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41137. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41138. }
  41139. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41140. }
  41141. createDefaultTexture( texture ) {
  41142. let textureGPU;
  41143. const format = getFormat( texture );
  41144. if ( texture.isCubeTexture ) {
  41145. textureGPU = this._getDefaultCubeTextureGPU( format );
  41146. } else if ( texture.isVideoTexture ) {
  41147. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41148. } else {
  41149. textureGPU = this._getDefaultTextureGPU( format );
  41150. }
  41151. this.backend.get( texture ).texture = textureGPU;
  41152. }
  41153. createTexture( texture, options = {} ) {
  41154. const backend = this.backend;
  41155. const textureData = backend.get( texture );
  41156. if ( textureData.initialized ) {
  41157. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41158. }
  41159. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41160. if ( options.levels === undefined ) options.levels = 1;
  41161. if ( options.depth === undefined ) options.depth = 1;
  41162. const { width, height, depth, levels } = options;
  41163. const dimension = this._getDimension( texture );
  41164. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41165. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  41166. sampleCount = backend.utils.getSampleCount( sampleCount );
  41167. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  41168. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41169. if ( texture.isStorageTexture === true ) {
  41170. usage |= GPUTextureUsage.STORAGE_BINDING;
  41171. }
  41172. if ( texture.isCompressedTexture !== true ) {
  41173. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41174. }
  41175. const textureDescriptorGPU = {
  41176. label: texture.name,
  41177. size: {
  41178. width: width,
  41179. height: height,
  41180. depthOrArrayLayers: depth,
  41181. },
  41182. mipLevelCount: levels,
  41183. sampleCount: primarySampleCount,
  41184. dimension: dimension,
  41185. format: format,
  41186. usage: usage
  41187. };
  41188. // texture creation
  41189. if ( texture.isVideoTexture ) {
  41190. const video = texture.source.data;
  41191. const videoFrame = new VideoFrame( video );
  41192. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41193. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41194. videoFrame.close();
  41195. textureData.externalTexture = video;
  41196. } else {
  41197. if ( format === undefined ) {
  41198. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41199. return this.createDefaultTexture( texture );
  41200. }
  41201. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41202. }
  41203. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  41204. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41205. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41206. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  41207. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41208. }
  41209. textureData.initialized = true;
  41210. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41211. }
  41212. destroyTexture( texture ) {
  41213. const backend = this.backend;
  41214. const textureData = backend.get( texture );
  41215. textureData.texture.destroy();
  41216. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41217. backend.delete( texture );
  41218. }
  41219. destroySampler( texture ) {
  41220. const backend = this.backend;
  41221. const textureData = backend.get( texture );
  41222. delete textureData.sampler;
  41223. }
  41224. generateMipmaps( texture ) {
  41225. const textureData = this.backend.get( texture );
  41226. if ( texture.isCubeTexture ) {
  41227. for ( let i = 0; i < 6; i ++ ) {
  41228. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41229. }
  41230. } else {
  41231. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  41232. }
  41233. }
  41234. getColorBuffer() {
  41235. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41236. const backend = this.backend;
  41237. const { width, height } = backend.getDrawingBufferSize();
  41238. this.colorBuffer = backend.device.createTexture( {
  41239. label: 'colorBuffer',
  41240. size: {
  41241. width: width,
  41242. height: height,
  41243. depthOrArrayLayers: 1
  41244. },
  41245. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41246. format: GPUTextureFormat.BGRA8Unorm,
  41247. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41248. } );
  41249. return this.colorBuffer;
  41250. }
  41251. getDepthBuffer( depth = true, stencil = false ) {
  41252. const backend = this.backend;
  41253. const { width, height } = backend.getDrawingBufferSize();
  41254. const depthTexture = this.depthTexture;
  41255. const depthTextureGPU = backend.get( depthTexture ).texture;
  41256. let format, type;
  41257. if ( stencil ) {
  41258. format = DepthStencilFormat;
  41259. type = UnsignedInt248Type;
  41260. } else if ( depth ) {
  41261. format = DepthFormat;
  41262. type = UnsignedIntType;
  41263. }
  41264. if ( depthTextureGPU !== undefined ) {
  41265. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41266. return depthTextureGPU;
  41267. }
  41268. this.destroyTexture( depthTexture );
  41269. }
  41270. depthTexture.name = 'depthBuffer';
  41271. depthTexture.format = format;
  41272. depthTexture.type = type;
  41273. depthTexture.image.width = width;
  41274. depthTexture.image.height = height;
  41275. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  41276. return backend.get( depthTexture ).texture;
  41277. }
  41278. updateTexture( texture, options ) {
  41279. const textureData = this.backend.get( texture );
  41280. const { textureDescriptorGPU } = textureData;
  41281. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  41282. return;
  41283. // transfer texture data
  41284. if ( texture.isDataTexture ) {
  41285. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41286. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41287. for ( let i = 0; i < options.image.depth; i ++ ) {
  41288. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  41289. }
  41290. } else if ( texture.isCompressedTexture ) {
  41291. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  41292. } else if ( texture.isCubeTexture ) {
  41293. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  41294. } else if ( texture.isVideoTexture ) {
  41295. const video = texture.source.data;
  41296. textureData.externalTexture = video;
  41297. } else {
  41298. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41299. }
  41300. //
  41301. textureData.version = texture.version;
  41302. if ( texture.onUpdate ) texture.onUpdate( texture );
  41303. }
  41304. async copyTextureToBuffer( texture, x, y, width, height ) {
  41305. const device = this.backend.device;
  41306. const textureData = this.backend.get( texture );
  41307. const textureGPU = textureData.texture;
  41308. const format = textureData.textureDescriptorGPU.format;
  41309. const bytesPerTexel = this._getBytesPerTexel( format );
  41310. let bytesPerRow = width * bytesPerTexel;
  41311. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  41312. const readBuffer = device.createBuffer(
  41313. {
  41314. size: width * height * bytesPerTexel,
  41315. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41316. }
  41317. );
  41318. const encoder = device.createCommandEncoder();
  41319. encoder.copyTextureToBuffer(
  41320. {
  41321. texture: textureGPU,
  41322. origin: { x, y },
  41323. },
  41324. {
  41325. buffer: readBuffer,
  41326. bytesPerRow: bytesPerRow
  41327. },
  41328. {
  41329. width: width,
  41330. height: height
  41331. }
  41332. );
  41333. const typedArrayType = this._getTypedArrayType( format );
  41334. device.queue.submit( [ encoder.finish() ] );
  41335. await readBuffer.mapAsync( GPUMapMode.READ );
  41336. const buffer = readBuffer.getMappedRange();
  41337. return new typedArrayType( buffer );
  41338. }
  41339. _isEnvironmentTexture( texture ) {
  41340. const mapping = texture.mapping;
  41341. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  41342. }
  41343. _getDefaultTextureGPU( format ) {
  41344. let defaultTexture = this.defaultTexture[ format ];
  41345. if ( defaultTexture === undefined ) {
  41346. const texture = new Texture();
  41347. texture.minFilter = NearestFilter;
  41348. texture.magFilter = NearestFilter;
  41349. this.createTexture( texture, { width: 1, height: 1, format } );
  41350. this.defaultTexture[ format ] = defaultTexture = texture;
  41351. }
  41352. return this.backend.get( defaultTexture ).texture;
  41353. }
  41354. _getDefaultCubeTextureGPU( format ) {
  41355. let defaultCubeTexture = this.defaultTexture[ format ];
  41356. if ( defaultCubeTexture === undefined ) {
  41357. const texture = new CubeTexture();
  41358. texture.minFilter = NearestFilter;
  41359. texture.magFilter = NearestFilter;
  41360. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  41361. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  41362. }
  41363. return this.backend.get( defaultCubeTexture ).texture;
  41364. }
  41365. _getDefaultVideoFrame() {
  41366. let defaultVideoFrame = this.defaultVideoFrame;
  41367. if ( defaultVideoFrame === null ) {
  41368. const init = {
  41369. timestamp: 0,
  41370. codedWidth: 1,
  41371. codedHeight: 1,
  41372. format: 'RGBA',
  41373. };
  41374. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  41375. }
  41376. return defaultVideoFrame;
  41377. }
  41378. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  41379. for ( let i = 0; i < 6; i ++ ) {
  41380. const image = images[ i ];
  41381. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  41382. if ( image.isDataTexture ) {
  41383. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41384. } else {
  41385. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41386. }
  41387. }
  41388. }
  41389. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  41390. const device = this.backend.device;
  41391. device.queue.copyExternalImageToTexture(
  41392. {
  41393. source: image
  41394. }, {
  41395. texture: textureGPU,
  41396. mipLevel: 0,
  41397. origin: { x: 0, y: 0, z: originDepth }
  41398. }, {
  41399. width: image.width,
  41400. height: image.height,
  41401. depthOrArrayLayers: 1
  41402. }
  41403. );
  41404. if ( flipY === true ) {
  41405. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41406. }
  41407. }
  41408. _getPassUtils() {
  41409. let passUtils = this._passUtils;
  41410. if ( passUtils === null ) {
  41411. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  41412. }
  41413. return passUtils;
  41414. }
  41415. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  41416. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  41417. }
  41418. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  41419. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  41420. }
  41421. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  41422. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41423. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  41424. const device = this.backend.device;
  41425. const data = image.data;
  41426. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  41427. const bytesPerRow = image.width * bytesPerTexel;
  41428. device.queue.writeTexture(
  41429. {
  41430. texture: textureGPU,
  41431. mipLevel: 0,
  41432. origin: { x: 0, y: 0, z: originDepth }
  41433. },
  41434. data,
  41435. {
  41436. offset: image.width * image.height * bytesPerTexel * depth,
  41437. bytesPerRow
  41438. },
  41439. {
  41440. width: image.width,
  41441. height: image.height,
  41442. depthOrArrayLayers: 1
  41443. } );
  41444. if ( flipY === true ) {
  41445. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41446. }
  41447. }
  41448. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  41449. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41450. const device = this.backend.device;
  41451. const blockData = this._getBlockData( textureDescriptorGPU.format );
  41452. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41453. const mipmap = mipmaps[ i ];
  41454. const width = mipmap.width;
  41455. const height = mipmap.height;
  41456. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  41457. device.queue.writeTexture(
  41458. {
  41459. texture: textureGPU,
  41460. mipLevel: i
  41461. },
  41462. mipmap.data,
  41463. {
  41464. offset: 0,
  41465. bytesPerRow
  41466. },
  41467. {
  41468. width: Math.ceil( width / blockData.width ) * blockData.width,
  41469. height: Math.ceil( height / blockData.width ) * blockData.width,
  41470. depthOrArrayLayers: 1
  41471. }
  41472. );
  41473. }
  41474. }
  41475. _getBlockData( format ) {
  41476. // this method is only relevant for compressed texture formats
  41477. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  41478. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  41479. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  41480. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  41481. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  41482. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  41483. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  41484. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41485. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41486. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41487. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  41488. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  41489. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  41490. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  41491. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41492. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  41493. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  41494. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  41495. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  41496. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  41497. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  41498. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  41499. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  41500. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  41501. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  41502. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  41503. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  41504. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  41505. }
  41506. _convertAddressMode( value ) {
  41507. let addressMode = GPUAddressMode.ClampToEdge;
  41508. if ( value === RepeatWrapping ) {
  41509. addressMode = GPUAddressMode.Repeat;
  41510. } else if ( value === MirroredRepeatWrapping ) {
  41511. addressMode = GPUAddressMode.MirrorRepeat;
  41512. }
  41513. return addressMode;
  41514. }
  41515. _convertFilterMode( value ) {
  41516. let filterMode = GPUFilterMode.Linear;
  41517. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  41518. filterMode = GPUFilterMode.Nearest;
  41519. }
  41520. return filterMode;
  41521. }
  41522. _getBytesPerTexel( format ) {
  41523. // 8-bit formats
  41524. if ( format === GPUTextureFormat.R8Unorm ||
  41525. format === GPUTextureFormat.R8Snorm ||
  41526. format === GPUTextureFormat.R8Uint ||
  41527. format === GPUTextureFormat.R8Sint ) return 1;
  41528. // 16-bit formats
  41529. if ( format === GPUTextureFormat.R16Uint ||
  41530. format === GPUTextureFormat.R16Sint ||
  41531. format === GPUTextureFormat.R16Float ||
  41532. format === GPUTextureFormat.RG8Unorm ||
  41533. format === GPUTextureFormat.RG8Snorm ||
  41534. format === GPUTextureFormat.RG8Uint ||
  41535. format === GPUTextureFormat.RG8Sint ) return 2;
  41536. // 32-bit formats
  41537. if ( format === GPUTextureFormat.R32Uint ||
  41538. format === GPUTextureFormat.R32Sint ||
  41539. format === GPUTextureFormat.R32Float ||
  41540. format === GPUTextureFormat.RG16Uint ||
  41541. format === GPUTextureFormat.RG16Sint ||
  41542. format === GPUTextureFormat.RG16Float ||
  41543. format === GPUTextureFormat.RGBA8Unorm ||
  41544. format === GPUTextureFormat.RGBA8UnormSRGB ||
  41545. format === GPUTextureFormat.RGBA8Snorm ||
  41546. format === GPUTextureFormat.RGBA8Uint ||
  41547. format === GPUTextureFormat.RGBA8Sint ||
  41548. format === GPUTextureFormat.BGRA8Unorm ||
  41549. format === GPUTextureFormat.BGRA8UnormSRGB ||
  41550. // Packed 32-bit formats
  41551. format === GPUTextureFormat.RGB9E5UFloat ||
  41552. format === GPUTextureFormat.RGB10A2Unorm ||
  41553. format === GPUTextureFormat.RG11B10UFloat ||
  41554. format === GPUTextureFormat.Depth32Float ||
  41555. format === GPUTextureFormat.Depth24Plus ||
  41556. format === GPUTextureFormat.Depth24PlusStencil8 ||
  41557. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  41558. // 64-bit formats
  41559. if ( format === GPUTextureFormat.RG32Uint ||
  41560. format === GPUTextureFormat.RG32Sint ||
  41561. format === GPUTextureFormat.RG32Float ||
  41562. format === GPUTextureFormat.RGBA16Uint ||
  41563. format === GPUTextureFormat.RGBA16Sint ||
  41564. format === GPUTextureFormat.RGBA16Float ) return 8;
  41565. // 128-bit formats
  41566. if ( format === GPUTextureFormat.RGBA32Uint ||
  41567. format === GPUTextureFormat.RGBA32Sint ||
  41568. format === GPUTextureFormat.RGBA32Float ) return 16;
  41569. }
  41570. _getTypedArrayType( format ) {
  41571. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  41572. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  41573. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  41574. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  41575. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  41576. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  41577. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  41578. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  41579. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  41580. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  41581. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  41582. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  41583. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  41584. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  41585. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  41586. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  41587. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  41588. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  41589. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  41590. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  41591. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  41592. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  41593. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  41594. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  41595. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  41596. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  41597. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  41598. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  41599. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  41600. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  41601. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  41602. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  41603. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  41604. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  41605. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  41606. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  41607. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  41608. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  41609. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  41610. }
  41611. _getDimension( texture ) {
  41612. let dimension;
  41613. if ( texture.isData3DTexture ) {
  41614. dimension = GPUTextureDimension.ThreeD;
  41615. } else {
  41616. dimension = GPUTextureDimension.TwoD;
  41617. }
  41618. return dimension;
  41619. }
  41620. }
  41621. function getFormat( texture, device = null ) {
  41622. const format = texture.format;
  41623. const type = texture.type;
  41624. const colorSpace = texture.colorSpace;
  41625. let formatGPU;
  41626. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  41627. formatGPU = GPUTextureFormat.BGRA8Unorm;
  41628. } else if ( texture.isCompressedTexture === true ) {
  41629. switch ( format ) {
  41630. case RGBA_S3TC_DXT1_Format:
  41631. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  41632. break;
  41633. case RGBA_S3TC_DXT3_Format:
  41634. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  41635. break;
  41636. case RGBA_S3TC_DXT5_Format:
  41637. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  41638. break;
  41639. case RGB_ETC2_Format:
  41640. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  41641. break;
  41642. case RGBA_ETC2_EAC_Format:
  41643. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  41644. break;
  41645. case RGBA_ASTC_4x4_Format:
  41646. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  41647. break;
  41648. case RGBA_ASTC_5x4_Format:
  41649. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  41650. break;
  41651. case RGBA_ASTC_5x5_Format:
  41652. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  41653. break;
  41654. case RGBA_ASTC_6x5_Format:
  41655. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  41656. break;
  41657. case RGBA_ASTC_6x6_Format:
  41658. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  41659. break;
  41660. case RGBA_ASTC_8x5_Format:
  41661. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  41662. break;
  41663. case RGBA_ASTC_8x6_Format:
  41664. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  41665. break;
  41666. case RGBA_ASTC_8x8_Format:
  41667. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  41668. break;
  41669. case RGBA_ASTC_10x5_Format:
  41670. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  41671. break;
  41672. case RGBA_ASTC_10x6_Format:
  41673. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  41674. break;
  41675. case RGBA_ASTC_10x8_Format:
  41676. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  41677. break;
  41678. case RGBA_ASTC_10x10_Format:
  41679. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  41680. break;
  41681. case RGBA_ASTC_12x10_Format:
  41682. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  41683. break;
  41684. case RGBA_ASTC_12x12_Format:
  41685. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  41686. break;
  41687. default:
  41688. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  41689. }
  41690. } else {
  41691. switch ( format ) {
  41692. case RGBAFormat:
  41693. switch ( type ) {
  41694. case ByteType:
  41695. formatGPU = GPUTextureFormat.RGBA8Snorm;
  41696. break;
  41697. case ShortType:
  41698. formatGPU = GPUTextureFormat.RGBA16Sint;
  41699. break;
  41700. case UnsignedShortType:
  41701. formatGPU = GPUTextureFormat.RGBA16Uint;
  41702. break;
  41703. case UnsignedIntType:
  41704. formatGPU = GPUTextureFormat.RGBA32Uint;
  41705. break;
  41706. case IntType:
  41707. formatGPU = GPUTextureFormat.RGBA32Sint;
  41708. break;
  41709. case UnsignedByteType:
  41710. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  41711. break;
  41712. case HalfFloatType:
  41713. formatGPU = GPUTextureFormat.RGBA16Float;
  41714. break;
  41715. case FloatType:
  41716. formatGPU = GPUTextureFormat.RGBA32Float;
  41717. break;
  41718. default:
  41719. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  41720. }
  41721. break;
  41722. case RGBFormat:
  41723. switch ( type ) {
  41724. case UnsignedInt5999Type:
  41725. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  41726. break;
  41727. default:
  41728. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  41729. }
  41730. break;
  41731. case RedFormat:
  41732. switch ( type ) {
  41733. case ByteType:
  41734. formatGPU = GPUTextureFormat.R8Snorm;
  41735. break;
  41736. case ShortType:
  41737. formatGPU = GPUTextureFormat.R16Sint;
  41738. break;
  41739. case UnsignedShortType:
  41740. formatGPU = GPUTextureFormat.R16Uint;
  41741. break;
  41742. case UnsignedIntType:
  41743. formatGPU = GPUTextureFormat.R32Uint;
  41744. break;
  41745. case IntType:
  41746. formatGPU = GPUTextureFormat.R32Sint;
  41747. break;
  41748. case UnsignedByteType:
  41749. formatGPU = GPUTextureFormat.R8Unorm;
  41750. break;
  41751. case HalfFloatType:
  41752. formatGPU = GPUTextureFormat.R16Float;
  41753. break;
  41754. case FloatType:
  41755. formatGPU = GPUTextureFormat.R32Float;
  41756. break;
  41757. default:
  41758. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  41759. }
  41760. break;
  41761. case RGFormat:
  41762. switch ( type ) {
  41763. case ByteType:
  41764. formatGPU = GPUTextureFormat.RG8Snorm;
  41765. break;
  41766. case ShortType:
  41767. formatGPU = GPUTextureFormat.RG16Sint;
  41768. break;
  41769. case UnsignedShortType:
  41770. formatGPU = GPUTextureFormat.RG16Uint;
  41771. break;
  41772. case UnsignedIntType:
  41773. formatGPU = GPUTextureFormat.RG32Uint;
  41774. break;
  41775. case IntType:
  41776. formatGPU = GPUTextureFormat.RG32Sint;
  41777. break;
  41778. case UnsignedByteType:
  41779. formatGPU = GPUTextureFormat.RG8Unorm;
  41780. break;
  41781. case HalfFloatType:
  41782. formatGPU = GPUTextureFormat.RG16Float;
  41783. break;
  41784. case FloatType:
  41785. formatGPU = GPUTextureFormat.RG32Float;
  41786. break;
  41787. default:
  41788. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  41789. }
  41790. break;
  41791. case DepthFormat:
  41792. switch ( type ) {
  41793. case UnsignedShortType:
  41794. formatGPU = GPUTextureFormat.Depth16Unorm;
  41795. break;
  41796. case UnsignedIntType:
  41797. formatGPU = GPUTextureFormat.Depth24Plus;
  41798. break;
  41799. case FloatType:
  41800. formatGPU = GPUTextureFormat.Depth32Float;
  41801. break;
  41802. default:
  41803. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  41804. }
  41805. break;
  41806. case DepthStencilFormat:
  41807. switch ( type ) {
  41808. case UnsignedInt248Type:
  41809. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  41810. break;
  41811. case FloatType:
  41812. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  41813. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  41814. }
  41815. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  41816. break;
  41817. default:
  41818. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  41819. }
  41820. break;
  41821. case RedIntegerFormat:
  41822. switch ( type ) {
  41823. case IntType:
  41824. formatGPU = GPUTextureFormat.R32Sint;
  41825. break;
  41826. case UnsignedIntType:
  41827. formatGPU = GPUTextureFormat.R32Uint;
  41828. break;
  41829. default:
  41830. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  41831. }
  41832. break;
  41833. case RGIntegerFormat:
  41834. switch ( type ) {
  41835. case IntType:
  41836. formatGPU = GPUTextureFormat.RG32Sint;
  41837. break;
  41838. case UnsignedIntType:
  41839. formatGPU = GPUTextureFormat.RG32Uint;
  41840. break;
  41841. default:
  41842. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  41843. }
  41844. break;
  41845. case RGBAIntegerFormat:
  41846. switch ( type ) {
  41847. case IntType:
  41848. formatGPU = GPUTextureFormat.RGBA32Sint;
  41849. break;
  41850. case UnsignedIntType:
  41851. formatGPU = GPUTextureFormat.RGBA32Uint;
  41852. break;
  41853. default:
  41854. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  41855. }
  41856. break;
  41857. default:
  41858. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  41859. }
  41860. }
  41861. return formatGPU;
  41862. }
  41863. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  41864. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  41865. const wgslTypeLib$1 = {
  41866. 'f32': 'float',
  41867. 'i32': 'int',
  41868. 'u32': 'uint',
  41869. 'bool': 'bool',
  41870. 'vec2<f32>': 'vec2',
  41871. 'vec2<i32>': 'ivec2',
  41872. 'vec2<u32>': 'uvec2',
  41873. 'vec2<bool>': 'bvec2',
  41874. 'vec2f': 'vec2',
  41875. 'vec2i': 'ivec2',
  41876. 'vec2u': 'uvec2',
  41877. 'vec2b': 'bvec2',
  41878. 'vec3<f32>': 'vec3',
  41879. 'vec3<i32>': 'ivec3',
  41880. 'vec3<u32>': 'uvec3',
  41881. 'vec3<bool>': 'bvec3',
  41882. 'vec3f': 'vec3',
  41883. 'vec3i': 'ivec3',
  41884. 'vec3u': 'uvec3',
  41885. 'vec3b': 'bvec3',
  41886. 'vec4<f32>': 'vec4',
  41887. 'vec4<i32>': 'ivec4',
  41888. 'vec4<u32>': 'uvec4',
  41889. 'vec4<bool>': 'bvec4',
  41890. 'vec4f': 'vec4',
  41891. 'vec4i': 'ivec4',
  41892. 'vec4u': 'uvec4',
  41893. 'vec4b': 'bvec4',
  41894. 'mat2x2<f32>': 'mat2',
  41895. 'mat2x2f': 'mat2',
  41896. 'mat3x3<f32>': 'mat3',
  41897. 'mat3x3f': 'mat3',
  41898. 'mat4x4<f32>': 'mat4',
  41899. 'mat4x4f': 'mat4',
  41900. 'sampler': 'sampler',
  41901. 'texture_1d': 'texture',
  41902. 'texture_2d': 'texture',
  41903. 'texture_2d_array': 'texture',
  41904. 'texture_multisampled_2d': 'cubeTexture',
  41905. 'texture_depth_2d': 'depthTexture',
  41906. 'texture_3d': 'texture3D',
  41907. 'texture_cube': 'cubeTexture',
  41908. 'texture_cube_array': 'cubeTexture',
  41909. 'texture_storage_1d': 'storageTexture',
  41910. 'texture_storage_2d': 'storageTexture',
  41911. 'texture_storage_2d_array': 'storageTexture',
  41912. 'texture_storage_3d': 'storageTexture'
  41913. };
  41914. const parse = ( source ) => {
  41915. source = source.trim();
  41916. const declaration = source.match( declarationRegexp );
  41917. if ( declaration !== null && declaration.length === 4 ) {
  41918. const inputsCode = declaration[ 2 ];
  41919. const propsMatches = [];
  41920. let match = null;
  41921. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  41922. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  41923. }
  41924. // Process matches to correctly pair names and types
  41925. const inputs = [];
  41926. for ( let i = 0; i < propsMatches.length; i ++ ) {
  41927. const { name, type } = propsMatches[ i ];
  41928. let resolvedType = type;
  41929. if ( resolvedType.startsWith( 'texture' ) ) {
  41930. resolvedType = type.split( '<' )[ 0 ];
  41931. }
  41932. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  41933. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  41934. }
  41935. const blockCode = source.substring( declaration[ 0 ].length );
  41936. const outputType = declaration[ 3 ] || 'void';
  41937. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  41938. const type = wgslTypeLib$1[ outputType ] || outputType;
  41939. return {
  41940. type,
  41941. inputs,
  41942. name,
  41943. inputsCode,
  41944. blockCode,
  41945. outputType
  41946. };
  41947. } else {
  41948. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  41949. }
  41950. };
  41951. class WGSLNodeFunction extends NodeFunction {
  41952. constructor( source ) {
  41953. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  41954. super( type, inputs, name );
  41955. this.inputsCode = inputsCode;
  41956. this.blockCode = blockCode;
  41957. this.outputType = outputType;
  41958. }
  41959. getCode( name = this.name ) {
  41960. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  41961. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  41962. }
  41963. }
  41964. class WGSLNodeParser extends NodeParser {
  41965. parseFunction( source ) {
  41966. return new WGSLNodeFunction( source );
  41967. }
  41968. }
  41969. // GPUShaderStage is not defined in browsers not supporting WebGPU
  41970. const GPUShaderStage = self.GPUShaderStage;
  41971. const gpuShaderStageLib = {
  41972. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  41973. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  41974. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  41975. };
  41976. const supports = {
  41977. instance: true,
  41978. swizzleAssign: false,
  41979. storageBuffer: true
  41980. };
  41981. const wgslFnOpLib = {
  41982. '^^': 'threejs_xor'
  41983. };
  41984. const wgslTypeLib = {
  41985. float: 'f32',
  41986. int: 'i32',
  41987. uint: 'u32',
  41988. bool: 'bool',
  41989. color: 'vec3<f32>',
  41990. vec2: 'vec2<f32>',
  41991. ivec2: 'vec2<i32>',
  41992. uvec2: 'vec2<u32>',
  41993. bvec2: 'vec2<bool>',
  41994. vec3: 'vec3<f32>',
  41995. ivec3: 'vec3<i32>',
  41996. uvec3: 'vec3<u32>',
  41997. bvec3: 'vec3<bool>',
  41998. vec4: 'vec4<f32>',
  41999. ivec4: 'vec4<i32>',
  42000. uvec4: 'vec4<u32>',
  42001. bvec4: 'vec4<bool>',
  42002. mat2: 'mat2x2<f32>',
  42003. imat2: 'mat2x2<i32>',
  42004. umat2: 'mat2x2<u32>',
  42005. bmat2: 'mat2x2<bool>',
  42006. mat3: 'mat3x3<f32>',
  42007. imat3: 'mat3x3<i32>',
  42008. umat3: 'mat3x3<u32>',
  42009. bmat3: 'mat3x3<bool>',
  42010. mat4: 'mat4x4<f32>',
  42011. imat4: 'mat4x4<i32>',
  42012. umat4: 'mat4x4<u32>',
  42013. bmat4: 'mat4x4<bool>'
  42014. };
  42015. const wgslMethods = {
  42016. dFdx: 'dpdx',
  42017. dFdy: '- dpdy',
  42018. mod_float: 'threejs_mod_float',
  42019. mod_vec2: 'threejs_mod_vec2',
  42020. mod_vec3: 'threejs_mod_vec3',
  42021. mod_vec4: 'threejs_mod_vec4',
  42022. equals_bool: 'threejs_equals_bool',
  42023. equals_bvec2: 'threejs_equals_bvec2',
  42024. equals_bvec3: 'threejs_equals_bvec3',
  42025. equals_bvec4: 'threejs_equals_bvec4',
  42026. lessThanEqual: 'threejs_lessThanEqual',
  42027. greaterThan: 'threejs_greaterThan',
  42028. inversesqrt: 'inverseSqrt',
  42029. bitcast: 'bitcast<f32>'
  42030. };
  42031. const wgslPolyfill = {
  42032. threejs_xor: new CodeNode( `
  42033. fn threejs_xor( a : bool, b : bool ) -> bool {
  42034. return ( a || b ) && !( a && b );
  42035. }
  42036. ` ),
  42037. lessThanEqual: new CodeNode( `
  42038. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  42039. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  42040. }
  42041. ` ),
  42042. greaterThan: new CodeNode( `
  42043. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  42044. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  42045. }
  42046. ` ),
  42047. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42048. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42049. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42050. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42051. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42052. equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  42053. equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  42054. equals_bvec4: new CodeNode( 'fn threejs_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 ); }' ),
  42055. repeatWrapping: new CodeNode( `
  42056. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  42057. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  42058. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  42059. }
  42060. ` ),
  42061. biquadraticTexture: new CodeNode( `
  42062. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  42063. let res = vec2f( textureDimensions( map, level ) );
  42064. let uvScaled = coord * res;
  42065. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42066. // https://www.shadertoy.com/view/WtyXRy
  42067. let uv = uvWrapping - 0.5;
  42068. let iuv = floor( uv );
  42069. let f = fract( uv );
  42070. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  42071. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  42072. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  42073. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  42074. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42075. }
  42076. ` )
  42077. };
  42078. class WGSLNodeBuilder extends NodeBuilder {
  42079. constructor( object, renderer ) {
  42080. super( object, renderer, new WGSLNodeParser() );
  42081. this.uniformGroups = {};
  42082. this.builtins = {};
  42083. this.directives = {};
  42084. }
  42085. needsColorSpaceToLinear( texture ) {
  42086. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42087. }
  42088. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42089. if ( shaderStage === 'fragment' ) {
  42090. if ( depthSnippet ) {
  42091. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42092. } else {
  42093. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42094. }
  42095. } else if ( this.isFilteredTexture( texture ) ) {
  42096. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42097. } else {
  42098. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  42099. }
  42100. }
  42101. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42102. if ( shaderStage === 'fragment' ) {
  42103. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42104. } else {
  42105. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42106. }
  42107. }
  42108. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42109. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  42110. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42111. } else if ( this.isFilteredTexture( texture ) ) {
  42112. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42113. } else {
  42114. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  42115. }
  42116. }
  42117. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42118. this._include( 'biquadraticTexture' );
  42119. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  42120. }
  42121. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42122. this._include( 'repeatWrapping' );
  42123. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  42124. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  42125. }
  42126. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42127. if ( depthSnippet ) {
  42128. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  42129. } else {
  42130. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42131. }
  42132. }
  42133. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42134. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42135. }
  42136. isUnfilterable( texture ) {
  42137. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  42138. }
  42139. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42140. let snippet = null;
  42141. if ( texture.isVideoTexture === true ) {
  42142. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42143. } else if ( this.isUnfilterable( texture ) ) {
  42144. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  42145. } else {
  42146. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42147. }
  42148. return snippet;
  42149. }
  42150. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42151. if ( shaderStage === 'fragment' ) {
  42152. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42153. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42154. } else {
  42155. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42156. }
  42157. }
  42158. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42159. if ( shaderStage === 'fragment' ) {
  42160. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42161. } else {
  42162. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42163. }
  42164. }
  42165. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42166. let snippet = null;
  42167. if ( texture.isVideoTexture === true ) {
  42168. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42169. } else {
  42170. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42171. }
  42172. return snippet;
  42173. }
  42174. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42175. if ( shaderStage === 'fragment' ) {
  42176. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42177. } else {
  42178. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42179. }
  42180. }
  42181. getPropertyName( node, shaderStage = this.shaderStage ) {
  42182. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42183. if ( shaderStage === 'vertex' ) {
  42184. return `varyings.${ node.name }`;
  42185. }
  42186. } else if ( node.isNodeUniform === true ) {
  42187. const name = node.name;
  42188. const type = node.type;
  42189. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42190. return name;
  42191. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  42192. return `NodeBuffer_${ node.id }.${name}`;
  42193. } else {
  42194. return node.groupNode.name + '.' + name;
  42195. }
  42196. }
  42197. return super.getPropertyName( node );
  42198. }
  42199. getOutputStructName() {
  42200. return 'output';
  42201. }
  42202. _getUniformGroupCount( shaderStage ) {
  42203. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42204. }
  42205. getFunctionOperator( op ) {
  42206. const fnOp = wgslFnOpLib[ op ];
  42207. if ( fnOp !== undefined ) {
  42208. this._include( fnOp );
  42209. return fnOp;
  42210. }
  42211. return null;
  42212. }
  42213. getStorageAccess( node ) {
  42214. if ( node.isStorageTextureNode ) {
  42215. switch ( node.access ) {
  42216. case GPUStorageTextureAccess.ReadOnly:
  42217. return 'read';
  42218. case GPUStorageTextureAccess.WriteOnly:
  42219. return 'write';
  42220. default:
  42221. return 'read_write';
  42222. }
  42223. } else {
  42224. switch ( node.access ) {
  42225. case GPUBufferBindingType.Storage:
  42226. return 'read_write';
  42227. case GPUBufferBindingType.ReadOnlyStorage:
  42228. return 'read';
  42229. default:
  42230. return 'write';
  42231. }
  42232. }
  42233. }
  42234. getUniformFromNode( node, type, shaderStage, name = null ) {
  42235. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42236. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42237. if ( nodeData.uniformGPU === undefined ) {
  42238. let uniformGPU;
  42239. const group = node.groupNode;
  42240. const groupName = group.name;
  42241. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42242. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42243. let texture = null;
  42244. if ( type === 'texture' || type === 'storageTexture' ) {
  42245. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42246. } else if ( type === 'cubeTexture' ) {
  42247. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42248. } else if ( type === 'texture3D' ) {
  42249. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42250. }
  42251. texture.store = node.isStorageTextureNode === true;
  42252. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42253. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  42254. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  42255. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42256. bindings.push( sampler, texture );
  42257. uniformGPU = [ sampler, texture ];
  42258. } else {
  42259. bindings.push( texture );
  42260. uniformGPU = [ texture ];
  42261. }
  42262. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  42263. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  42264. const buffer = new bufferClass( node, group );
  42265. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42266. bindings.push( buffer );
  42267. uniformGPU = buffer;
  42268. } else {
  42269. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42270. let uniformsGroup = uniformsStage[ groupName ];
  42271. if ( uniformsGroup === undefined ) {
  42272. uniformsGroup = new NodeUniformsGroup( groupName, group );
  42273. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42274. uniformsStage[ groupName ] = uniformsGroup;
  42275. bindings.push( uniformsGroup );
  42276. }
  42277. uniformGPU = this.getNodeUniform( uniformNode, type );
  42278. uniformsGroup.addUniform( uniformGPU );
  42279. }
  42280. nodeData.uniformGPU = uniformGPU;
  42281. }
  42282. return uniformNode;
  42283. }
  42284. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  42285. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  42286. if ( map.has( name ) === false ) {
  42287. map.set( name, {
  42288. name,
  42289. property,
  42290. type
  42291. } );
  42292. }
  42293. return property;
  42294. }
  42295. getVertexIndex() {
  42296. if ( this.shaderStage === 'vertex' ) {
  42297. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  42298. }
  42299. return 'vertexIndex';
  42300. }
  42301. buildFunctionCode( shaderNode ) {
  42302. const layout = shaderNode.layout;
  42303. const flowData = this.flowShaderNode( shaderNode );
  42304. const parameters = [];
  42305. for ( const input of layout.inputs ) {
  42306. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  42307. }
  42308. //
  42309. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  42310. ${ flowData.vars }
  42311. ${ flowData.code }
  42312. return ${ flowData.result };
  42313. }`;
  42314. //
  42315. return code;
  42316. }
  42317. getInstanceIndex() {
  42318. if ( this.shaderStage === 'vertex' ) {
  42319. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  42320. }
  42321. return 'instanceIndex';
  42322. }
  42323. getDrawIndex() {
  42324. return null;
  42325. }
  42326. getFrontFacing() {
  42327. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  42328. }
  42329. getFragCoord() {
  42330. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  42331. }
  42332. getFragDepth() {
  42333. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  42334. }
  42335. isFlipY() {
  42336. return false;
  42337. }
  42338. enableDirective( name, shaderStage = this.shaderStage ) {
  42339. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = [] );
  42340. stage.push( name );
  42341. }
  42342. getDirectives( shaderStage ) {
  42343. const snippets = [];
  42344. const directives = this.directives[ shaderStage ];
  42345. if ( directives !== undefined ) {
  42346. for ( const directive of directives ) {
  42347. snippets.push( `enable ${directive}` );
  42348. }
  42349. }
  42350. return snippets.join( '\n' );
  42351. }
  42352. enableClipDistances() {
  42353. this.enableDirective( 'clip_distances' );
  42354. }
  42355. enableShaderF16() {
  42356. this.enableDirective( 'f16' );
  42357. }
  42358. enableDualSourceBlending() {
  42359. this.enableDirective( 'dual_source_blending' );
  42360. }
  42361. getBuiltins( shaderStage ) {
  42362. const snippets = [];
  42363. const builtins = this.builtins[ shaderStage ];
  42364. if ( builtins !== undefined ) {
  42365. for ( const { name, property, type } of builtins.values() ) {
  42366. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  42367. }
  42368. }
  42369. return snippets.join( ',\n\t' );
  42370. }
  42371. getAttributes( shaderStage ) {
  42372. const snippets = [];
  42373. if ( shaderStage === 'compute' ) {
  42374. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  42375. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  42376. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  42377. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  42378. }
  42379. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42380. const builtins = this.getBuiltins( 'attribute' );
  42381. if ( builtins ) snippets.push( builtins );
  42382. const attributes = this.getAttributesArray();
  42383. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  42384. const attribute = attributes[ index ];
  42385. const name = attribute.name;
  42386. const type = this.getType( attribute.type );
  42387. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  42388. }
  42389. }
  42390. return snippets.join( ',\n\t' );
  42391. }
  42392. getStructMembers( struct ) {
  42393. const snippets = [];
  42394. const members = struct.getMemberTypes();
  42395. for ( let i = 0; i < members.length; i ++ ) {
  42396. const member = members[ i ];
  42397. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  42398. }
  42399. const builtins = this.getBuiltins( 'output' );
  42400. if ( builtins ) snippets.push( builtins );
  42401. return snippets.join( ',\n' );
  42402. }
  42403. getStructs( shaderStage ) {
  42404. const snippets = [];
  42405. const structs = this.structs[ shaderStage ];
  42406. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  42407. const struct = structs[ index ];
  42408. const name = struct.name;
  42409. let snippet = `\struct ${ name } {\n`;
  42410. snippet += this.getStructMembers( struct );
  42411. snippet += '\n}';
  42412. snippets.push( snippet );
  42413. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  42414. }
  42415. return snippets.join( '\n\n' );
  42416. }
  42417. getVar( type, name ) {
  42418. return `var ${ name } : ${ this.getType( type ) }`;
  42419. }
  42420. getVars( shaderStage ) {
  42421. const snippets = [];
  42422. const vars = this.vars[ shaderStage ];
  42423. if ( vars !== undefined ) {
  42424. for ( const variable of vars ) {
  42425. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  42426. }
  42427. }
  42428. return `\n${ snippets.join( '\n' ) }\n`;
  42429. }
  42430. getVaryings( shaderStage ) {
  42431. const snippets = [];
  42432. if ( shaderStage === 'vertex' ) {
  42433. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  42434. }
  42435. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  42436. const varyings = this.varyings;
  42437. const vars = this.vars[ shaderStage ];
  42438. for ( let index = 0; index < varyings.length; index ++ ) {
  42439. const varying = varyings[ index ];
  42440. if ( varying.needsInterpolation ) {
  42441. let attributesSnippet = `@location( ${index} )`;
  42442. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  42443. attributesSnippet += ' @interpolate( flat )';
  42444. }
  42445. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  42446. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  42447. vars.push( varying );
  42448. }
  42449. }
  42450. }
  42451. const builtins = this.getBuiltins( shaderStage );
  42452. if ( builtins ) snippets.push( builtins );
  42453. const code = snippets.join( ',\n\t' );
  42454. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  42455. }
  42456. getUniforms( shaderStage ) {
  42457. const uniforms = this.uniforms[ shaderStage ];
  42458. const bindingSnippets = [];
  42459. const bufferSnippets = [];
  42460. const structSnippets = [];
  42461. const uniformGroups = {};
  42462. for ( const uniform of uniforms ) {
  42463. const groundName = uniform.groupNode.name;
  42464. const uniformIndexes = this.bindingsIndexes[ groundName ];
  42465. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  42466. const texture = uniform.node.value;
  42467. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  42468. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  42469. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  42470. } else {
  42471. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  42472. }
  42473. }
  42474. let textureType;
  42475. let multisampled = '';
  42476. if ( texture.isMultisampleRenderTargetTexture === true ) {
  42477. multisampled = '_multisampled';
  42478. }
  42479. if ( texture.isCubeTexture === true ) {
  42480. textureType = 'texture_cube<f32>';
  42481. } else if ( texture.isDataArrayTexture === true ) {
  42482. textureType = 'texture_2d_array<f32>';
  42483. } else if ( texture.isDepthTexture === true ) {
  42484. textureType = `texture_depth${multisampled}_2d`;
  42485. } else if ( texture.isVideoTexture === true ) {
  42486. textureType = 'texture_external';
  42487. } else if ( texture.isData3DTexture === true ) {
  42488. textureType = 'texture_3d<f32>';
  42489. } else if ( uniform.node.isStorageTextureNode === true ) {
  42490. const format = getFormat( texture );
  42491. const access = this.getStorageAccess( uniform.node );
  42492. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  42493. } else {
  42494. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  42495. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  42496. }
  42497. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  42498. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  42499. const bufferNode = uniform.node;
  42500. const bufferType = this.getType( bufferNode.bufferType );
  42501. const bufferCount = bufferNode.bufferCount;
  42502. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  42503. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  42504. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  42505. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  42506. } else {
  42507. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  42508. const groupName = uniform.groupNode.name;
  42509. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  42510. index: uniformIndexes.binding ++,
  42511. id: uniformIndexes.group,
  42512. snippets: []
  42513. } );
  42514. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  42515. }
  42516. }
  42517. for ( const name in uniformGroups ) {
  42518. const group = uniformGroups[ name ];
  42519. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  42520. }
  42521. let code = bindingSnippets.join( '\n' );
  42522. code += bufferSnippets.join( '\n' );
  42523. code += structSnippets.join( '\n' );
  42524. return code;
  42525. }
  42526. buildCode() {
  42527. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  42528. for ( const shaderStage in shadersData ) {
  42529. const stageData = shadersData[ shaderStage ];
  42530. stageData.uniforms = this.getUniforms( shaderStage );
  42531. stageData.attributes = this.getAttributes( shaderStage );
  42532. stageData.varyings = this.getVaryings( shaderStage );
  42533. stageData.structs = this.getStructs( shaderStage );
  42534. stageData.vars = this.getVars( shaderStage );
  42535. stageData.codes = this.getCodes( shaderStage );
  42536. stageData.directives = this.getDirectives( shaderStage );
  42537. //
  42538. let flow = '// code\n\n';
  42539. flow += this.flowCode[ shaderStage ];
  42540. const flowNodes = this.flowNodes[ shaderStage ];
  42541. const mainNode = flowNodes[ flowNodes.length - 1 ];
  42542. const outputNode = mainNode.outputNode;
  42543. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  42544. for ( const node of flowNodes ) {
  42545. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  42546. const slotName = node.name;
  42547. if ( slotName ) {
  42548. if ( flow.length > 0 ) flow += '\n';
  42549. flow += `\t// flow -> ${ slotName }\n\t`;
  42550. }
  42551. flow += `${ flowSlotData.code }\n\t`;
  42552. if ( node === mainNode && shaderStage !== 'compute' ) {
  42553. flow += '// result\n\n\t';
  42554. if ( shaderStage === 'vertex' ) {
  42555. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  42556. } else if ( shaderStage === 'fragment' ) {
  42557. if ( isOutputStruct ) {
  42558. stageData.returnType = outputNode.nodeType;
  42559. flow += `return ${ flowSlotData.result };`;
  42560. } else {
  42561. let structSnippet = '\t@location(0) color: vec4<f32>';
  42562. const builtins = this.getBuiltins( 'output' );
  42563. if ( builtins ) structSnippet += ',\n\t' + builtins;
  42564. stageData.returnType = 'OutputStruct';
  42565. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  42566. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  42567. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  42568. }
  42569. }
  42570. }
  42571. }
  42572. stageData.flow = flow;
  42573. }
  42574. if ( this.material !== null ) {
  42575. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  42576. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  42577. } else {
  42578. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  42579. }
  42580. }
  42581. getMethod( method, output = null ) {
  42582. let wgslMethod;
  42583. if ( output !== null ) {
  42584. wgslMethod = this._getWGSLMethod( method + '_' + output );
  42585. }
  42586. if ( wgslMethod === undefined ) {
  42587. wgslMethod = this._getWGSLMethod( method );
  42588. }
  42589. return wgslMethod || method;
  42590. }
  42591. getType( type ) {
  42592. return wgslTypeLib[ type ] || type;
  42593. }
  42594. isAvailable( name ) {
  42595. let result = supports[ name ];
  42596. if ( result === undefined ) {
  42597. if ( name === 'float32Filterable' ) {
  42598. result = this.renderer.hasFeature( 'float32-filterable' );
  42599. }
  42600. supports[ name ] = result;
  42601. }
  42602. return result;
  42603. }
  42604. _getWGSLMethod( method ) {
  42605. if ( wgslPolyfill[ method ] !== undefined ) {
  42606. this._include( method );
  42607. }
  42608. return wgslMethods[ method ];
  42609. }
  42610. _include( name ) {
  42611. const codeNode = wgslPolyfill[ name ];
  42612. codeNode.build( this );
  42613. if ( this.currentFunctionNode !== null ) {
  42614. this.currentFunctionNode.includes.push( codeNode );
  42615. }
  42616. return codeNode;
  42617. }
  42618. _getWGSLVertexCode( shaderData ) {
  42619. return `${ this.getSignature() }
  42620. // directives
  42621. ${shaderData.directives};
  42622. // uniforms
  42623. ${shaderData.uniforms}
  42624. // varyings
  42625. ${shaderData.varyings}
  42626. var<private> varyings : VaryingsStruct;
  42627. // codes
  42628. ${shaderData.codes}
  42629. @vertex
  42630. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  42631. // vars
  42632. ${shaderData.vars}
  42633. // flow
  42634. ${shaderData.flow}
  42635. return varyings;
  42636. }
  42637. `;
  42638. }
  42639. _getWGSLFragmentCode( shaderData ) {
  42640. return `${ this.getSignature() }
  42641. diagnostic( off, derivative_uniformity );
  42642. // uniforms
  42643. ${shaderData.uniforms}
  42644. // structs
  42645. ${shaderData.structs}
  42646. // codes
  42647. ${shaderData.codes}
  42648. @fragment
  42649. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  42650. // vars
  42651. ${shaderData.vars}
  42652. // flow
  42653. ${shaderData.flow}
  42654. }
  42655. `;
  42656. }
  42657. _getWGSLComputeCode( shaderData, workgroupSize ) {
  42658. return `${ this.getSignature() }
  42659. // directives
  42660. ${shaderData.directives}
  42661. // system
  42662. var<private> instanceIndex : u32;
  42663. // uniforms
  42664. ${shaderData.uniforms}
  42665. // codes
  42666. ${shaderData.codes}
  42667. @compute @workgroup_size( ${workgroupSize} )
  42668. fn main( ${shaderData.attributes} ) {
  42669. // system
  42670. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  42671. // vars
  42672. ${shaderData.vars}
  42673. // flow
  42674. ${shaderData.flow}
  42675. }
  42676. `;
  42677. }
  42678. _getWGSLStruct( name, vars ) {
  42679. return `
  42680. struct ${name} {
  42681. ${vars}
  42682. };`;
  42683. }
  42684. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  42685. const structName = name + 'Struct';
  42686. const structSnippet = this._getWGSLStruct( structName, vars );
  42687. return `${structSnippet}
  42688. @binding( ${binding} ) @group( ${group} )
  42689. var<${access}> ${name} : ${structName};`;
  42690. }
  42691. }
  42692. class WebGPUUtils {
  42693. constructor( backend ) {
  42694. this.backend = backend;
  42695. }
  42696. getCurrentDepthStencilFormat( renderContext ) {
  42697. let format;
  42698. if ( renderContext.depthTexture !== null ) {
  42699. format = this.getTextureFormatGPU( renderContext.depthTexture );
  42700. } else if ( renderContext.depth && renderContext.stencil ) {
  42701. format = GPUTextureFormat.Depth24PlusStencil8;
  42702. } else if ( renderContext.depth ) {
  42703. format = GPUTextureFormat.Depth24Plus;
  42704. }
  42705. return format;
  42706. }
  42707. getTextureFormatGPU( texture ) {
  42708. return this.backend.get( texture ).texture.format;
  42709. }
  42710. getCurrentColorFormat( renderContext ) {
  42711. let format;
  42712. if ( renderContext.textures !== null ) {
  42713. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  42714. } else {
  42715. format = GPUTextureFormat.BGRA8Unorm; // default context format
  42716. }
  42717. return format;
  42718. }
  42719. getCurrentColorSpace( renderContext ) {
  42720. if ( renderContext.textures !== null ) {
  42721. return renderContext.textures[ 0 ].colorSpace;
  42722. }
  42723. return this.backend.renderer.outputColorSpace;
  42724. }
  42725. getPrimitiveTopology( object, material ) {
  42726. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  42727. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  42728. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  42729. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  42730. }
  42731. getSampleCount( sampleCount ) {
  42732. let count = 1;
  42733. if ( sampleCount > 1 ) {
  42734. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  42735. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  42736. if ( count === 2 ) {
  42737. count = 4;
  42738. }
  42739. }
  42740. return count;
  42741. }
  42742. getSampleCountRenderContext( renderContext ) {
  42743. if ( renderContext.textures !== null ) {
  42744. return this.getSampleCount( renderContext.sampleCount );
  42745. }
  42746. return this.getSampleCount( this.backend.renderer.samples );
  42747. }
  42748. }
  42749. const typedArraysToVertexFormatPrefix = new Map( [
  42750. [ Int8Array, [ 'sint8', 'snorm8' ]],
  42751. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  42752. [ Int16Array, [ 'sint16', 'snorm16' ]],
  42753. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  42754. [ Int32Array, [ 'sint32', 'snorm32' ]],
  42755. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  42756. [ Float32Array, [ 'float32', ]],
  42757. ] );
  42758. const typedAttributeToVertexFormatPrefix = new Map( [
  42759. [ Float16BufferAttribute, [ 'float16', ]],
  42760. ] );
  42761. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  42762. [ Int32Array, 'sint32' ],
  42763. [ Int16Array, 'sint32' ], // patch for INT16
  42764. [ Uint32Array, 'uint32' ],
  42765. [ Uint16Array, 'uint32' ], // patch for UINT16
  42766. [ Float32Array, 'float32' ]
  42767. ] );
  42768. class WebGPUAttributeUtils {
  42769. constructor( backend ) {
  42770. this.backend = backend;
  42771. }
  42772. createAttribute( attribute, usage ) {
  42773. const bufferAttribute = this._getBufferAttribute( attribute );
  42774. const backend = this.backend;
  42775. const bufferData = backend.get( bufferAttribute );
  42776. let buffer = bufferData.buffer;
  42777. if ( buffer === undefined ) {
  42778. const device = backend.device;
  42779. let array = bufferAttribute.array;
  42780. // patch for INT16 and UINT16
  42781. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  42782. const tempArray = new Uint32Array( array.length );
  42783. for ( let i = 0; i < array.length; i ++ ) {
  42784. tempArray[ i ] = array[ i ];
  42785. }
  42786. array = tempArray;
  42787. }
  42788. bufferAttribute.array = array;
  42789. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  42790. array = new array.constructor( bufferAttribute.count * 4 );
  42791. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  42792. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  42793. }
  42794. // Update BufferAttribute
  42795. bufferAttribute.itemSize = 4;
  42796. bufferAttribute.array = array;
  42797. }
  42798. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  42799. buffer = device.createBuffer( {
  42800. label: bufferAttribute.name,
  42801. size: size,
  42802. usage: usage,
  42803. mappedAtCreation: true
  42804. } );
  42805. new array.constructor( buffer.getMappedRange() ).set( array );
  42806. buffer.unmap();
  42807. bufferData.buffer = buffer;
  42808. }
  42809. }
  42810. updateAttribute( attribute ) {
  42811. const bufferAttribute = this._getBufferAttribute( attribute );
  42812. const backend = this.backend;
  42813. const device = backend.device;
  42814. const buffer = backend.get( bufferAttribute ).buffer;
  42815. const array = bufferAttribute.array;
  42816. const updateRanges = bufferAttribute.updateRanges;
  42817. if ( updateRanges.length === 0 ) {
  42818. // Not using update ranges
  42819. device.queue.writeBuffer(
  42820. buffer,
  42821. 0,
  42822. array,
  42823. 0
  42824. );
  42825. } else {
  42826. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42827. const range = updateRanges[ i ];
  42828. device.queue.writeBuffer(
  42829. buffer,
  42830. 0,
  42831. array,
  42832. range.start * array.BYTES_PER_ELEMENT,
  42833. range.count * array.BYTES_PER_ELEMENT
  42834. );
  42835. }
  42836. bufferAttribute.clearUpdateRanges();
  42837. }
  42838. }
  42839. createShaderVertexBuffers( renderObject ) {
  42840. const attributes = renderObject.getAttributes();
  42841. const vertexBuffers = new Map();
  42842. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  42843. const geometryAttribute = attributes[ slot ];
  42844. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  42845. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  42846. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  42847. if ( vertexBufferLayout === undefined ) {
  42848. let arrayStride, stepMode;
  42849. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  42850. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  42851. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  42852. } else {
  42853. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  42854. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  42855. }
  42856. // patch for INT16 and UINT16
  42857. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  42858. arrayStride = 4;
  42859. }
  42860. vertexBufferLayout = {
  42861. arrayStride,
  42862. attributes: [],
  42863. stepMode
  42864. };
  42865. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  42866. }
  42867. const format = this._getVertexFormat( geometryAttribute );
  42868. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  42869. vertexBufferLayout.attributes.push( {
  42870. shaderLocation: slot,
  42871. offset,
  42872. format
  42873. } );
  42874. }
  42875. return Array.from( vertexBuffers.values() );
  42876. }
  42877. destroyAttribute( attribute ) {
  42878. const backend = this.backend;
  42879. const data = backend.get( this._getBufferAttribute( attribute ) );
  42880. data.buffer.destroy();
  42881. backend.delete( attribute );
  42882. }
  42883. async getArrayBufferAsync( attribute ) {
  42884. const backend = this.backend;
  42885. const device = backend.device;
  42886. const data = backend.get( this._getBufferAttribute( attribute ) );
  42887. const bufferGPU = data.buffer;
  42888. const size = bufferGPU.size;
  42889. let readBufferGPU = data.readBuffer;
  42890. let needsUnmap = true;
  42891. if ( readBufferGPU === undefined ) {
  42892. readBufferGPU = device.createBuffer( {
  42893. label: attribute.name,
  42894. size,
  42895. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42896. } );
  42897. needsUnmap = false;
  42898. data.readBuffer = readBufferGPU;
  42899. }
  42900. const cmdEncoder = device.createCommandEncoder( {} );
  42901. cmdEncoder.copyBufferToBuffer(
  42902. bufferGPU,
  42903. 0,
  42904. readBufferGPU,
  42905. 0,
  42906. size
  42907. );
  42908. if ( needsUnmap ) readBufferGPU.unmap();
  42909. const gpuCommands = cmdEncoder.finish();
  42910. device.queue.submit( [ gpuCommands ] );
  42911. await readBufferGPU.mapAsync( GPUMapMode.READ );
  42912. const arrayBuffer = readBufferGPU.getMappedRange();
  42913. return arrayBuffer;
  42914. }
  42915. _getVertexFormat( geometryAttribute ) {
  42916. const { itemSize, normalized } = geometryAttribute;
  42917. const ArrayType = geometryAttribute.array.constructor;
  42918. const AttributeType = geometryAttribute.constructor;
  42919. let format;
  42920. if ( itemSize == 1 ) {
  42921. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  42922. } else {
  42923. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  42924. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  42925. if ( prefix ) {
  42926. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  42927. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  42928. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  42929. if ( paddedItemSize % 1 ) {
  42930. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  42931. }
  42932. format = `${prefix}x${paddedItemSize}`;
  42933. }
  42934. }
  42935. if ( ! format ) {
  42936. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  42937. }
  42938. return format;
  42939. }
  42940. _getBufferAttribute( attribute ) {
  42941. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42942. return attribute;
  42943. }
  42944. }
  42945. class WebGPUBindingUtils {
  42946. constructor( backend ) {
  42947. this.backend = backend;
  42948. }
  42949. createBindingsLayout( bindGroup ) {
  42950. const backend = this.backend;
  42951. const device = backend.device;
  42952. const entries = [];
  42953. let index = 0;
  42954. for ( const binding of bindGroup.bindings ) {
  42955. const bindingGPU = {
  42956. binding: index ++,
  42957. visibility: binding.visibility
  42958. };
  42959. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  42960. const buffer = {}; // GPUBufferBindingLayout
  42961. if ( binding.isStorageBuffer ) {
  42962. buffer.type = binding.access;
  42963. }
  42964. bindingGPU.buffer = buffer;
  42965. } else if ( binding.isSampler ) {
  42966. const sampler = {}; // GPUSamplerBindingLayout
  42967. if ( binding.texture.isDepthTexture ) {
  42968. if ( binding.texture.compareFunction !== null ) {
  42969. sampler.type = 'comparison';
  42970. }
  42971. }
  42972. bindingGPU.sampler = sampler;
  42973. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  42974. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  42975. } else if ( binding.isSampledTexture && binding.store ) {
  42976. const format = this.backend.get( binding.texture ).texture.format;
  42977. const access = binding.access;
  42978. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  42979. } else if ( binding.isSampledTexture ) {
  42980. const texture = {}; // GPUTextureBindingLayout
  42981. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  42982. texture.multisampled = true;
  42983. }
  42984. if ( binding.texture.isDepthTexture ) {
  42985. texture.sampleType = GPUTextureSampleType.Depth;
  42986. } else if ( binding.texture.isDataTexture ) {
  42987. const type = binding.texture.type;
  42988. if ( type === IntType ) {
  42989. texture.sampleType = GPUTextureSampleType.SInt;
  42990. } else if ( type === UnsignedIntType ) {
  42991. texture.sampleType = GPUTextureSampleType.UInt;
  42992. } else if ( type === FloatType ) {
  42993. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  42994. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  42995. }
  42996. }
  42997. if ( binding.isSampledCubeTexture ) {
  42998. texture.viewDimension = GPUTextureViewDimension.Cube;
  42999. } else if ( binding.texture.isDataArrayTexture ) {
  43000. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  43001. } else if ( binding.isSampledTexture3D ) {
  43002. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  43003. }
  43004. bindingGPU.texture = texture;
  43005. } else {
  43006. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  43007. }
  43008. entries.push( bindingGPU );
  43009. }
  43010. return device.createBindGroupLayout( { entries } );
  43011. }
  43012. createBindings( bindGroup ) {
  43013. const backend = this.backend;
  43014. const bindingsData = backend.get( bindGroup );
  43015. // setup (static) binding layout and (dynamic) binding group
  43016. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  43017. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  43018. bindingsData.layout = bindLayoutGPU;
  43019. bindingsData.group = bindGroupGPU;
  43020. }
  43021. updateBinding( binding ) {
  43022. const backend = this.backend;
  43023. const device = backend.device;
  43024. const buffer = binding.buffer;
  43025. const bufferGPU = backend.get( binding ).buffer;
  43026. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  43027. }
  43028. createBindGroup( bindGroup, layoutGPU ) {
  43029. const backend = this.backend;
  43030. const device = backend.device;
  43031. let bindingPoint = 0;
  43032. const entriesGPU = [];
  43033. for ( const binding of bindGroup.bindings ) {
  43034. if ( binding.isUniformBuffer ) {
  43035. const bindingData = backend.get( binding );
  43036. if ( bindingData.buffer === undefined ) {
  43037. const byteLength = binding.byteLength;
  43038. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  43039. const bufferGPU = device.createBuffer( {
  43040. label: 'bindingBuffer_' + binding.name,
  43041. size: byteLength,
  43042. usage: usage
  43043. } );
  43044. bindingData.buffer = bufferGPU;
  43045. }
  43046. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43047. } else if ( binding.isStorageBuffer ) {
  43048. const bindingData = backend.get( binding );
  43049. if ( bindingData.buffer === undefined ) {
  43050. const attribute = binding.attribute;
  43051. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  43052. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  43053. bindingData.buffer = backend.get( attribute ).buffer;
  43054. }
  43055. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43056. } else if ( binding.isSampler ) {
  43057. const textureGPU = backend.get( binding.texture );
  43058. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  43059. } else if ( binding.isSampledTexture ) {
  43060. const textureData = backend.get( binding.texture );
  43061. let dimensionViewGPU;
  43062. if ( binding.isSampledCubeTexture ) {
  43063. dimensionViewGPU = GPUTextureViewDimension.Cube;
  43064. } else if ( binding.isSampledTexture3D ) {
  43065. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  43066. } else if ( binding.texture.isDataArrayTexture ) {
  43067. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  43068. } else {
  43069. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  43070. }
  43071. let resourceGPU;
  43072. if ( textureData.externalTexture !== undefined ) {
  43073. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  43074. } else {
  43075. const aspectGPU = GPUTextureAspect.All;
  43076. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  43077. }
  43078. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  43079. }
  43080. bindingPoint ++;
  43081. }
  43082. return device.createBindGroup( {
  43083. label: 'bindGroup_' + bindGroup.name,
  43084. layout: layoutGPU,
  43085. entries: entriesGPU
  43086. } );
  43087. }
  43088. }
  43089. class WebGPUPipelineUtils {
  43090. constructor( backend ) {
  43091. this.backend = backend;
  43092. }
  43093. _getSampleCount( renderObjectContext ) {
  43094. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  43095. }
  43096. createRenderPipeline( renderObject, promises ) {
  43097. const { object, material, geometry, pipeline } = renderObject;
  43098. const { vertexProgram, fragmentProgram } = pipeline;
  43099. const backend = this.backend;
  43100. const device = backend.device;
  43101. const utils = backend.utils;
  43102. const pipelineData = backend.get( pipeline );
  43103. // bind group layouts
  43104. const bindGroupLayouts = [];
  43105. for ( const bindGroup of renderObject.getBindings() ) {
  43106. const bindingsData = backend.get( bindGroup );
  43107. bindGroupLayouts.push( bindingsData.layout );
  43108. }
  43109. // vertex buffers
  43110. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  43111. // blending
  43112. let blending;
  43113. if ( material.transparent === true && material.blending !== NoBlending ) {
  43114. blending = this._getBlending( material );
  43115. }
  43116. // stencil
  43117. let stencilFront = {};
  43118. if ( material.stencilWrite === true ) {
  43119. stencilFront = {
  43120. compare: this._getStencilCompare( material ),
  43121. failOp: this._getStencilOperation( material.stencilFail ),
  43122. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  43123. passOp: this._getStencilOperation( material.stencilZPass )
  43124. };
  43125. }
  43126. const colorWriteMask = this._getColorWriteMask( material );
  43127. const targets = [];
  43128. if ( renderObject.context.textures !== null ) {
  43129. const textures = renderObject.context.textures;
  43130. for ( let i = 0; i < textures.length; i ++ ) {
  43131. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  43132. targets.push( {
  43133. format: colorFormat,
  43134. blend: blending,
  43135. writeMask: colorWriteMask
  43136. } );
  43137. }
  43138. } else {
  43139. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43140. targets.push( {
  43141. format: colorFormat,
  43142. blend: blending,
  43143. writeMask: colorWriteMask
  43144. } );
  43145. }
  43146. const vertexModule = backend.get( vertexProgram ).module;
  43147. const fragmentModule = backend.get( fragmentProgram ).module;
  43148. const primitiveState = this._getPrimitiveState( object, geometry, material );
  43149. const depthCompare = this._getDepthCompare( material );
  43150. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43151. const sampleCount = this._getSampleCount( renderObject.context );
  43152. const pipelineDescriptor = {
  43153. label: 'renderPipeline',
  43154. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  43155. fragment: Object.assign( {}, fragmentModule, { targets } ),
  43156. primitive: primitiveState,
  43157. depthStencil: {
  43158. format: depthStencilFormat,
  43159. depthWriteEnabled: material.depthWrite,
  43160. depthCompare: depthCompare,
  43161. stencilFront: stencilFront,
  43162. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  43163. stencilReadMask: material.stencilFuncMask,
  43164. stencilWriteMask: material.stencilWriteMask
  43165. },
  43166. multisample: {
  43167. count: sampleCount,
  43168. alphaToCoverageEnabled: material.alphaToCoverage
  43169. },
  43170. layout: device.createPipelineLayout( {
  43171. bindGroupLayouts
  43172. } )
  43173. };
  43174. if ( promises === null ) {
  43175. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  43176. } else {
  43177. const p = new Promise( ( resolve /*, reject*/ ) => {
  43178. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  43179. pipelineData.pipeline = pipeline;
  43180. resolve();
  43181. } );
  43182. } );
  43183. promises.push( p );
  43184. }
  43185. }
  43186. createBundleEncoder( renderContext, renderObject ) {
  43187. const backend = this.backend;
  43188. const { utils, device } = backend;
  43189. const renderContextData = backend.get( renderContext );
  43190. const renderObjectData = backend.get( renderObject );
  43191. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  43192. const colorFormat = utils.getCurrentColorFormat( renderContext );
  43193. const sampleCount = this._getSampleCount( renderObject.context );
  43194. const descriptor = {
  43195. label: 'renderBundleEncoder',
  43196. colorFormats: [ colorFormat ],
  43197. depthStencilFormat,
  43198. sampleCount
  43199. };
  43200. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  43201. renderObjectData.bundleEncoder = bundleEncoder;
  43202. renderContextData.currentSets = { attributes: {} };
  43203. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  43204. return bundleEncoder;
  43205. }
  43206. createComputePipeline( pipeline, bindings ) {
  43207. const backend = this.backend;
  43208. const device = backend.device;
  43209. const computeProgram = backend.get( pipeline.computeProgram ).module;
  43210. const pipelineGPU = backend.get( pipeline );
  43211. // bind group layouts
  43212. const bindGroupLayouts = [];
  43213. for ( const bindingsGroup of bindings ) {
  43214. const bindingsData = backend.get( bindingsGroup );
  43215. bindGroupLayouts.push( bindingsData.layout );
  43216. }
  43217. pipelineGPU.pipeline = device.createComputePipeline( {
  43218. compute: computeProgram,
  43219. layout: device.createPipelineLayout( {
  43220. bindGroupLayouts
  43221. } )
  43222. } );
  43223. }
  43224. _getBlending( material ) {
  43225. let color, alpha;
  43226. const blending = material.blending;
  43227. const blendSrc = material.blendSrc;
  43228. const blendDst = material.blendDst;
  43229. const blendEquation = material.blendEquation;
  43230. if ( blending === CustomBlending ) {
  43231. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  43232. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  43233. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  43234. color = {
  43235. srcFactor: this._getBlendFactor( blendSrc ),
  43236. dstFactor: this._getBlendFactor( blendDst ),
  43237. operation: this._getBlendOperation( blendEquation )
  43238. };
  43239. alpha = {
  43240. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  43241. dstFactor: this._getBlendFactor( blendDstAlpha ),
  43242. operation: this._getBlendOperation( blendEquationAlpha )
  43243. };
  43244. } else {
  43245. const premultipliedAlpha = material.premultipliedAlpha;
  43246. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  43247. color = {
  43248. srcFactor: srcRGB,
  43249. dstFactor: dstRGB,
  43250. operation: GPUBlendOperation.Add
  43251. };
  43252. alpha = {
  43253. srcFactor: srcAlpha,
  43254. dstFactor: dstAlpha,
  43255. operation: GPUBlendOperation.Add
  43256. };
  43257. };
  43258. if ( premultipliedAlpha ) {
  43259. switch ( blending ) {
  43260. case NormalBlending:
  43261. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43262. break;
  43263. case AdditiveBlending:
  43264. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  43265. break;
  43266. case SubtractiveBlending:
  43267. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43268. break;
  43269. case MultiplyBlending:
  43270. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  43271. break;
  43272. }
  43273. } else {
  43274. switch ( blending ) {
  43275. case NormalBlending:
  43276. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43277. break;
  43278. case AdditiveBlending:
  43279. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  43280. break;
  43281. case SubtractiveBlending:
  43282. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43283. break;
  43284. case MultiplyBlending:
  43285. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  43286. break;
  43287. }
  43288. }
  43289. }
  43290. if ( color !== undefined && alpha !== undefined ) {
  43291. return { color, alpha };
  43292. } else {
  43293. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  43294. }
  43295. }
  43296. _getBlendFactor( blend ) {
  43297. let blendFactor;
  43298. switch ( blend ) {
  43299. case ZeroFactor:
  43300. blendFactor = GPUBlendFactor.Zero;
  43301. break;
  43302. case OneFactor:
  43303. blendFactor = GPUBlendFactor.One;
  43304. break;
  43305. case SrcColorFactor:
  43306. blendFactor = GPUBlendFactor.Src;
  43307. break;
  43308. case OneMinusSrcColorFactor:
  43309. blendFactor = GPUBlendFactor.OneMinusSrc;
  43310. break;
  43311. case SrcAlphaFactor:
  43312. blendFactor = GPUBlendFactor.SrcAlpha;
  43313. break;
  43314. case OneMinusSrcAlphaFactor:
  43315. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  43316. break;
  43317. case DstColorFactor:
  43318. blendFactor = GPUBlendFactor.Dst;
  43319. break;
  43320. case OneMinusDstColorFactor:
  43321. blendFactor = GPUBlendFactor.OneMinusDstColor;
  43322. break;
  43323. case DstAlphaFactor:
  43324. blendFactor = GPUBlendFactor.DstAlpha;
  43325. break;
  43326. case OneMinusDstAlphaFactor:
  43327. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  43328. break;
  43329. case SrcAlphaSaturateFactor:
  43330. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  43331. break;
  43332. case BlendColorFactor:
  43333. blendFactor = GPUBlendFactor.Constant;
  43334. break;
  43335. case OneMinusBlendColorFactor:
  43336. blendFactor = GPUBlendFactor.OneMinusConstant;
  43337. break;
  43338. default:
  43339. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  43340. }
  43341. return blendFactor;
  43342. }
  43343. _getStencilCompare( material ) {
  43344. let stencilCompare;
  43345. const stencilFunc = material.stencilFunc;
  43346. switch ( stencilFunc ) {
  43347. case NeverStencilFunc:
  43348. stencilCompare = GPUCompareFunction.Never;
  43349. break;
  43350. case AlwaysStencilFunc:
  43351. stencilCompare = GPUCompareFunction.Always;
  43352. break;
  43353. case LessStencilFunc:
  43354. stencilCompare = GPUCompareFunction.Less;
  43355. break;
  43356. case LessEqualStencilFunc:
  43357. stencilCompare = GPUCompareFunction.LessEqual;
  43358. break;
  43359. case EqualStencilFunc:
  43360. stencilCompare = GPUCompareFunction.Equal;
  43361. break;
  43362. case GreaterEqualStencilFunc:
  43363. stencilCompare = GPUCompareFunction.GreaterEqual;
  43364. break;
  43365. case GreaterStencilFunc:
  43366. stencilCompare = GPUCompareFunction.Greater;
  43367. break;
  43368. case NotEqualStencilFunc:
  43369. stencilCompare = GPUCompareFunction.NotEqual;
  43370. break;
  43371. default:
  43372. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  43373. }
  43374. return stencilCompare;
  43375. }
  43376. _getStencilOperation( op ) {
  43377. let stencilOperation;
  43378. switch ( op ) {
  43379. case KeepStencilOp:
  43380. stencilOperation = GPUStencilOperation.Keep;
  43381. break;
  43382. case ZeroStencilOp:
  43383. stencilOperation = GPUStencilOperation.Zero;
  43384. break;
  43385. case ReplaceStencilOp:
  43386. stencilOperation = GPUStencilOperation.Replace;
  43387. break;
  43388. case InvertStencilOp:
  43389. stencilOperation = GPUStencilOperation.Invert;
  43390. break;
  43391. case IncrementStencilOp:
  43392. stencilOperation = GPUStencilOperation.IncrementClamp;
  43393. break;
  43394. case DecrementStencilOp:
  43395. stencilOperation = GPUStencilOperation.DecrementClamp;
  43396. break;
  43397. case IncrementWrapStencilOp:
  43398. stencilOperation = GPUStencilOperation.IncrementWrap;
  43399. break;
  43400. case DecrementWrapStencilOp:
  43401. stencilOperation = GPUStencilOperation.DecrementWrap;
  43402. break;
  43403. default:
  43404. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  43405. }
  43406. return stencilOperation;
  43407. }
  43408. _getBlendOperation( blendEquation ) {
  43409. let blendOperation;
  43410. switch ( blendEquation ) {
  43411. case AddEquation:
  43412. blendOperation = GPUBlendOperation.Add;
  43413. break;
  43414. case SubtractEquation:
  43415. blendOperation = GPUBlendOperation.Subtract;
  43416. break;
  43417. case ReverseSubtractEquation:
  43418. blendOperation = GPUBlendOperation.ReverseSubtract;
  43419. break;
  43420. case MinEquation:
  43421. blendOperation = GPUBlendOperation.Min;
  43422. break;
  43423. case MaxEquation:
  43424. blendOperation = GPUBlendOperation.Max;
  43425. break;
  43426. default:
  43427. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  43428. }
  43429. return blendOperation;
  43430. }
  43431. _getPrimitiveState( object, geometry, material ) {
  43432. const descriptor = {};
  43433. const utils = this.backend.utils;
  43434. descriptor.topology = utils.getPrimitiveTopology( object, material );
  43435. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  43436. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  43437. }
  43438. switch ( material.side ) {
  43439. case FrontSide:
  43440. descriptor.frontFace = GPUFrontFace.CCW;
  43441. descriptor.cullMode = GPUCullMode.Back;
  43442. break;
  43443. case BackSide:
  43444. descriptor.frontFace = GPUFrontFace.CCW;
  43445. descriptor.cullMode = GPUCullMode.Front;
  43446. break;
  43447. case DoubleSide:
  43448. descriptor.frontFace = GPUFrontFace.CCW;
  43449. descriptor.cullMode = GPUCullMode.None;
  43450. break;
  43451. default:
  43452. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  43453. break;
  43454. }
  43455. return descriptor;
  43456. }
  43457. _getColorWriteMask( material ) {
  43458. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  43459. }
  43460. _getDepthCompare( material ) {
  43461. let depthCompare;
  43462. if ( material.depthTest === false ) {
  43463. depthCompare = GPUCompareFunction.Always;
  43464. } else {
  43465. const depthFunc = material.depthFunc;
  43466. switch ( depthFunc ) {
  43467. case NeverDepth:
  43468. depthCompare = GPUCompareFunction.Never;
  43469. break;
  43470. case AlwaysDepth:
  43471. depthCompare = GPUCompareFunction.Always;
  43472. break;
  43473. case LessDepth:
  43474. depthCompare = GPUCompareFunction.Less;
  43475. break;
  43476. case LessEqualDepth:
  43477. depthCompare = GPUCompareFunction.LessEqual;
  43478. break;
  43479. case EqualDepth:
  43480. depthCompare = GPUCompareFunction.Equal;
  43481. break;
  43482. case GreaterEqualDepth:
  43483. depthCompare = GPUCompareFunction.GreaterEqual;
  43484. break;
  43485. case GreaterDepth:
  43486. depthCompare = GPUCompareFunction.Greater;
  43487. break;
  43488. case NotEqualDepth:
  43489. depthCompare = GPUCompareFunction.NotEqual;
  43490. break;
  43491. default:
  43492. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  43493. }
  43494. }
  43495. return depthCompare;
  43496. }
  43497. }
  43498. /*// debugger tools
  43499. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  43500. //*/
  43501. //
  43502. class WebGPUBackend extends Backend {
  43503. constructor( parameters = {} ) {
  43504. super( parameters );
  43505. this.isWebGPUBackend = true;
  43506. // some parameters require default values other than "undefined"
  43507. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  43508. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  43509. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43510. this.device = null;
  43511. this.context = null;
  43512. this.colorBuffer = null;
  43513. this.defaultRenderPassdescriptor = null;
  43514. this.utils = new WebGPUUtils( this );
  43515. this.attributeUtils = new WebGPUAttributeUtils( this );
  43516. this.bindingUtils = new WebGPUBindingUtils( this );
  43517. this.pipelineUtils = new WebGPUPipelineUtils( this );
  43518. this.textureUtils = new WebGPUTextureUtils( this );
  43519. this.occludedResolveCache = new Map();
  43520. }
  43521. async init( renderer ) {
  43522. await super.init( renderer );
  43523. //
  43524. const parameters = this.parameters;
  43525. // create the device if it is not passed with parameters
  43526. let device;
  43527. if ( parameters.device === undefined ) {
  43528. const adapterOptions = {
  43529. powerPreference: parameters.powerPreference
  43530. };
  43531. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  43532. if ( adapter === null ) {
  43533. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  43534. }
  43535. // feature support
  43536. const features = Object.values( GPUFeatureName );
  43537. const supportedFeatures = [];
  43538. for ( const name of features ) {
  43539. if ( adapter.features.has( name ) ) {
  43540. supportedFeatures.push( name );
  43541. }
  43542. }
  43543. const deviceDescriptor = {
  43544. requiredFeatures: supportedFeatures,
  43545. requiredLimits: parameters.requiredLimits
  43546. };
  43547. device = await adapter.requestDevice( deviceDescriptor );
  43548. } else {
  43549. device = parameters.device;
  43550. }
  43551. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  43552. this.device = device;
  43553. this.context = context;
  43554. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  43555. this.context.configure( {
  43556. device: this.device,
  43557. format: GPUTextureFormat.BGRA8Unorm,
  43558. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  43559. alphaMode: alphaMode
  43560. } );
  43561. this.updateSize();
  43562. }
  43563. get coordinateSystem() {
  43564. return WebGPUCoordinateSystem;
  43565. }
  43566. async getArrayBufferAsync( attribute ) {
  43567. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43568. }
  43569. getContext() {
  43570. return this.context;
  43571. }
  43572. _getDefaultRenderPassDescriptor() {
  43573. let descriptor = this.defaultRenderPassdescriptor;
  43574. if ( descriptor === null ) {
  43575. const renderer = this.renderer;
  43576. descriptor = {
  43577. colorAttachments: [ {
  43578. view: null
  43579. } ],
  43580. depthStencilAttachment: {
  43581. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  43582. }
  43583. };
  43584. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43585. if ( this.renderer.samples > 0 ) {
  43586. colorAttachment.view = this.colorBuffer.createView();
  43587. } else {
  43588. colorAttachment.resolveTarget = undefined;
  43589. }
  43590. this.defaultRenderPassdescriptor = descriptor;
  43591. }
  43592. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43593. if ( this.renderer.samples > 0 ) {
  43594. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  43595. } else {
  43596. colorAttachment.view = this.context.getCurrentTexture().createView();
  43597. }
  43598. return descriptor;
  43599. }
  43600. _getRenderPassDescriptor( renderContext ) {
  43601. const renderTarget = renderContext.renderTarget;
  43602. const renderTargetData = this.get( renderTarget );
  43603. let descriptors = renderTargetData.descriptors;
  43604. if ( descriptors === undefined ) {
  43605. descriptors = [];
  43606. renderTargetData.descriptors = descriptors;
  43607. }
  43608. if ( renderTargetData.width !== renderTarget.width ||
  43609. renderTargetData.height !== renderTarget.height ||
  43610. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  43611. renderTargetData.samples !== renderTarget.samples ||
  43612. descriptors.length !== renderTarget.textures.length
  43613. ) {
  43614. descriptors.length = 0;
  43615. // dispose
  43616. const onDispose = () => {
  43617. renderTarget.removeEventListener( 'dispose', onDispose );
  43618. this.delete( renderTarget );
  43619. };
  43620. renderTarget.addEventListener( 'dispose', onDispose );
  43621. }
  43622. let descriptor = descriptors[ renderContext.activeCubeFace ];
  43623. if ( descriptor === undefined ) {
  43624. const textures = renderContext.textures;
  43625. const colorAttachments = [];
  43626. for ( let i = 0; i < textures.length; i ++ ) {
  43627. const textureData = this.get( textures[ i ] );
  43628. const textureView = textureData.texture.createView( {
  43629. baseMipLevel: renderContext.activeMipmapLevel,
  43630. mipLevelCount: 1,
  43631. baseArrayLayer: renderContext.activeCubeFace,
  43632. dimension: GPUTextureViewDimension.TwoD
  43633. } );
  43634. let view, resolveTarget;
  43635. if ( textureData.msaaTexture !== undefined ) {
  43636. view = textureData.msaaTexture.createView();
  43637. resolveTarget = textureView;
  43638. } else {
  43639. view = textureView;
  43640. resolveTarget = undefined;
  43641. }
  43642. colorAttachments.push( {
  43643. view,
  43644. resolveTarget,
  43645. loadOp: GPULoadOp.Load,
  43646. storeOp: GPUStoreOp.Store
  43647. } );
  43648. }
  43649. const depthTextureData = this.get( renderContext.depthTexture );
  43650. const depthStencilAttachment = {
  43651. view: depthTextureData.texture.createView()
  43652. };
  43653. descriptor = {
  43654. colorAttachments,
  43655. depthStencilAttachment
  43656. };
  43657. descriptors[ renderContext.activeCubeFace ] = descriptor;
  43658. renderTargetData.width = renderTarget.width;
  43659. renderTargetData.height = renderTarget.height;
  43660. renderTargetData.samples = renderTarget.samples;
  43661. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  43662. }
  43663. return descriptor;
  43664. }
  43665. beginRender( renderContext ) {
  43666. const renderContextData = this.get( renderContext );
  43667. const device = this.device;
  43668. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43669. let occlusionQuerySet;
  43670. if ( occlusionQueryCount > 0 ) {
  43671. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  43672. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  43673. // Get a reference to the array of objects with queries. The renderContextData property
  43674. // can be changed by another render pass before the buffer.mapAsyc() completes.
  43675. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  43676. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  43677. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43678. //
  43679. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  43680. renderContextData.occlusionQuerySet = occlusionQuerySet;
  43681. renderContextData.occlusionQueryIndex = 0;
  43682. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43683. renderContextData.lastOcclusionObject = null;
  43684. }
  43685. let descriptor;
  43686. if ( renderContext.textures === null ) {
  43687. descriptor = this._getDefaultRenderPassDescriptor();
  43688. } else {
  43689. descriptor = this._getRenderPassDescriptor( renderContext );
  43690. }
  43691. this.initTimestampQuery( renderContext, descriptor );
  43692. descriptor.occlusionQuerySet = occlusionQuerySet;
  43693. const depthStencilAttachment = descriptor.depthStencilAttachment;
  43694. if ( renderContext.textures !== null ) {
  43695. const colorAttachments = descriptor.colorAttachments;
  43696. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  43697. const colorAttachment = colorAttachments[ i ];
  43698. if ( renderContext.clearColor ) {
  43699. colorAttachment.clearValue = renderContext.clearColorValue;
  43700. colorAttachment.loadOp = GPULoadOp.Clear;
  43701. colorAttachment.storeOp = GPUStoreOp.Store;
  43702. } else {
  43703. colorAttachment.loadOp = GPULoadOp.Load;
  43704. colorAttachment.storeOp = GPUStoreOp.Store;
  43705. }
  43706. }
  43707. } else {
  43708. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43709. if ( renderContext.clearColor ) {
  43710. colorAttachment.clearValue = renderContext.clearColorValue;
  43711. colorAttachment.loadOp = GPULoadOp.Clear;
  43712. colorAttachment.storeOp = GPUStoreOp.Store;
  43713. } else {
  43714. colorAttachment.loadOp = GPULoadOp.Load;
  43715. colorAttachment.storeOp = GPUStoreOp.Store;
  43716. }
  43717. }
  43718. //
  43719. if ( renderContext.depth ) {
  43720. if ( renderContext.clearDepth ) {
  43721. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  43722. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43723. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43724. } else {
  43725. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43726. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43727. }
  43728. }
  43729. if ( renderContext.stencil ) {
  43730. if ( renderContext.clearStencil ) {
  43731. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  43732. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43733. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43734. } else {
  43735. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43736. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43737. }
  43738. }
  43739. //
  43740. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  43741. const currentPass = encoder.beginRenderPass( descriptor );
  43742. //
  43743. renderContextData.descriptor = descriptor;
  43744. renderContextData.encoder = encoder;
  43745. renderContextData.currentPass = currentPass;
  43746. renderContextData.currentSets = { attributes: {} };
  43747. //
  43748. if ( renderContext.viewport ) {
  43749. this.updateViewport( renderContext );
  43750. }
  43751. if ( renderContext.scissor ) {
  43752. const { x, y, width, height } = renderContext.scissorValue;
  43753. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  43754. }
  43755. }
  43756. finishRender( renderContext ) {
  43757. const renderContextData = this.get( renderContext );
  43758. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43759. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  43760. renderContextData.registerBundlesPhase = false;
  43761. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  43762. }
  43763. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43764. renderContextData.currentPass.endOcclusionQuery();
  43765. }
  43766. renderContextData.currentPass.end();
  43767. if ( occlusionQueryCount > 0 ) {
  43768. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  43769. //
  43770. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  43771. if ( queryResolveBuffer === undefined ) {
  43772. queryResolveBuffer = this.device.createBuffer(
  43773. {
  43774. size: bufferSize,
  43775. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  43776. }
  43777. );
  43778. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  43779. }
  43780. //
  43781. const readBuffer = this.device.createBuffer(
  43782. {
  43783. size: bufferSize,
  43784. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43785. }
  43786. );
  43787. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  43788. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  43789. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  43790. renderContextData.occlusionQueryBuffer = readBuffer;
  43791. //
  43792. this.resolveOccludedAsync( renderContext );
  43793. }
  43794. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  43795. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  43796. //
  43797. if ( renderContext.textures !== null ) {
  43798. const textures = renderContext.textures;
  43799. for ( let i = 0; i < textures.length; i ++ ) {
  43800. const texture = textures[ i ];
  43801. if ( texture.generateMipmaps === true ) {
  43802. this.textureUtils.generateMipmaps( texture );
  43803. }
  43804. }
  43805. }
  43806. }
  43807. isOccluded( renderContext, object ) {
  43808. const renderContextData = this.get( renderContext );
  43809. return renderContextData.occluded && renderContextData.occluded.has( object );
  43810. }
  43811. async resolveOccludedAsync( renderContext ) {
  43812. const renderContextData = this.get( renderContext );
  43813. // handle occlusion query results
  43814. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  43815. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  43816. const occluded = new WeakSet();
  43817. renderContextData.currentOcclusionQueryObjects = null;
  43818. renderContextData.currentOcclusionQueryBuffer = null;
  43819. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  43820. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  43821. const results = new BigUint64Array( buffer );
  43822. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  43823. if ( results[ i ] !== BigInt( 0 ) ) {
  43824. occluded.add( currentOcclusionQueryObjects[ i ] );
  43825. }
  43826. }
  43827. currentOcclusionQueryBuffer.destroy();
  43828. renderContextData.occluded = occluded;
  43829. }
  43830. }
  43831. updateViewport( renderContext ) {
  43832. const { currentPass } = this.get( renderContext );
  43833. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  43834. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  43835. }
  43836. clear( color, depth, stencil, renderTargetData = null ) {
  43837. const device = this.device;
  43838. const renderer = this.renderer;
  43839. let colorAttachments = [];
  43840. let depthStencilAttachment;
  43841. let clearValue;
  43842. let supportsDepth;
  43843. let supportsStencil;
  43844. if ( color ) {
  43845. const clearColor = this.getClearColor();
  43846. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  43847. }
  43848. if ( renderTargetData === null ) {
  43849. supportsDepth = renderer.depth;
  43850. supportsStencil = renderer.stencil;
  43851. const descriptor = this._getDefaultRenderPassDescriptor();
  43852. if ( color ) {
  43853. colorAttachments = descriptor.colorAttachments;
  43854. const colorAttachment = colorAttachments[ 0 ];
  43855. colorAttachment.clearValue = clearValue;
  43856. colorAttachment.loadOp = GPULoadOp.Clear;
  43857. colorAttachment.storeOp = GPUStoreOp.Store;
  43858. }
  43859. if ( supportsDepth || supportsStencil ) {
  43860. depthStencilAttachment = descriptor.depthStencilAttachment;
  43861. }
  43862. } else {
  43863. supportsDepth = renderTargetData.depth;
  43864. supportsStencil = renderTargetData.stencil;
  43865. if ( color ) {
  43866. for ( const texture of renderTargetData.textures ) {
  43867. const textureData = this.get( texture );
  43868. const textureView = textureData.texture.createView();
  43869. let view, resolveTarget;
  43870. if ( textureData.msaaTexture !== undefined ) {
  43871. view = textureData.msaaTexture.createView();
  43872. resolveTarget = textureView;
  43873. } else {
  43874. view = textureView;
  43875. resolveTarget = undefined;
  43876. }
  43877. colorAttachments.push( {
  43878. view,
  43879. resolveTarget,
  43880. clearValue,
  43881. loadOp: GPULoadOp.Clear,
  43882. storeOp: GPUStoreOp.Store
  43883. } );
  43884. }
  43885. }
  43886. if ( supportsDepth || supportsStencil ) {
  43887. const depthTextureData = this.get( renderTargetData.depthTexture );
  43888. depthStencilAttachment = {
  43889. view: depthTextureData.texture.createView()
  43890. };
  43891. }
  43892. }
  43893. //
  43894. if ( supportsDepth ) {
  43895. if ( depth ) {
  43896. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43897. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  43898. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43899. } else {
  43900. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43901. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43902. }
  43903. }
  43904. //
  43905. if ( supportsStencil ) {
  43906. if ( stencil ) {
  43907. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43908. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  43909. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43910. } else {
  43911. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43912. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43913. }
  43914. }
  43915. //
  43916. const encoder = device.createCommandEncoder( {} );
  43917. const currentPass = encoder.beginRenderPass( {
  43918. colorAttachments,
  43919. depthStencilAttachment
  43920. } );
  43921. currentPass.end();
  43922. device.queue.submit( [ encoder.finish() ] );
  43923. }
  43924. // compute
  43925. beginCompute( computeGroup ) {
  43926. const groupGPU = this.get( computeGroup );
  43927. const descriptor = {};
  43928. this.initTimestampQuery( computeGroup, descriptor );
  43929. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  43930. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  43931. }
  43932. compute( computeGroup, computeNode, bindings, pipeline ) {
  43933. const { passEncoderGPU } = this.get( computeGroup );
  43934. // pipeline
  43935. const pipelineGPU = this.get( pipeline ).pipeline;
  43936. passEncoderGPU.setPipeline( pipelineGPU );
  43937. // bind groups
  43938. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  43939. const bindGroup = bindings[ i ];
  43940. const bindingsData = this.get( bindGroup );
  43941. passEncoderGPU.setBindGroup( i, bindingsData.group );
  43942. }
  43943. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  43944. const computeNodeData = this.get( computeNode );
  43945. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  43946. const { dispatchSize } = computeNodeData;
  43947. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  43948. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  43949. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  43950. } else {
  43951. dispatchSize.x = computeNode.dispatchCount;
  43952. }
  43953. passEncoderGPU.dispatchWorkgroups(
  43954. dispatchSize.x,
  43955. dispatchSize.y,
  43956. dispatchSize.z
  43957. );
  43958. }
  43959. finishCompute( computeGroup ) {
  43960. const groupData = this.get( computeGroup );
  43961. groupData.passEncoderGPU.end();
  43962. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  43963. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  43964. }
  43965. // render object
  43966. draw( renderObject, info ) {
  43967. const { object, geometry, context, pipeline } = renderObject;
  43968. const bindings = renderObject.getBindings();
  43969. const contextData = this.get( context );
  43970. const pipelineGPU = this.get( pipeline ).pipeline;
  43971. const currentSets = contextData.currentSets;
  43972. const renderObjectData = this.get( renderObject );
  43973. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  43974. const renderContextData = this.get( context );
  43975. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  43976. renderContextData.renderBundles.push( renderBundle );
  43977. return;
  43978. }
  43979. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  43980. // pipeline
  43981. if ( currentSets.pipeline !== pipelineGPU ) {
  43982. passEncoderGPU.setPipeline( pipelineGPU );
  43983. currentSets.pipeline = pipelineGPU;
  43984. }
  43985. // bind groups
  43986. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  43987. const bindGroup = bindings[ i ];
  43988. const bindingsData = this.get( bindGroup );
  43989. passEncoderGPU.setBindGroup( i, bindingsData.group );
  43990. }
  43991. // attributes
  43992. const index = renderObject.getIndex();
  43993. const hasIndex = ( index !== null );
  43994. // index
  43995. if ( hasIndex === true ) {
  43996. if ( currentSets.index !== index ) {
  43997. const buffer = this.get( index ).buffer;
  43998. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  43999. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  44000. currentSets.index = index;
  44001. }
  44002. }
  44003. // vertex buffers
  44004. const vertexBuffers = renderObject.getVertexBuffers();
  44005. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  44006. const vertexBuffer = vertexBuffers[ i ];
  44007. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  44008. const buffer = this.get( vertexBuffer ).buffer;
  44009. passEncoderGPU.setVertexBuffer( i, buffer );
  44010. currentSets.attributes[ i ] = vertexBuffer;
  44011. }
  44012. }
  44013. // occlusion queries - handle multiple consecutive draw calls for an object
  44014. if ( contextData.occlusionQuerySet !== undefined ) {
  44015. const lastObject = contextData.lastOcclusionObject;
  44016. if ( lastObject !== object ) {
  44017. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44018. passEncoderGPU.endOcclusionQuery();
  44019. contextData.occlusionQueryIndex ++;
  44020. }
  44021. if ( object.occlusionTest === true ) {
  44022. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  44023. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  44024. }
  44025. contextData.lastOcclusionObject = object;
  44026. }
  44027. }
  44028. // draw
  44029. const drawRange = renderObject.drawRange;
  44030. const firstVertex = drawRange.start;
  44031. const instanceCount = this.getInstanceCount( renderObject );
  44032. if ( instanceCount === 0 ) return;
  44033. if ( object.isBatchedMesh === true ) {
  44034. const starts = object._multiDrawStarts;
  44035. const counts = object._multiDrawCounts;
  44036. const drawCount = object._multiDrawCount;
  44037. const drawInstances = object._multiDrawInstances;
  44038. const bytesPerElement = index.bytesPerElement || 1;
  44039. for ( let i = 0; i < drawCount; i ++ ) {
  44040. const count = drawInstances ? drawInstances[ i ] : 1;
  44041. const firstInstance = count > 1 ? 0 : i;
  44042. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  44043. }
  44044. } else if ( hasIndex === true ) {
  44045. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  44046. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  44047. info.update( object, indexCount, instanceCount );
  44048. } else {
  44049. const positionAttribute = geometry.attributes.position;
  44050. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  44051. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  44052. info.update( object, vertexCount, instanceCount );
  44053. }
  44054. if ( this.renderer._currentRenderBundle ) {
  44055. const renderBundle = passEncoderGPU.finish();
  44056. renderObjectData.lastPipelineGPU = pipelineGPU;
  44057. renderObjectData.renderBundle = renderBundle;
  44058. renderObjectData.bundleEncoder = passEncoderGPU;
  44059. }
  44060. }
  44061. // cache key
  44062. needsRenderUpdate( renderObject ) {
  44063. const data = this.get( renderObject );
  44064. const { object, material } = renderObject;
  44065. const utils = this.utils;
  44066. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  44067. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  44068. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44069. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44070. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  44071. let needsUpdate = false;
  44072. if ( data.material !== material || data.materialVersion !== material.version ||
  44073. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  44074. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  44075. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  44076. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  44077. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  44078. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  44079. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  44080. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  44081. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  44082. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  44083. data.primitiveTopology !== primitiveTopology ||
  44084. data.clippingContextVersion !== renderObject.clippingContextVersion
  44085. ) {
  44086. data.material = material; data.materialVersion = material.version;
  44087. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  44088. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  44089. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  44090. data.colorWrite = material.colorWrite;
  44091. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  44092. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  44093. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  44094. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  44095. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  44096. data.sampleCount = sampleCount;
  44097. data.colorSpace = colorSpace;
  44098. data.colorFormat = colorFormat;
  44099. data.depthStencilFormat = depthStencilFormat;
  44100. data.primitiveTopology = primitiveTopology;
  44101. data.clippingContextVersion = renderObject.clippingContextVersion;
  44102. needsUpdate = true;
  44103. }
  44104. return needsUpdate;
  44105. }
  44106. getRenderCacheKey( renderObject ) {
  44107. const { object, material } = renderObject;
  44108. const utils = this.utils;
  44109. const renderContext = renderObject.context;
  44110. return [
  44111. material.transparent, material.blending, material.premultipliedAlpha,
  44112. material.blendSrc, material.blendDst, material.blendEquation,
  44113. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  44114. material.colorWrite,
  44115. material.depthWrite, material.depthTest, material.depthFunc,
  44116. material.stencilWrite, material.stencilFunc,
  44117. material.stencilFail, material.stencilZFail, material.stencilZPass,
  44118. material.stencilFuncMask, material.stencilWriteMask,
  44119. material.side,
  44120. utils.getSampleCountRenderContext( renderContext ),
  44121. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  44122. utils.getPrimitiveTopology( object, material ),
  44123. renderObject.clippingContextVersion
  44124. ].join();
  44125. }
  44126. // textures
  44127. createSampler( texture ) {
  44128. this.textureUtils.createSampler( texture );
  44129. }
  44130. destroySampler( texture ) {
  44131. this.textureUtils.destroySampler( texture );
  44132. }
  44133. createDefaultTexture( texture ) {
  44134. this.textureUtils.createDefaultTexture( texture );
  44135. }
  44136. createTexture( texture, options ) {
  44137. this.textureUtils.createTexture( texture, options );
  44138. }
  44139. updateTexture( texture, options ) {
  44140. this.textureUtils.updateTexture( texture, options );
  44141. }
  44142. generateMipmaps( texture ) {
  44143. this.textureUtils.generateMipmaps( texture );
  44144. }
  44145. destroyTexture( texture ) {
  44146. this.textureUtils.destroyTexture( texture );
  44147. }
  44148. copyTextureToBuffer( texture, x, y, width, height ) {
  44149. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  44150. }
  44151. initTimestampQuery( renderContext, descriptor ) {
  44152. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44153. const renderContextData = this.get( renderContext );
  44154. if ( ! renderContextData.timeStampQuerySet ) {
  44155. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  44156. // beginning and one for the end of compute pass execution.
  44157. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  44158. const timestampWrites = {
  44159. querySet: timeStampQuerySet,
  44160. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  44161. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  44162. };
  44163. Object.assign( descriptor, {
  44164. timestampWrites,
  44165. } );
  44166. renderContextData.timeStampQuerySet = timeStampQuerySet;
  44167. }
  44168. }
  44169. // timestamp utils
  44170. prepareTimestampBuffer( renderContext, encoder ) {
  44171. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44172. const renderContextData = this.get( renderContext );
  44173. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  44174. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  44175. renderContextData.currentTimestampQueryBuffers = {
  44176. resolveBuffer: this.device.createBuffer( {
  44177. label: 'timestamp resolve buffer',
  44178. size: size,
  44179. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  44180. } ),
  44181. resultBuffer: this.device.createBuffer( {
  44182. label: 'timestamp result buffer',
  44183. size: size,
  44184. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  44185. } ),
  44186. isMappingPending: false,
  44187. };
  44188. }
  44189. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44190. if ( isMappingPending === true ) return;
  44191. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  44192. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  44193. }
  44194. async resolveTimestampAsync( renderContext, type = 'render' ) {
  44195. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44196. const renderContextData = this.get( renderContext );
  44197. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  44198. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44199. if ( isMappingPending === true ) return;
  44200. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  44201. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  44202. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  44203. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  44204. this.renderer.info.updateTimestamp( type, duration );
  44205. resultBuffer.unmap();
  44206. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  44207. } );
  44208. }
  44209. // node builder
  44210. createNodeBuilder( object, renderer ) {
  44211. return new WGSLNodeBuilder( object, renderer );
  44212. }
  44213. // program
  44214. createProgram( program ) {
  44215. const programGPU = this.get( program );
  44216. programGPU.module = {
  44217. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  44218. entryPoint: 'main'
  44219. };
  44220. }
  44221. destroyProgram( program ) {
  44222. this.delete( program );
  44223. }
  44224. // pipelines
  44225. createRenderPipeline( renderObject, promises ) {
  44226. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  44227. }
  44228. createComputePipeline( computePipeline, bindings ) {
  44229. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  44230. }
  44231. createBundleEncoder( renderContext, renderObject ) {
  44232. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  44233. }
  44234. // bindings
  44235. createBindings( bindGroup ) {
  44236. this.bindingUtils.createBindings( bindGroup );
  44237. }
  44238. updateBindings( bindGroup ) {
  44239. this.bindingUtils.createBindings( bindGroup );
  44240. }
  44241. updateBinding( binding ) {
  44242. this.bindingUtils.updateBinding( binding );
  44243. }
  44244. // attributes
  44245. createIndexAttribute( attribute ) {
  44246. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44247. }
  44248. createAttribute( attribute ) {
  44249. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44250. }
  44251. createStorageAttribute( attribute ) {
  44252. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44253. }
  44254. updateAttribute( attribute ) {
  44255. this.attributeUtils.updateAttribute( attribute );
  44256. }
  44257. destroyAttribute( attribute ) {
  44258. this.attributeUtils.destroyAttribute( attribute );
  44259. }
  44260. // canvas
  44261. updateSize() {
  44262. this.colorBuffer = this.textureUtils.getColorBuffer();
  44263. this.defaultRenderPassdescriptor = null;
  44264. }
  44265. // utils public
  44266. getMaxAnisotropy() {
  44267. return 16;
  44268. }
  44269. hasFeature( name ) {
  44270. return this.device.features.has( name );
  44271. }
  44272. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  44273. let dstX = 0;
  44274. let dstY = 0;
  44275. let srcX = 0;
  44276. let srcY = 0;
  44277. let srcWidth = srcTexture.image.width;
  44278. let srcHeight = srcTexture.image.height;
  44279. if ( srcRegion !== null ) {
  44280. srcX = srcRegion.x;
  44281. srcY = srcRegion.y;
  44282. srcWidth = srcRegion.width;
  44283. srcHeight = srcRegion.height;
  44284. }
  44285. if ( dstPosition !== null ) {
  44286. dstX = dstPosition.x;
  44287. dstY = dstPosition.y;
  44288. }
  44289. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  44290. const sourceGPU = this.get( srcTexture ).texture;
  44291. const destinationGPU = this.get( dstTexture ).texture;
  44292. encoder.copyTextureToTexture(
  44293. {
  44294. texture: sourceGPU,
  44295. mipLevel: level,
  44296. origin: { x: srcX, y: srcY, z: 0 }
  44297. },
  44298. {
  44299. texture: destinationGPU,
  44300. mipLevel: level,
  44301. origin: { x: dstX, y: dstY, z: 0 }
  44302. },
  44303. [
  44304. srcWidth,
  44305. srcHeight
  44306. ]
  44307. );
  44308. this.device.queue.submit( [ encoder.finish() ] );
  44309. }
  44310. copyFramebufferToTexture( texture, renderContext ) {
  44311. const renderContextData = this.get( renderContext );
  44312. const { encoder, descriptor } = renderContextData;
  44313. let sourceGPU = null;
  44314. if ( renderContext.renderTarget ) {
  44315. if ( texture.isDepthTexture ) {
  44316. sourceGPU = this.get( renderContext.depthTexture ).texture;
  44317. } else {
  44318. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  44319. }
  44320. } else {
  44321. if ( texture.isDepthTexture ) {
  44322. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  44323. } else {
  44324. sourceGPU = this.context.getCurrentTexture();
  44325. }
  44326. }
  44327. const destinationGPU = this.get( texture ).texture;
  44328. if ( sourceGPU.format !== destinationGPU.format ) {
  44329. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  44330. return;
  44331. }
  44332. renderContextData.currentPass.end();
  44333. encoder.copyTextureToTexture(
  44334. {
  44335. texture: sourceGPU,
  44336. origin: { x: 0, y: 0, z: 0 }
  44337. },
  44338. {
  44339. texture: destinationGPU
  44340. },
  44341. [
  44342. texture.image.width,
  44343. texture.image.height
  44344. ]
  44345. );
  44346. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  44347. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  44348. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  44349. }
  44350. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44351. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44352. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  44353. renderContextData.currentSets = { attributes: {} };
  44354. }
  44355. }
  44356. /*
  44357. const debugHandler = {
  44358. get: function ( target, name ) {
  44359. // Add |update
  44360. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  44361. return target[ name ];
  44362. }
  44363. };
  44364. */
  44365. class WebGPURenderer extends Renderer {
  44366. constructor( parameters = {} ) {
  44367. let BackendClass;
  44368. if ( parameters.forceWebGL ) {
  44369. BackendClass = WebGLBackend;
  44370. } else if ( WebGPU.isAvailable() ) {
  44371. BackendClass = WebGPUBackend;
  44372. } else {
  44373. BackendClass = WebGLBackend;
  44374. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  44375. }
  44376. const backend = new BackendClass( parameters );
  44377. //super( new Proxy( backend, debugHandler ) );
  44378. super( backend, parameters );
  44379. this.isWebGPURenderer = true;
  44380. }
  44381. }
  44382. const _material = /*@__PURE__*/ new NodeMaterial();
  44383. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  44384. class PostProcessing {
  44385. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  44386. this.renderer = renderer;
  44387. this.outputNode = outputNode;
  44388. this.outputColorTransform = true;
  44389. this.needsUpdate = true;
  44390. }
  44391. render() {
  44392. this.update();
  44393. const renderer = this.renderer;
  44394. const toneMapping = renderer.toneMapping;
  44395. const outputColorSpace = renderer.outputColorSpace;
  44396. renderer.toneMapping = NoToneMapping;
  44397. renderer.outputColorSpace = LinearSRGBColorSpace;
  44398. //
  44399. _quadMesh.render( renderer );
  44400. //
  44401. renderer.toneMapping = toneMapping;
  44402. renderer.outputColorSpace = outputColorSpace;
  44403. }
  44404. update() {
  44405. if ( this.needsUpdate === true ) {
  44406. const renderer = this.renderer;
  44407. const toneMapping = renderer.toneMapping;
  44408. const outputColorSpace = renderer.outputColorSpace;
  44409. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  44410. _quadMesh.material.needsUpdate = true;
  44411. this.needsUpdate = false;
  44412. }
  44413. }
  44414. async renderAsync() {
  44415. this.update();
  44416. const renderer = this.renderer;
  44417. const toneMapping = renderer.toneMapping;
  44418. const outputColorSpace = renderer.outputColorSpace;
  44419. renderer.toneMapping = NoToneMapping;
  44420. renderer.outputColorSpace = LinearSRGBColorSpace;
  44421. //
  44422. await _quadMesh.renderAsync( renderer );
  44423. //
  44424. renderer.toneMapping = toneMapping;
  44425. renderer.outputColorSpace = outputColorSpace;
  44426. }
  44427. }
  44428. class StorageTexture extends Texture {
  44429. constructor( width = 1, height = 1 ) {
  44430. super();
  44431. this.image = { width, height };
  44432. this.magFilter = LinearFilter;
  44433. this.minFilter = LinearFilter;
  44434. this.isStorageTexture = true;
  44435. }
  44436. }
  44437. class StorageBufferAttribute extends BufferAttribute {
  44438. constructor( array, itemSize, typeClass = Float32Array ) {
  44439. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  44440. super( array, itemSize );
  44441. this.isStorageBufferAttribute = true;
  44442. }
  44443. }
  44444. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  44445. constructor( array, itemSize, typeClass = Float32Array ) {
  44446. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  44447. super( array, itemSize );
  44448. this.isStorageInstancedBufferAttribute = true;
  44449. }
  44450. }
  44451. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  44452. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  44453. revision: REVISION,
  44454. } } ) );
  44455. }
  44456. if ( typeof window !== 'undefined' ) {
  44457. if ( window.__THREE__ ) {
  44458. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  44459. } else {
  44460. window.__THREE__ = REVISION;
  44461. }
  44462. }
  44463. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, 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, BatchNode, BatchedMesh, BlendModeNode, BloomNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CheckerNode, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorAdjustmentNode, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, CondNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, 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, DiscardNode, 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, 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, HashNode, 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, 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, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, Lut3DNode, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, 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, NodeKeywords, 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, OperatorNode, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, PackingNode, 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, RotateUVNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, 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, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureBicubicNode, TextureLoader, TextureNode, TextureSizeNode, TimerNode, ToneMappingNode, TorusGeometry, TorusKnotGeometry, TransitionNode, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UniformsNode, 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, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, all, alphaT, anamorphic, and, anisotropy, anisotropyB, anisotropyT, any, ao, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, batch, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bloom, blur, bmat2, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createCanvasElement, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, denoise, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, discard, 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, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat2, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightTargetDirection, lightingContext, lights, lightsNode, linearDepth, linearToColorSpace, linearTosRGB, log, log2, loop, luminance, lut3D, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, 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, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToViewZ, pixelationPass, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rgbShift, rotate, rotateUV, roughness, round, rtt, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, setCurrentStack, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, sobel, specularColor, split, spritesheetUV, sqrt, stack, step, storage, storageObject, storageTexture, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, threshold, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transition, transpose, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat2, umat3, umat4, uniform, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor };